Build a phone agent
Answer a phone call over Twilio Media Streams and hold a conversation on it with a voice session.
Twilio can connect a phone call to your server over a WebSocket, called a Media Stream. It sends the caller's audio over the socket and plays back the audio you send. twilioMediaStream(ws) from voiceai-sdk/twilio turns that socket into a transport for a session, so the agent from Give your agent a voice can answer the phone.
How a call reaches your code
- A caller dials your Twilio number, and Twilio sends a request to your voice webhook.
- Your webhook returns TwiML that tells Twilio to stream the call to your WebSocket URL.
- Twilio opens the WebSocket and streams the caller's audio as 8 kHz mu-law.
- Your server opens a session, connects it to the socket, and talks.
- When the socket closes, from either side, the call ends.
You need a Twilio number, provider keys on your server, such as DEEPGRAM_API_KEY and ELEVENLABS_API_KEY, and a public HTTPS address. Twilio only connects to wss:// URLs, so in development, run a tunnel to your machine.
Return TwiML from the webhook
The webhook answers with this TwiML:
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Connect>
<Stream url="wss://voice.example.com/media" />
</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. In the Twilio console, set your number's voice webhook to the URL that returns this TwiML, here https://voice.example.com/voice.
Connect the stream to a session
One server handles both the webhook and the stream:
import { createSession } from "voiceai-sdk";
import { deepgram } from "voiceai-sdk/deepgram";
import { elevenlabs } from "voiceai-sdk/elevenlabs";
import { twilioMediaStream } from "voiceai-sdk/twilio";
const twiml = `<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Connect>
<Stream url="wss://voice.example.com/media" />
</Connect>
</Response>`;
Bun.serve({
port: 3000,
fetch(req, server) {
const { pathname } = new URL(req.url);
if (pathname === "/voice") return new Response(twiml, { headers: { "content-type": "text/xml" } });
if (pathname === "/media" && server.upgrade(req)) return;
return new Response("not found", { status: 404 });
},
websocket: {
async open(ws) {
await using session = await createSession(
{ stt: deepgram(), tts: elevenlabs() },
{ encoding: "mulaw", sampleRate: 8000 },
);
session.connect(twilioMediaStream(ws));
await session.say`Thanks for calling Luigi's. 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 codeunsupported. Which providers accept it depends on the provider; see Capabilities.session.sayspeaks into the call. Interpolated values are spoken as plain text, never as SSML, so you can greet a caller by a name from your database.- When the caller hangs up, Twilio closes the socket,
converseresolves, andawait usingcloses the session.
Put a model on the line
Replace the echo handler with a model. Phone 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(...)
const { end_call } = voiceTools(session);
await session.say`Thanks for calling Luigi's. How can I help?`;
await session.converse((text, ctx) => {
const result = streamText({
model: "openai/gpt-5",
system: "You answer the phone for Luigi's. Keep answers to one or two sentences. Call end_call when the caller is done.",
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. See Interruptions and barge-in.
Hang up
The call ends when the session closes. Any of these closes it:
| Who decides | How |
|---|---|
| The model | It calls the end_call tool. The session closes and converse resolves. |
| Your code | You call session.close(). It is idempotent, so calling it after the model has hung up is safe. |
| The caller | They hang up. Twilio closes the socket and converse resolves. |
To hang up from your own code after a goodbye, wait for the goodbye to finish playing. Closing while a reply is still playing cuts it off.
import { answer } from "./agent";
let done = false;
session.on("speech.end", () => {
if (done) session.close();
});
await session.converse((text, ctx) => {
if (text.toLowerCase().includes("goodbye")) {
done = true;
return "Thanks for calling. Goodbye.";
}
return answer(text, ctx);
});Next steps
- One session per caller: let a caller whose line drops resume the same conversation.
- Latency and audio formats: what
sampleRateandencodingchange. - Twilio: the Twilio transport in detail.