Voice AI Integration Tutorial: Connect an AI Voice Agent to Your Phone Line (Twilio, Exotel, Plivo)
Hands-on tutorial: route a phone number to your server, stream call audio over WebSockets, connect speech-to-text, an LLM and text-to-speech, handle interruptions, and hand calls to humans — with Node.js code.

Table of contents
What you will build
By the end of this tutorial you will understand how to connect a real phone number to an AI voice agent: a caller dials in, audio streams to your server, your server transcribes it, an LLM decides what to say, and synthesised speech streams back to the caller. If you are new to voice agents, read our guide on how AI voice agents work first.
- A phone number with media streaming: Twilio (Media Streams), Plivo (Audio Streams) or Exotel (Voicebot / stream applet) for Indian numbers.
- A server with a public WebSocket URL (wss://).
- Accounts for streaming speech-to-text, an LLM and streaming text-to-speech — or one realtime speech-to-speech model.

Step 1: Route the call to your WebSocket
With Twilio, you point the phone number’s voice webhook to an endpoint that returns TwiML telling Twilio to open a bidirectional media stream to your server. Other providers have equivalent configuration in their dashboard or call-flow builder.
<Response>
<Connect>
<Stream url="wss://voice.example.com/media" />
</Connect>
</Response>Step 2: Receive and send audio
The provider sends JSON messages over the WebSocket: a start event with call details, media events containing base64-encoded audio (8 kHz μ-law for standard phone calls), and a stop event when the call ends. To speak, you send media messages back with audio in the same format.
import { WebSocketServer } from "ws"
const wss = new WebSocketServer({ port: 8080, path: "/media" })
wss.on("connection", (socket) => {
let streamSid
const stt = createStreamingSTT({ encoding: "mulaw", sampleRate: 8000 })
socket.on("message", (raw) => {
const msg = JSON.parse(raw)
if (msg.event === "start") streamSid = msg.start.streamSid
if (msg.event === "media") stt.write(Buffer.from(msg.media.payload, "base64"))
if (msg.event === "stop") stt.close()
})
stt.on("final", async (text) => {
const replyText = await agent.respond(text) // LLM + tools
for await (const chunk of tts.stream(replyText, { format: "mulaw_8000" })) {
socket.send(JSON.stringify({ event: "media", streamSid, media: { payload: chunk.toString("base64") } }))
}
})
stt.on("speechStarted", () => { // caller interrupts
tts.cancel()
socket.send(JSON.stringify({ event: "clear", streamSid })) // flush queued audio
})
})Tip: createStreamingSTT, agent and tts are placeholders for your chosen providers’ SDKs. Keep each piece streaming end to end — waiting for a full sentence or full audio file adds seconds.
Step 3: Give the agent tools and a script

- 1
Write the system prompt: who the agent is, what it can do, how to speak (short sentences, confirm numbers), and when to transfer.
- 2
Add tools: check_availability, book_appointment, get_order_status — each calling your real systems with validated inputs.
- 3
Greeting and disclosure: start with a short greeting that tells callers they are speaking with an automated assistant.
- 4
Fallbacks: if the agent cannot understand twice, offer to transfer or arrange a callback.
Step 4: Transfer to a human
When a transfer is needed, update the live call through your telephony provider’s API to dial a staff number or queue, and send the agent’s conversation summary to the staff member by WhatsApp, CRM note or screen pop so the caller does not have to repeat themselves.
Step 5: Test and go live
“Ship voice agents with a human transfer path on day one. It is what makes callers trust the automation.”
- Latency: measure time from end of caller speech to first agent audio; aim for under about a second.
- Real conditions: test from mobile networks, noisy rooms and with Hindi, English and Hinglish speakers.
- Outbound calls: follow DND and commercial communication rules, call only consented numbers, and respect calling hours.
- Monitoring: log transcripts (with consent), tool calls, transfer rates and call outcomes; review them weekly.
Topics
Umer Hasan
Co-Founder & CTO at Zapprex
Leads engineering, cloud infrastructure and AI automation at Zapprex Technologies, with 7+ years of full-stack and mobile experience.
Keep reading
All articlesHow AI Voice Agents Work: Speech-to-Text, LLMs, Text-to-Speech and Latency Explained
Learn the architecture behind AI phone agents — telephony, streaming speech recognition, the language model, voice synthesis, interruptions and latency budgets — plus where voice agents work well in Indian and Gulf businesses.
How to Build an AI Chatbot for Your Website: A Step-by-Step Tutorial for Businesses
From choosing the chatbot’s job to writing the system prompt, connecting your knowledge base, capturing leads, handing over to humans and measuring results — a practical tutorial with a working backend example.
How WhatsApp Business Chatbots Drive 3x More Conversions & Automate Support in 2026
With open rates exceeding 98%, WhatsApp has evolved into the highest-converting customer channel. Discover how official WhatsApp Cloud API chatbots automate lead qualification, sales, and 24/7 support.
Questions readers ask
Yes. Indian telephony providers such as Exotel and Plivo support streaming call audio to your server, and the architecture is the same as with Twilio.
No. Use a streaming speech-to-text API or a realtime speech-to-speech model. Your work is the integration, prompts, tools, latency tuning and testing.
Yes. Give the agent tools that call your CRM API to create leads, log call summaries and schedule follow-ups, with validation in your code.
Have a project in mind?
Let's build something that moves your business forward.
Share your idea, process or problem — we will come back with a clear plan, timeline and cost range. No technical spec needed.
- Founder reply within 1 business day
- NDA on request · 100% code ownership
- Talk directly to the engineers
