Build a Voice Agent or WhatsApp Bot using Twilio
Overview
This guide shows you how to build a real-time conversational agent with Twilio and Sarvam AI, on either of two channels: a phone voice agent that answers inbound calls, or a WhatsApp bot that replies to text and voice messages. Both use Sarvam AI for speech-to-text, the LLM, and text-to-speech, and are a great starting point for IVR replacements, customer support lines, and conversational agents in Indian languages.
What Youโll Build
Pick the channel that matches your use case:
Answers inbound phone calls on a Twilio number, listens to callers in multiple Indian languages, and responds back in a natural-sounding voice, in real time. Built with Twilio Media Streams and Pipecat.
Replies to WhatsApp text messages and voice notes on a Twilio WhatsApp number, transcribing voice notes and replying with text (or optionally, a spoken voice note).
Part 1: Phone Call Agent (Telephony)
A voice agent that can:
- Answer inbound phone calls on a Twilio number
- Listen to callers speaking, in multiple Indian languages
- Understand and process what they say
- Respond back in a natural-sounding voice, over the phone
Quick Overview
- Get API keys (Twilio, Sarvam)
- Install packages:
pip install "pipecat-ai[websocket,sarvam]" python-dotenv - Create a
.envfile with your API keys - Write about 80 lines of Python code
- Point a Twilio phone number at your agent using TwiML
- Call your Twilio number
Quick Start
1. Prerequisites
- Python 3.9 or higher
- ngrok, to expose your local server during development
- Accounts and keys from:
2. Install Dependencies
macOS/Linux
Windows
3. Create Environment File
Create a file named .env in your project folder:
Then replace each placeholder with your real credentials from the Sarvam dashboard and the Twilio Console.
TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN arenโt optional here. Pipecatโs Twilio transport uses them to authenticate with Twilioโs REST API and to hang up the call cleanly when your agent ends the conversation.
4. Write Your Agent
Create agent.py:
Thereโs no manual try/except around stt, tts, or llm here on purpose. Those lines just construct pipeline processors; the actual Sarvam API calls happen later, streamed frame-by-frame while the pipeline runs, and Pipecat already catches failures at that layer and surfaces them as ErrorFrames (logged via loguru) instead of raising into your code. Wrapping the setup code in try/except wouldnโt protect anything a real call could fail on.
5. Configure Twilio to Reach Your Agent
Twilio needs a public wss:// URL to stream call audio to. For local development, expose your agent with ngrok.
Start ngrok:
ngrok prints a forwarding URL that looks like https://xxxx.ngrok-free.app. Youโll turn this into a wss:// URL in the next step.
The domain suffix ngrok assigns varies per account โ you may see ngrok-free.app, ngrok-free.dev, or the older ngrok.io, regardless of whether youโre on macOS, Windows, or Linux. Always use whatever URL ngrok actually prints, not the placeholder shown here.
Free ngrok URLs change every time you restart ngrok. If your agent stops receiving calls, check whether the URL in your TwiML Bin still matches the one ngrok is currently printing.
Create a TwiML Bin:
TwiML Bins arenโt in the Twilio Consoleโs left sidebar by default. The fastest way to reach them is to click the search bar at the top of the console and type โTwiML Binsโ.
- Open the Twilio Console and search for TwiML Bins using the search bar at the top (or find it under Developer Tools in the sidebar)
- Click Create new TwiML Bin, give it a friendly name, and paste the following, replacing the domain with your own ngrok URL:
- Click Create to save the bin
Assign it to your phone number:
- Go to Numbers & Senders, then Phone Numbers, and select your number
- Open its configuration/voice settings tab
- Find the setting for what happens when a call comes in, and set it to use your TwiML Bin (Twilio has labeled this option TwiML, TwiML Bin, or similar depending on your console version)
- Save
Twilio has redesigned this pageโs tabs and section names more than once (you may see Configuration, Configure, or Configuration Details; Voice & Fax, Voice Configuration, or Voice and emergency calling). The setting you want is always the one controlling what happens when a call comes in. If you canโt find it, Twilioโs own Getting Started with TwiML Bins guide has current screenshots.
6. Run Your Agent
This starts a local FastAPI server, via Pipecatโs development runner, that accepts Twilioโs Media Streams WebSocket connection at /ws.
7. Test Your Agent
Call your Twilio phone number from any phone. Your voice agent will pick up and start the conversation.
Customization Examples
Example 1: Hindi Voice Agent
language, voice, and language_code are Settings fields, not constructor keyword arguments. Passing them directly to SarvamSTTService(...) or SarvamTTSService(...) raises a TypeError on current versions of pipecat-ai. Only mode (STT) and api_key stay outside settings.
Example 2: Tamil Voice Agent
Example 3: Multilingual Agent (Auto-detect)
Use language="unknown" for support lines where callers might speak any of several languages. Sarvam auto-detects the spoken language per utterance, so the same agent can handle a Hindi caller followed by a Tamil caller without any code changes.
Example 4: Speech-to-English Agent (Saaras)
Saarika transcribes speech to text in the same language. Saaras translates speech directly to English text. Use Saaras when the caller speaks an Indian language but you want to process and respond in English.
Saaras auto-detects the source language (Hindi, Tamil, and so on) and translates spoken content directly to English text, which makes Indian-language speech usable by English-based LLMs.
Available Options
Language Codes
Speaker Voices (Bulbul v3)
Male (23): Shubh (default), Aditya, Rahul, Rohan, Amit, Dev, Ratan, Varun, Manan, Sumit, Kabir, Aayan, Ashutosh, Advait, Anand, Tarun, Sunny, Mani, Gokul, Vijay, Mohit, Rehan, Soham
Female (14): Ritu, Priya, Neha, Pooja, Simran, Kavya, Ishita, Shreya, Roopa, Tanya, Shruti, Suhani, Kavitha, Rupali
TTS Additional Parameters
You can customize the TTS service with additional parameters:
Twilio Media Streams always carry 8kHz mono audio. You donโt need to touch sample_rate on SarvamTTSService for this: Pipecat resamples the TTS output to match the audio_out_sample_rate set in PipelineParams automatically.
Understanding the Call Flow
- Caller dials your Twilio number. Twilio answers using the TwiML Bin and opens a WebSocket (Media Stream) to your agent.
- Transport Input: Your Pipecat transport receives the callerโs audio over the WebSocket, and hands it to STT.
- STT (Speech-to-Text): Converts audio to text using Sarvamโs Saarika or Saaras, and the context aggregator adds it to the conversation context.
- LLM: Generates a response using Sarvam.
- TTS (Text-to-Speech): Converts the response to audio using Sarvamโs Bulbul.
- Transport Output: Streams the audio back over the WebSocket, and Twilio plays it to the caller, while the context aggregator saves the assistantโs response to context.
Pro Tips
- Use
language="unknown"to automatically detect the callerโs language. This works well for multilingual support lines, but transcription accuracy is slightly lower than when you specify the exact language code, so prefer an explicit code whenever you already know which language the caller will use. - Sarvamโs models understand code-mixing, so your agent can naturally handle Hinglish, Tanglish, and other mixed languages, which is common on real support calls.
- Use
sarvam-105bfor the LLM step.
Log the transcript from context_aggregator if you want post-call analytics. Writing it to a file or database is cheap and wonโt slow down the live pipeline.
Troubleshooting
Call connects but thereโs no audio. Confirm the TwiML <Stream url> uses wss://, not wss:/ or https://, and that it points at your current ngrok URL. Free ngrok URLs change on every restart.
Call drops immediately. Check that TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN are set correctly in .env. The Twilio serializer needs both to manage the call.
API key errors. Make sure all keys are in your .env file and that the file sits in the same directory as agent.py.
Module not found. Re-run the install command for your operating system (see Step 2 above).
Poor transcription. Try language="unknown" for auto-detection, or set the exact language code (en-IN, hi-IN, and so on) if you already know it.
Choppy or robotic audio. Make sure audio_in_sample_rate and audio_out_sample_rate are both set to 8000 in PipelineParams. Twilio Media Streams donโt support other rates, and a mismatch causes distorted playback.
Part 2: WhatsApp Bot
A WhatsApp bot that can:
- Receive inbound WhatsApp messages, text or voice notes, on a Twilio WhatsApp number
- Transcribe voice notes in multiple Indian languages
- Understand and process what the user said or typed
- Reply with text, or optionally, a spoken voice note
Unlike the phone agent, this path doesnโt use Pipecat. WhatsApp messages arrive as one-off HTTP webhook requests rather than a continuous audio stream, so a small web server (Flask) that calls Sarvamโs APIs directly is all you need.
WhatsApp Bot: Quick Overview
- Get API keys (Twilio, Sarvam)
- Install packages:
pip install flask twilio sarvamai python-dotenv requests - Create a
.envfile with your API keys - Write about 50 lines of Python code
- From WhatsApp, send the Sandboxโs join code to opt your number in
- Point the Sandboxโs webhook at your agent
- Message your Twilio WhatsApp number
WhatsApp Bot: Quick Start
Step 1: Prerequisites
- Python 3.9 or higher
- ngrok, to expose your local server during development
- Accounts and keys from:
This guide uses the Twilio Sandbox for WhatsApp, a free, instant way to test WhatsApp messaging in development. Moving to production requires registering a WhatsApp Sender, which involves Meta Business verification and can take a few days. See Twilioโs WhatsApp docs when youโre ready to go live.
Step 2: Install Dependencies
Step 3: Create Environment File
Create a file named .env in your project folder:
Then replace each placeholder with your real credentials from the Sarvam dashboard and the Twilio Console.
TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN are used to authenticate when downloading voice-note media from Twilio, which requires HTTP Basic Auth with these credentials.
Step 4: Write Your Agent
Create whatsapp_agent.py:
WhatsApp voice notes arrive as OGG/Opus audio, and Sarvamโs speech-to-text REST API accepts that format directly, no transcoding needed. Voice notes longer than 30 seconds will fail on this endpoint; for longer audio, switch to the Batch STT API.
The try/except around the webhook body exists because this endpoint is a system boundary โ it calls two external services (Twilioโs media download, Sarvamโs API) over the network, either of which can fail independently of your code. Replying with a short apology keeps the conversation alive instead of leaving the sender with no response at all.
This example trusts every request to /whatsapp. Before going to production, validate the X-Twilio-Signature header on each request (using twilio.request_validator.RequestValidator) so that requests canโt be spoofed as coming from Twilio.
Step 5: Configure Twilio to Reach Your Agent
Start ngrok:
ngrok prints a forwarding URL that looks like https://xxxx.ngrok-free.app.
5a. Register your WhatsApp number with the Sandbox (required first)
The Sandbox is a shared Twilio number (+1 XXX XXX XXXX, shown on the console page below), used by every developer testing WhatsApp. Twilio only forwards messages from phone numbers that have explicitly opted in to your sandbox โ nothing reaches your webhook until this step is done, no matter how correctly your code or webhook URL is set up.
- Open the Twilio Console and go to Messaging โ Try it out โ Send a WhatsApp message (or search for โWhatsApp sandboxโ in the console search bar). This page shows the sandbox number and your accountโs unique join code, for example
join happy-elephant. - From the WhatsApp app on your phone, send that exact
join <your-code>message as a normal WhatsApp text to the sandbox number shown on that page (or scan the QR code Twilio shows, which pre-fills this message for you). - Twilio replies confirming youโre connected. Your number is now opted in to your sandbox.
This opt-in is per phone number, not per account. Anyone else who wants to message your bot (a teammate, a demo user) must send the same join <code> message from their own WhatsApp number first โ thereโs no way around this for the Sandbox.
The opt-in expires 3 days after joining (or after the last message exchanged). If your bot suddenly stops receiving messages from a number that worked before, re-send the join <code> message from that WhatsApp number.
5b. Point the Sandbox at your webhook
- Still on the Sandbox settings page, find When a message comes in
- Set it to your ngrok URL plus
/whatsapp(for example,https://xxxx.ngrok-free.app/whatsapp), with the method set to HTTP POST - Save
Free ngrok URLs change every time you restart ngrok. If your bot stops responding, check whether the webhook URL in the sandbox settings still matches the one ngrok is currently printing.
Step 6: Run and Test Your Agent
Send a text message, or a voice note, to your Twilio WhatsApp number from any phone. Your bot will transcribe and reply within a few seconds.
Reply with a Voice Note (Optional)
To have your bot speak its reply back as a voice note instead of (or alongside) text, synthesize the reply with Sarvamโs text-to-speech API, serve the audio file from your own Flask app, and attach it to the TwiML response as media:
request.host_url resolves to your current ngrok URL automatically, since ngrok forwards the original Host header, so you donโt need to hardcode it here.
Synthesizing the voice note is wrapped in its own try/except, separate from the outer one, so a TTS failure only drops the audio attachment โ the sender still gets the text reply instead of the generic apology.
WhatsApp only renders a native, waveform voice-note bubble for OGG/Opus audio. A .wav reply still plays back fine, just as a regular audio attachment rather than a voice-note bubble.
You can use the same language codes and speaker voices listed above for the phone agent when customizing STT and TTS for your WhatsApp bot.
Understanding the Message Flow
- User sends a message. Text or a voice note, to your Twilio WhatsApp number. Twilio POSTs it to your
/whatsappwebhook. - STT (Speech-to-Text): If the message is a voice note, your agent downloads it and converts it to text using Sarvamโs Saaras.
- LLM: Generates a reply using Sarvam.
- TTS (Text-to-Speech, optional): Converts the reply to audio using Sarvamโs Bulbul, if youโve added voice-note replies.
- Response: Your agent returns TwiML, and Twilio delivers the reply, text and/or audio, back to the user on WhatsApp.
WhatsApp Bot: Pro Tips
- Use
language_code="unknown"in STT to auto-detect whichever language the sender types or speaks in. - Keep system prompts explicit about reply length (as in the example) โ WhatsApp messages are capped at 1600 characters by Twilio, and short replies also read better in a chat window.
- For production traffic, move off the Sandbox to a verified WhatsApp Sender, and validate Twilioโs request signature on every webhook call.
WhatsAppโs Business Platform only allows free-form replies within 24 hours of the userโs last message. Outside that window, you need a pre-approved template message โ this is a WhatsApp policy that neither Sarvam nor Twilio can bypass.
WhatsApp Bot: Troubleshooting
Webhook never gets called. First confirm the sending number actually joined the sandbox (Step 5a) โ Twilio silently drops messages from numbers that havenโt opted in, and this is the most common reason nothing reaches your server. Then check that the sandboxโs โWhen a message comes inโ URL matches your current ngrok URL exactly, ends in /whatsapp, and uses HTTPS.
Works for a few days, then stops. The sandbox opt-in expires 3 days after joining (or after the last message exchanged). Re-send the join <code> message from that WhatsApp number to reconnect.
No response outside a fresh conversation. WhatsAppโs 24-hour session-messaging window has closed; youโll need a pre-approved template message to reach the user again.
Voice note transcription fails or comes back empty. Confirm MediaContentType0 starts with audio/, and that youโre passing your Twilio Account SID and Auth Token as Basic Auth when downloading MediaUrl0 (Twilio media URLs return 401 without it).
Voice notes over 30 seconds fail. The synchronous speech-to-text endpoint caps input at 30 seconds. Switch to the Batch STT API for longer voice notes.
Module not found. Re-run the install command from Step 2 above.
Additional Resources
- Sarvam AI Documentation
- Pipecat Documentation
- Pipecat Sarvam LLM Service
- Pipecat Twilio Serializer Reference
- Twilio Media Streams Documentation
- Twilio Getting Started with TwiML Bins
- Twilio Sandbox for WhatsApp
- Twilio WhatsApp API Overview
- Twilio Python Helper Library
- Twilio Console
Need Help?
- Sarvam Support: developer@sarvam.ai
- Community: Join the Discord Community
Happy Building!