A Twilio voice agent is a server with two routes: a voice webhook that answers each call with TwiML, and a WebSocket that receives the call's audio as a Media Stream. Connect that socket to a voice session with twilioMediaStream(ws) from voiceai-sdk/twilio, and session.converse runs the conversation: it hears the caller, calls your model, and speaks the reply into the call.
This post uses the planned 1.0 API of VoiceAI SDK, which is in developer preview. The code was written against that API and was not run against a live Twilio account or provider keys. Twilio-specific details come from the Twilio integration page.
The call flow at a glance
| Step | What happens |
|---|---|
| 1. The caller dials | Twilio sends a request to your number's voice webhook. |
| 2. The webhook answers | Your server returns TwiML with <Connect><Stream> and a wss:// URL. |
| 3. The stream opens | Twilio opens the WebSocket and streams the caller's audio as 8 kHz mu-law. |
| 4. The session connects | Your server opens a session in the same format and calls session.connect(twilioMediaStream(ws)). |
| 5. Turns | converse calls your handler for each final transcript and speaks the reply into the call. |
| 6. Someone hangs up | The socket closes, converse resolves, and the session closes. |
What you need
- A Twilio phone number.
- A public HTTPS address for your server. Twilio only connects to
wss://URLs, so in development, run a tunnel to your machine. - Provider keys on the server. This post uses a pipeline, so
DEEPGRAM_API_KEYandELEVENLABS_API_KEY, plus whatever your model needs. - Node 22 or later, or Bun. The server below uses
Bun.serve.
npm install voiceai-sdk twilio ai
npx voiceai-sdk doctorAnswer the webhook with TwiML
When a call comes in, Twilio requests your voice webhook. The webhook answers with TwiML that connects the call to your stream URL:
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Connect>
<Stream url="wss://voice.example.com/media/CA0123456789abcdef0123456789abcdef" />
</Connect>
</Response><Connect> keeps the call on the stream until the WebSocket closes. Nothing follows it, so Twilio ends the call when the stream ends. Use <Connect><Stream>, not <Start><Stream>: <Start> only sends the caller's audio to you, so the agent could hear but never answer. The stream URL can't carry a query string, so the CallSid goes in the path.
Connect the stream to a session
One server handles both routes. The twilio package writes the TwiML, and the WebSocket handler opens one session per call:
import twilio from "twilio";
import { createSession } from "voiceai-sdk";
import { deepgram } from "voiceai-sdk/deepgram";
import { elevenlabs } from "voiceai-sdk/elevenlabs";
import { twilioMediaStream } from "voiceai-sdk/twilio";
Bun.serve({
port: 3000,
async fetch(req, server) {
const url = new URL(req.url);
// The voice webhook: answer with TwiML that opens a media stream.
if (url.pathname === "/voice") {
const callSid = (await req.formData()).get("CallSid");
const twiml = new twilio.twiml.VoiceResponse();
twiml.connect().stream({ url: `wss://${url.host}/media/${callSid}` });
return new Response(twiml.toString(), { headers: { "content-type": "text/xml" } });
}
// The media stream for one call.
if (url.pathname.startsWith("/media/")) {
const callSid = url.pathname.slice("/media/".length);
if (server.upgrade(req, { data: { callSid } })) return;
}
return new Response("not found", { status: 404 });
},
websocket: {
async open(ws) {
await using session = await createSession(
{ stt: deepgram(), tts: elevenlabs({ voice: process.env.VOICE_ID }) },
{ key: `call:${ws.data.callSid}`, encoding: "mulaw", sampleRate: 8000, timeoutMs: 20 * 60_000 },
);
session.connect(twilioMediaStream(ws));
await session.say`Thanks for calling the bike shop. How can I help?`;
await session.converse(async (text) => `You said: ${text}`);
},
},
});encoding: "mulaw"andsampleRate: 8000match the audio Twilio sends and expects back. If a provider can't work in that format,createSessionthrowsVoiceErrorwith codeunsupportedinstead of converting quietly.- The key is built from the
CallSid, solistSessionsshows which call each session belongs to. session.sayspeaks into the call. Interpolated values are spoken as plain text, never as SSML.
Put a model on the line
Replace the echo handler with a model. Callers can't see anything, so ask for short spoken answers, and give the model end_call so it can hang up:
import { streamText } from "ai";
import { voiceTools } from "voiceai-sdk/ai";
// Inside open(ws), after session.connect(...) and the greeting
const { end_call } = voiceTools(session);
await session.converse((text, ctx) => {
const result = streamText({
model: "openai/gpt-5",
system:
"You answer the phone for a bike shop. Use one or two short sentences, with no lists or links. " +
"When the caller is done, say goodbye and call end_call.",
messages: [...ctx.history, { role: "user", content: text }],
tools: { end_call },
abortSignal: ctx.signal,
});
return result.textStream;
});The reply streams into the call as the model writes it. If the caller talks over it, the session stops speaking and ctx.signal stops the model; Barge-in explains how. If you would rather have one speech-to-speech model run the call, pass openai({ instructions }) and call converse() without a handler, as in OpenAI Realtime API in TypeScript.
Hang up and clean up
- The model hangs up. It calls
end_call, the session closes, andconverseresolves. - The caller hangs up. Twilio closes the socket,
converseresolves, andawait usingcloses the session. - Your code hangs up. Close the socket with
ws.close(). With nothing after<Connect>, Twilio ends the call.
timeoutMs in the session options is a backstop: no call stays open longer than that, whatever happens. To hang up after a goodbye from your own code, wait for speech.end before you close the socket, or the goodbye is cut off.
Lock down both routes
Both routes open sessions on your provider accounts, so anyone who finds them can spend your keys. Check the X-Twilio-Signature header on /voice with twilio.validateRequest, and accept a media stream only for a CallSid your webhook answered. Provider keys stay on your server: Twilio sends audio to you, and your server talks to the provider.
Common questions
Why mu-law at 8 kHz? It is the format Twilio Media Streams carry in both directions. Opening the session in the same format means no conversion on your side. Which providers accept it depends on the provider; see Capabilities. The openai() provider page notes that the SDK converts telephony audio for it.
Can a caller pick up the same conversation after a dropped call? A new call has a new CallSid. To continue a conversation across calls, key the session by the caller's number, such as caller:+15551234567, set idleTimeoutMs, and don't open it with await using, which would close it when the socket closes. See One session per caller.
How do I test the agent without phoning it? The handler is a function from text to a reply. Run it against mock() with scripted transcripts; see Testing voice agents without a microphone.
Does the agent need a browser or a client app? No. The phone talks to Twilio, and Twilio talks to your server. Nothing runs in a browser.
Next steps
- Build a phone agent: the full guide, including hanging up after a goodbye.
- Twilio: the transport, the audio format and the security checks.
- One session per caller: keep a conversation when a caller reconnects.
More guides on the VoiceAI SDK blog, or start with the quickstart.