Chapter 13 of 32 · ~16 min read & lab+65 XP
Chapter 13 · Agentic AI

Voice, Realtime & Multimodal Agents: VAD, Barge-In & Streaming Loops

Master sub-500ms conversational voice agents—comparing Cascaded (STT → LLM → TTS) vs. Native Speech-to-Speech pipelines, Voice Activity Detection, and barge-in cancellation

What Is It?

Voice and realtime multimodal agents process live audio and video streams continuously over WebRTC or WebSockets—handling turn-taking, interruptions (barge-in), and asynchronous tool calls under strict human latency budgets (< 500 ms).

Why Is It Required?

Text chat tolerates 2–4 seconds of latency, but in a live phone call or voice assistant, even an 800 ms pause feels awkward and broken—requiring streaming pipelines, turn-detection models, and non-blocking tool execution.

Everyday Analogy: A text chatbot is like exchanging emails; a realtime voice agent is like a live phone conversation where you must notice the instant the other person starts talking, stop mid-sentence, and still look up their reservation in the background.
Why ML Engineers & Data Scientists Actually Need This

Voice AI (customer support, sales, healthcare triage, live coding copilots) is one of the highest-revenue production agent categories—and its engineering bottlenecks are completely different from text agents.

ML / AI Engineer

You engineer the audio transport (WebRTC vs. WebSocket), Voice Activity Detection (VAD) thresholds, speculative TTS sentence chunking, and barge-in cancellation tokens so audio stops within 50 ms of user interruption.

Data Scientist

You measure voice-to-voice latency (P50/P95), false-interruption rate (cutting off users during brief pauses), and tool-call filler naturalness.

Interview & Debug Edge

Candidates who immediately break down the voice latency budget—VAD Endpointing + STT + LLM TTFT + TTS TTFB—and explain how streaming sentence-by-sentence cuts perceived latency by 3× stand out immediately.

Step 0 · Test Your Gut Before Any Math!

A voice agent waits for the LLM to finish generating its full 40-word response before sending text to Text-to-Speech (TTS). What happens to the user's experience?

What You Will Master in This Chapter
  • Function Calling, Tool Schemas & Dispatch
  • Basic familiarity with streaming APIs and latency budgets
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Text agents optimize for accuracy per dollar; realtime voice agents optimize for conversational turn-taking under 500 ms. Every stage in the pipeline must stream incrementally—and every stage must be instantly cancellable the millisecond the user interrupts.

1. Cascaded vs. Native Speech-to-Speech Architectures

ArchitecturePipelineTypical LatencyPros & Cons
Cascaded (Modular)Mic → VAD → Streaming STT → LLM → Streaming TTS → Speaker~500–900 msBest tool-calling accuracy, easy PII redaction & prompt control, swap any vendor
Native Speech-to-SpeechMic → Multimodal Audio-in/Audio-out LLM → Speaker~250–450 msPreserves emotion, tone, laughter & ultra-low latency; harder to audit/redact mid-stream

2. VAD, Semantic Endpointing & Barge-In

Three mechanics make or break a voice agent:

  1. VAD (Voice Activity Detection): Lightweight model (e.g., Silero VAD) running on 20 ms audio frames to detect speech vs. background noise.
  2. Semantic Turn Detection: Pure silence timers (e.g., 500 ms) cut off users who pause mid-thought ("My order number is... um... 4821"). A lightweight turn-detection classifier checks whether the utterance is semantically complete before triggering the LLM.
  3. Barge-In (Interruption Handling): If VAD detects user speech while the agent is speaking, the runtime immediately flushes the audio playback buffer, cancels the in-flight LLM/TTS streams, and truncates the assistant's transcript to only the words the user actually heard.

3. Non-Blocking Tool Calls in Voice Loops

If a database lookup takes 1.8 seconds during a phone call, total silence makes callers think the line dropped. Production voice agents handle this with:

  • Acknowledge-then-Execute: Emit a natural spoken filler ("Let me pull up your order right now...") in parallel with the async tool call.
  • Transport Choice: Use WebRTC (UDP-based, built-in echo cancellation & jitter buffers) for browser/mobile clients, and WebSockets for server-to-server telephony bridges (Twilio/SIP).
“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Because the LLM generated 30 words into the buffer, but the user interrupted after word 6. If you leave all 30 words in chat history, the LLM will mistakenly think the user heard the remaining 24 words!

Interactive Visual Lab
Lab Challenge: Inspect how asynchronous tool calls and streaming responses keep agent interactions responsive.
Interactive Animation • 2.1 Deep Lab

Safe Tool-Call Registry & Schema Dispatch Pipeline

Trace an LLM tool call through allowlist lookup, strict Pydantic validation, and structured observation return.

Stage 1 / 4
1. LLM Emits Tool Call
{"name": "get_order", "args": {"order_id": "ORD-402"}}
2. Allowlist Registry Lookup
TOOLS['get_order'] found ✓ (eval() never used!)
3. Pydantic Schema Validation
order_id: str matches ^ORD-\d+$ ✓
4. Sandboxed Execution → JSON
{"ok": true, "status": "shipped", "eta": "2026-12-05"} ✓
0%
1. LLM Emits Tool Call
Intuition Takeaway: Great voice agents stay under 500–700 ms by streaming every stage (VAD → STT → LLM → TTS), using WebRTC for echo-cancelled transport, and cleanly cancelling + truncating state on user barge-in.
Production NumPy & PyTorch Code Patterns
# Voice Agent Latency Budget & Barge-In Transcript Truncation Simulator
def compute_voice_turn_latency_ms(vad_ms: int, stt_ms: int, llm_ttft_ms: int, tts_ttfb_ms: int) -> dict:
    total = vad_ms + stt_ms + llm_ttft_ms + tts_ttfb_ms
    sla = "NATURAL (<500ms)" if total < 500 else ("ACCEPTABLE (<800ms)" if total < 800 else "SLUGGISH (>=800ms)")
    return {"total_ms": total, "sla": sla}

def handle_barge_in(generated_words: list[str], spoken_word_count: int) -> str:
    # Keep only the words actually played before the user interrupted
    heard = generated_words[:spoken_word_count]
    return " ".join(heard) + " [interrupted]"

print("Cascaded:", compute_voice_turn_latency_ms(vad_ms=180, stt_ms=140, llm_ttft_ms=220, tts_ttfb_ms=150))
print("Native S2S:", compute_voice_turn_latency_ms(vad_ms=150, stt_ms=0, llm_ttft_ms=180, tts_ttfb_ms=60))

reply = "Your package is scheduled to arrive tomorrow afternoon at three PM via express courier".split()
print("Saved history after barge-in at word 5:", handle_barge_in(reply, spoken_word_count=5))
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Forgetting Acoustic Echo Cancellation (AEC)
Best Practice: without it, the agent hears its own TTS voice and endlessly interrupts itself.
Trap #2: Using a fixed 300 ms silence timer for endpointing
Best Practice: it constantly interrupts users who pause to recall an account number or address.
Chapter Mastery Check (+65 XP)
Score: 0 / 1
1When a user interrupts (barges in on) a voice agent mid-sentence, what must the agent harness do besides stopping audio playback?

Apply What You Learned — Solve Matching Coding Problems