Conversational AI 12 min read

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.

Umer Hasan

Umer Hasan

Co-Founder & CTO at Zapprex

Voice AI Integration Tutorial: Connect an AI Voice Agent to Your Phone Line (Twilio, Exotel, Plivo)
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.
At a glance: What you will build — A phone number with media streaming, A server with a public WebSocket URL…, Accounts for streaming speech-to-text, an…
At a glance: What you will build

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.

TwiML returned when a call arrivesxml
<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.

Node.js WebSocket server (ws) — skeleton for Twilio Media Streamsjavascript
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

Step 3: Give the agent tools and a script: 4 steps
  1. 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. 2

    Add tools: check_availability, book_appointment, get_order_status — each calling your real systems with validated inputs.

  3. 3

    Greeting and disclosure: start with a short greeting that tells callers they are speaking with an automated assistant.

  4. 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.”

— Umer Hasan, CTO
  • 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

Voice AI IntegrationTwilioExotelWebSocketVoice Agent
Umer Hasan
Written by

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.

FAQ

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.

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