Twilio
Answer phone calls with a voice session over Twilio Media Streams, using twilioMediaStream from voiceai-sdk/twilio.
Twilio connects a phone call to your server over a WebSocket and streams the call's audio as Media Streams messages. twilioMediaStream(ws) from voiceai-sdk/twilio turns that socket into a transport, so the session hears the caller and speaks back on the same call.
Install
npm install voiceai-sdk twiliopnpm add voiceai-sdk twilioyarn add voiceai-sdk twiliobun add voiceai-sdk twiliotwilio is Twilio's helper library. The example uses it to write TwiML. You also need a Twilio phone number and a public address for your server, such as a tunnel while you develop.
Quickstart
The server has two routes. /voice is your number's voice webhook: Twilio requests it when a call comes in. /media/<CallSid> is the media stream that the TwiML opens.
import twilio from "twilio";
import { createSession } from "voiceai-sdk";
import { openai } from "voiceai-sdk/openai";
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);
return server.upgrade(req, { data: { callSid } }) ? undefined : new Response("upgrade required", { status: 426 });
}
return new Response("not found", { status: 404 });
},
websocket: {
async open(ws) {
await using session = await createSession(openai(), {
key: `call:${ws.data.callSid}`,
sampleRate: 8000,
encoding: "mulaw",
});
session.connect(twilioMediaStream(ws));
await session.say`Thanks for calling. How can I help?`;
await session.converse(async (text) => `You said: ${text}`);
},
},
});For a call, the webhook returns this TwiML:
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Connect>
<Stream url="wss://voice.example.com/media/CA0123456789abcdef0123456789abcdef" />
</Connect>
</Response>In the Twilio console, set your number's voice webhook to an HTTP POST to https://<your host>/voice. The stream URL can't carry a query string, so the CallSid goes in the path.
Audio format
Twilio Media Streams carry phone-quality audio in both directions. The session asks for the same format:
| Twilio stream | Session |
|---|---|
| 8 kHz sample rate | sampleRate: 8000 |
| mu-law encoding | encoding: "mulaw" |
Audio as base64 inside JSON media messages | Decoded and encoded by twilioMediaStream |
Whether a provider takes 8 kHz mu-law depends on the provider; see Capabilities. If it can't, createSession throws VoiceError with code unsupported instead of quietly using another format.
One session per call
The key is built from the CallSid, which Twilio assigns to each call and sends with every webhook. While the call is live, any code that calls createSession with that key gets the same session instead of a new one, and listSessions shows which call each session belongs to. To keep a conversation across separate calls from the same number, see One session per caller.
A call can end from either side:
- The caller hangs up. Twilio closes the socket,
converseresolves, andawait usingcloses the session. - Your code hangs up. Close the socket. With nothing after
<Connect>in the TwiML, Twilio ends the call when the stream closes, and the session closes as above. - An agent hangs up. If a model drives the call with agent tools, it calls
end_call.
For example, to end any call that runs past ten minutes, inside the open handler:
const limit = setTimeout(async () => {
session.interrupt();
await session.say`Sorry, we have to end the call here. Goodbye.`;
ws.close();
}, 10 * 60_000);
await session.converse(async (text) => `You said: ${text}`);
clearTimeout(limit);Where keys stay
- The provider's key, here
OPENAI_API_KEY, is read by your server. Twilio never sees it: Twilio sends audio to you, and your server talks to the provider. - Both routes open sessions on your provider account. Check the
X-Twilio-Signatureheader on/voicewithtwilio.validateRequest, and accept a media stream only for aCallSidyour webhook answered. - Nothing runs in a browser. The phone talks to Twilio, and Twilio talks to your server.
Next steps
- Build a phone agent: put a model behind this call.
- Interruptions and barge-in: what happens when the caller talks over the session.
- Latency and audio formats: sample rates and encodings for each transport.