Build an AI phone agent that answers real calls, using Twilio Voice and Media Streams for telephony and AssemblyAI-STT-3.7-Realtime-Agent for real-time speech-to-text.
The detail that keeps this build short is the audio format. Twilio streams 8 kHz μ-law (mulaw) audio, and AssemblyAI's streaming API accepts encoding=pcm_mulaw at sample_rate=8000 directly, so there's no resampling and no format conversion. AssemblyAI Text-to-Speech closes the loop in the same format: ask it for pcm_mulaw at 8,000 Hz, and the agent's replies go back to Twilio with no conversion on your side either.
Architecture
Incoming call
│
Twilio Voice
│ TwiML → open Media Stream WebSocket
▼
Your server (/media-stream WebSocket)
│ ▲
│ mulaw 8 kHz audio │ synthesized mulaw 8 kHz audio
▼ │
AssemblyAI-STT-3.7 AssemblyAI TTS
Realtime Agent ▲
│ transcript + turn end │ reply text
▼ │
OpenAI GPT-4o ────────────────┘Why AssemblyAI-STT-3.7-Realtime-Agent for phone calls?
Phone agents fail on the parts of a call that carry the most information: the policy number read out in chunks, the quiet "yes" after a confirmation question, the TV in the background. STT-3.7-Realtime-Agent is the model the AssemblyAI docs recommend for voice agents, and it's trained on real voice-agent and telephony conversations in which every speaker's role is labeled.
On AssemblyAI's benchmarks, compared with Universal-3.6 Pro Realtime:
| What goes wrong on a call (vs Universal-3.6 Pro Realtime) | Universal-3.6 Pro Realtime | AssemblyAI-STT-3.7-Realtime-Agent |
|---|---|---|
| Number errors (Voice Code Bench) | 11.28% | 2.27% (−80%) |
| Digit-string errors | 23.6% | 3.6% |
| Money-amount errors | 13.3% | 0.0% |
| Recordings with at least one missed entity | 71.3% | 37.0% |
| Words added while the caller is silent (per 1,000 words) | 2.53 | 1.34 (−47%) |
| One- and two-word replies dropped | 0.29% | 0.18% (−38%) |
| False end-of-turn events | — | −12% |
Source: the AssemblyAI-STT-3.7-Realtime-Agent research post, Nov 2026. The voice-agent benchmark is 12,460 scripted scenarios from 522 speakers, recorded as telephony audio with no, low or heavy background noise. Number and digit figures come from Voice Code Bench, a set dense in numbers and codes.
Background speech falls by about half; it doesn't go to zero. Fewer false end-of-turn events means fewer callers cut off mid-thought.
Prerequisites
- Python 3.11+
- An AssemblyAI API key (free account). One key covers speech-to-text and text-to-speech.
- A Twilio account with a phone number
- An OpenAI API key
- ngrok, for local development
Quick start
git clone https://github.com/kelsey-aai/twilio-phone-agent-assemblyai
cd twilio-phone-agent-assemblyai
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt # includes assemblyai>=1.10.1
cp .env.example .env
# Add ASSEMBLYAI_API_KEY and OPENAI_API_KEY to .env
uvicorn server:app --host 0.0.0.0 --port 8000
ngrok http 8000Configure Twilio
- Open the Twilio Console and go to Phone Numbers.
- Select your number, then Voice Configuration.
- Set A call comes in to Webhook:
https://your-ngrok-url.ngrok.io/incoming-call. - Call your Twilio number.
The /incoming-call route returns TwiML that tells Twilio to open a bidirectional Media Stream to your server:
from fastapi import FastAPI, Request
from fastapi.responses import Response
app = FastAPI()
@app.post("/incoming-call")
async def incoming_call(request: Request):
"""Return TwiML that opens a Media Streams WebSocket to this server."""
host = request.headers.get("host", "your-ngrok-url.ngrok.io")
twiml = f"""<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Connect>
<Stream url="wss://{host}/media-stream" />
</Connect>
</Response>"""
return Response(content=twiml, media_type="application/xml")AssemblyAI WebSocket parameters for Twilio
Twilio's Media Streams docs fix the inbound format: audio/x-mulaw at a sample rate of 8000, one channel. Match it on the AssemblyAI side and forward Twilio's audio as-is:
# The API key goes in the Authorization header, not the URL:
# the `token` query param is only for temporary streaming tokens.
ASSEMBLYAI_WS_URL = (
"wss://streaming.assemblyai.com/v3/ws"
"?speech_model=assemblyai-stt-3-7-realtime-agent"
"&encoding=pcm_mulaw" # must match Twilio's audio format
"&sample_rate=8000" # must match Twilio's 8 kHz stream
)Open the connection with your key in the Authorization header, then decode each Twilio media event and send the raw bytes:
import base64
import json
import os
import websockets
async def bridge(twilio_ws):
"""Forward Twilio's mu-law audio to AssemblyAI unchanged."""
async with websockets.connect(
ASSEMBLYAI_WS_URL,
additional_headers={"Authorization": os.environ["ASSEMBLYAI_API_KEY"]},
) as aai_ws:
async for raw in twilio_ws.iter_text():
msg = json.loads(raw)
if msg.get("event") == "media":
# Twilio sends base64-encoded mu-law; AssemblyAI wants the raw bytes
await aai_ws.send(base64.b64decode(msg["media"]["payload"]))
elif msg.get("event") == "stop":
await aai_ws.send(json.dumps({"type": "Terminate"}))
breakThere's no min_turn_silence or max_turn_silence on that URL, on purpose. The turn detection defaults now come from the mode preset (balanced unless you set one), and entity-aware endpointing holds a turn open while the caller reads out a phone number, code or email, without a longer silence timer. If your callers are deliberate speakers, add &mode=max_accuracy to the URL.
When your agent has just asked for something long, such as a card number, raise min_turn_silence for that one answer, then re-apply the mode to restore its defaults:
import json
async def capture_long_entity(aai_ws):
"""Give the caller extra room for one answer, then restore the defaults."""
await aai_ws.send(json.dumps({"type": "UpdateConfiguration", "min_turn_silence": 1000}))
async def restore_defaults(aai_ws):
await aai_ws.send(json.dumps({"type": "UpdateConfiguration", "mode": "balanced"}))Previous model: universal-3-6-pro (Universal-3.6 Pro Realtime) is still fully supported. Moving a Twilio agent to 3.7 is a one-value change to speech_model; the encoding, sample rate and message types are the same.
Speak replies with AssemblyAI Text-to-Speech
AssemblyAI Text-to-Speech is built for conversational voice agents and trained on millions of hours of audio, including real conversational data. For Twilio, configure the session for 8 kHz μ-law: encoding="pcm_mulaw" and sample_rate=8000. The model's native output is 24 kHz 16-bit PCM, and the server converts it before sending, so each chunk arrives raw, with no header, ready to base64-encode into a Twilio media event. Open the session when the call connects and reuse it for every reply:
import base64
import json
import os
import assemblyai as aai
from fastapi import FastAPI, WebSocket
app = FastAPI()
# Twilio plays 8 kHz mu-law, so ask for exactly that: no transcoding on the way out
TTS_CONFIG = aai.TTSConfig(
voice_id="aai-kyla", # the default English voice
language="english",
encoding="pcm_mulaw",
sample_rate=8000,
)
@app.websocket("/media-stream")
async def media_stream(ws: WebSocket):
await ws.accept()
# One TTS session per call: opened when the call starts, reused for every reply
async with aai.AsyncTTSSession(
TTS_CONFIG, api_key=os.environ["ASSEMBLYAI_API_KEY"]
) as tts:
... # the AssemblyAI STT bridge; for each agent reply:
# await speak_on_call(ws, tts, stream_sid, reply)
async def speak_on_call(ws: WebSocket, tts: aai.AsyncTTSSession, stream_sid: str, text: str):
"""Speak one reply on the call's TTS session and stream it into the Twilio call."""
async for chunk in tts.speak(text): # raw 8 kHz mu-law chunks
await ws.send_text(json.dumps({
"event": "media",
"streamSid": stream_sid,
"media": {"payload": base64.b64encode(chunk).decode()},
}))Keep one session open for the whole call. A session opened per reply pays the connection handshake on every turn and uses up your sessions-per-minute rate limit. The session closes after two minutes without a frame, so call await tts.keep_alive() during long caller silences; it lasts at most an hour. The TTS accuracy and latency guide has the full pattern.
Stream Twilio's 8 kHz audio straight into AssemblyAI-STT-3.7-Realtime-Agent, with no transcoding and turn detection that waits for the whole account number.
Let callers interrupt
To support barge-in, stop the reply as soon as the caller starts talking. On STT-3.7-Realtime-Agent, the session sends a SpeechStarted message once per turn, just before the first partial. Background noise alone doesn't trigger it, so the docs recommend it as the barge-in signal. When it arrives during a reply, cancel synthesis and tell Twilio to drop the audio it has already buffered:
import json
import assemblyai as aai
async def barge_in(twilio_ws, tts: aai.AsyncTTSSession, stream_sid: str):
"""The caller started talking over the agent: stop the reply everywhere."""
await tts.cancel() # stop synthesis of the reply in flight
await twilio_ws.send_text(json.dumps({"event": "clear", "streamSid": stream_sid}))Call it from your AssemblyAI receive loop when a message with "type": "SpeechStarted" arrives while a reply is playing. For that to work, run each reply as its own asyncio task so the loop keeps reading AssemblyAI messages while the agent talks.
Extending the agent
Give the model your agent's question
STT-3.7-Realtime-Agent transcribes each caller turn with two kinds of context: what was said in earlier turns, and what your agent just said. After your agent asks "What's your account number?", the model is primed for a string of digits. Send your agent's last reply as agent_context after each agent turn:
import json
async def send_agent_context(aai_ws, text: str):
"""Push the agent's last reply so the next caller turn is transcribed in context."""
await aai_ws.send(json.dumps({
"type": "UpdateConfiguration",
"agent_context": text, # up to 1,750 characters; each update replaces the last
}))The repo also sends the greeting as agent_context as soon as the session begins, so even the caller's first answer has context.
Handle noisy lines with Voice Focus
Voice Focus isolates the primary voice and suppresses background noise before transcription. It's available on the Agent model. Use near-field for close-talking mics, which covers most phone handsets and headsets, and far-field for distant mics, such as a speakerphone across a room:
ASSEMBLYAI_WS_URL += "&voice_focus=near-field"Add keyterm prompting
Bias the model toward your brand, product and plan names with up to 100 keyterms. Pass the list as one JSON-encoded keyterms_prompt query parameter. You can also update the list mid-call with UpdateConfiguration:
import json
from urllib.parse import urlencode
ASSEMBLYAI_WS_URL += "&" + urlencode({"keyterms_prompt": json.dumps(["YourBrand", "SpecialTerm"])})Add post-call transcription
For a full transcript after the call, run Twilio's recording through the pre-recorded API. Set the model explicitly:
import assemblyai as aai
aai.settings.api_key = "YOUR_ASSEMBLYAI_API_KEY"
config = aai.TranscriptionConfig(speech_models=["assemblyai-stt-3-7"])
transcript = aai.Transcriber(config=config).transcribe("https://example.com/recording.wav")
print(transcript.text)If you already stream calls for transcription only, without an agent, our guide to transcribing Twilio calls in real time covers that simpler setup.
Test the model on your own call recordings in the Playground and check how it handles account numbers, emails and noisy lines.
Deploy to Railway or Render
# Railway
railway login && railway init && railway up
# Render: create a Web Service pointing to this repo
# Start command: uvicorn server:app --host 0.0.0.0 --port $PORTThen point your Twilio number's webhook at https://<your-host>/incoming-call.
What it costs
AssemblyAI-STT-3.7-Realtime-Agent is $0.45/hr, billed on session duration, with keyterm prompting included. AssemblyAI Text-to-Speech is $15 per 1M characters, billed on input characters, on the same account. Twilio Voice and your LLM bill separately through their own accounts. Current rates for every add-on are on the pricing page.
Where to go next
Twilio is one front door for an agent. To build the same loop without telephony, from a laptop mic or a browser tab, see the Node.js voice agent tutorial. If you'd rather hand telephony, orchestration and a visual builder to a platform, the Vapi voice agent guide shows what Vapi's AssemblyAI transcriber supports today.
A phone agent is only as good as the numbers it hears. Transcription is the one stage where an error can't be fixed downstream, because the LLM never sees what the caller said. That's the case for spending your effort at the speech layer first.
Resources
Start free with AssemblyAI-STT-3.7-Realtime-Agent at $0.45/hr, keyterm prompting included. Point Twilio at your server and take your first call.
Frequently Asked Questions (FAQs)
What does a Twilio voice agent do?
A Twilio voice agent answers or places phone calls through Twilio Voice and holds a spoken conversation with the caller. Twilio Media Streams sends the call audio to your server over a WebSocket. Your server transcribes it in real time, sends each finished turn to an LLM, and streams the spoken reply back into the call.
What's the best speech-to-text model for a Twilio phone agent?
AssemblyAI-STT-3.7-Realtime-Agent is built for voice agents and accepts Twilio's native 8 kHz pcm_mulaw stream directly. Compared with Universal-3.6 Pro Realtime, it makes 80% fewer number errors on Voice Code Bench and adds 47% fewer words while the caller is silent. On AssemblyAI's voice-agent benchmark (November 2026), its entity error rate (13.2%) is the lowest of the 26 streaming models we ran, ahead of Soniox Realtime v6, ElevenLabs Scribe v3 Live and Deepgram Nova-3.
How do I connect Twilio Media Streams to AssemblyAI?
Point your number's incoming-call webhook at a route that returns TwiML with <Connect><Stream> to your WebSocket endpoint. In that endpoint, open wss://streaming.assemblyai.com/v3/ws?speech_model=assemblyai-stt-3-7-realtime-agent&encoding=pcm_mulaw&sample_rate=8000 with your API key in the Authorization header. Then base64-decode each Twilio media payload and send the bytes. Act on Turn messages where end_of_turn is true.
Do I need to convert Twilio's audio format for AssemblyAI?
No. Twilio streams audio/x-mulaw at 8,000 Hz, and the AssemblyAI streaming API accepts encoding=pcm_mulaw with sample_rate=8000, so you forward Twilio's audio unchanged. On the way back, ask AssemblyAI Text-to-Speech for pcm_mulaw at 8,000 Hz, and each chunk is ready for a Twilio media event.
How do I stop false turn endings on noisy phone calls?
Start with the defaults. Entity-aware endpointing already holds turns open through spoken numbers and codes, and STT-3.7-Realtime-Agent has 12% fewer false end-of-turn events than Universal-3.6 Pro Realtime. If callers still get cut off, set mode=max_accuracy, add voice_focus=near-field for handset audio, or raise min_turn_silence mid-stream for the one answer you expect to be long.
How much does a Twilio and AssemblyAI phone agent cost?
AssemblyAI-STT-3.7-Realtime-Agent is $0.45/hr, billed on session duration, with keyterm prompting included. AssemblyAI Text-to-Speech is $15 per 1M characters, billed on input characters. Twilio Voice and your LLM provider bill separately.