Library

Volume 1 · Additional Advanced System Design Scenarios

Notebook
Sign in

Section 66

Conversational AI Voice Assistant Platform

2,786 words · about 13 min

Problem Statement

Design a real-time voice assistant platform: speech-to-text (STT), LLM reasoning, text-to-speech (TTS), with a strict end-to-end perceived latency budget (sub-second to first audible response), support for barge-in/interruption (user can interrupt the assistant mid-response, naturally, like a human conversation), and graceful fallback/handoff to a human agent when the AI cannot resolve the request.

Requirements Clarification

  • Assume a phone-call or voice-app style interaction (not just single-turn “smart speaker” commands) — multi-turn conversations, potentially 5-15 turns, average call length 3-5 minutes.
  • Target end-to-end perceived latency: <800ms from end-of-user-speech to start of assistant’s audible response (industry research on natural conversation turn-taking generally points to ~200-800ms as the range that feels “natural”; above ~1-1.5s feels laggy/robotic).
  • Barge-in: user must be able to interrupt the assistant’s TTS playback mid-sentence and have the system stop speaking and start listening within a very short window (target <200ms from detected speech onset to TTS playback halt).
  • Assume peak concurrency: 10,000 simultaneous active voice sessions.
  • Fallback: if the LLM’s confidence is low, the conversation loops (repeated clarification failures), or the user explicitly requests a human, hand off to a live agent with full conversation context transferred (no “please repeat everything” experience).
  • Assume multi-language support is in scope but can reuse the same pipeline architecture per language (language-specific STT/TTS models, not a fundamentally different pipeline).
  • Background noise / telephony audio quality (8kHz narrowband for PSTN-style calls vs. higher-quality app audio) must be handled — clarify which channel(s) are in scope; assume both a telephony (PSTN/SIP) channel and an app/WebRTC channel.

Architecture Diagram

 User (phone/app) ◀──── audio stream (bidirectional, WebRTC/SIP) ────▶  Media Gateway
                                                                              │
                                                          ┌───────────────────▼────────────────────┐
                                                          │         Session Orchestrator              │
                                                          │  (per-call state machine, manages the      │
                                                          │   pipeline below, holds conversation        │
                                                          │   context/history)                          │
                                                          └───────────────────┬────────────────────┘
                                                                                │
     ┌──────────────────────────────────────────────────────────────────────┼───────────────────────────────────────┐
     │                                                                        │                                        │
     ▼                                                                        ▼                                        │
┌─────────────────────┐                                        ┌──────────────────────────┐                          │
│  Streaming VAD /      │                                        │   Streaming STT             │                          │
│  Endpoint Detection   │───speech segment (partial+final)─────▶│   (incremental, low-latency  │                          │
│  (voice activity       │                                        │    ASR, emits partial        │                          │
│   detection, <20ms      │                                        │    transcripts as user        │                          │
│   frame granularity)    │                                        │    speaks + final on          │                          │
│                          │                                        │    endpoint detected)          │                          │
└──────────┬───────────────┘                                        └──────────────┬─────────────┘                          │
           │                                                                          │  final transcript                     │
           │ barge-in signal (speech detected while                                   ▼                                        │
           │  TTS is playing) ──────────────────────────────▶  [interrupt TTS playback, flush queue]                          │
           │                                                                          │                                        │
           │                                                                          ▼                                        │
           │                                                        ┌──────────────────────────┐                             │
           │                                                        │   LLM Reasoning Engine      │                             │
           │                                                        │  - streaming token          │                             │
           │                                                        │    generation                │                             │
           │                                                        │  - tool calls (lookup order  │                             │
           │                                                        │    status, account data,     │                             │
           │                                                        │    etc.) via function-calling│                             │
           │                                                        │  - confidence/escalation      │                             │
           │                                                        │    signal computed alongside  │                             │
           │                                                        │    response                   │                             │
           │                                                        └──────────────┬─────────────┘                             │
           │                                                                          │ streaming tokens                        │
           │                                                                          ▼                                        │
           │                                                        ┌──────────────────────────┐                             │
           │                                                        │   Streaming TTS             │                             │
           │                                                        │  - sentence/phrase-chunked   │                             │
           │                                                        │    synthesis (don't wait for │                             │
           │                                                        │    full LLM response)         │                             │
           │                                                        │  - low-latency neural vocoder │                             │
           └────────────────────────────────────────────────────────┤  - streams audio back as      │                             │
                                                                       │    generated                  │                             │
                                                                       └──────────────┬─────────────┘                             │
                                                                                          │ audio chunks                          │
                                                                                          ▼                                        │
                                                                              back to Media Gateway ──▶ User                       │
                                                                                                                                    │
     ┌──────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
     │
     ▼
┌───────────────────────────┐          ┌────────────────────────────┐
│  Escalation Monitor          │──────▶│  Human Agent Handoff          │
│  - tracks repeated             │      │  - full transcript + context   │
│    clarification failures,     │      │    transferred to agent desktop│
│    explicit "agent" request,    │      │  - warm handoff (agent joins    │
│    low LLM confidence           │      │    call, AI can stay silent      │
│                                 │      │    or bridge audio)              │
└───────────────────────────┘          └────────────────────────────┘

Key Design Decisions

  1. Streaming/incremental pipeline (STT emits partials, LLM streams tokens, TTS synthesizes per-phrase) vs. batch turn-based processing (wait for full utterance, full LLM response, then full TTS).

    • Chosen: every stage streams — STT emits partial transcripts as the user speaks and a final transcript at endpoint detection; the LLM begins generating and streaming tokens as soon as the final (or even a stable partial) transcript is available; TTS synthesizes audio per sentence/phrase chunk as tokens arrive rather than waiting for the complete LLM response.
    • Alternative: fully batch — wait for complete utterance, full LLM completion, then synthesize the whole response as one TTS call.
    • Trade-off: batch is far simpler to build and debug (clean request/response boundaries at each stage) but stacks every stage’s latency serially — STT-complete-time + full-LLM-generation-time + full-TTS-synthesis-time easily exceeds 1.5-3 seconds for anything beyond a trivial response, blowing the <800ms budget. Streaming pipelines overlap these stages (TTS for sentence 1 starts while the LLM is still generating sentence 3) but require every component to support incremental/streaming APIs and introduces real engineering complexity in buffering, chunk-boundary handling (don’t cut TTS mid-word), and error recovery when a mid-stream stage fails.
  2. Barge-in handling via continuous VAD running in parallel with TTS playback vs. simple “assistant finishes speaking, then listens” turn-taking.

    • Chosen: voice activity detection runs continuously on the inbound audio stream even while the assistant’s TTS is playing outbound audio (full-duplex); detecting genuine user speech onset (distinguished from echo of the assistant’s own voice via acoustic echo cancellation) immediately triggers a playback-halt signal and flushes any queued TTS audio, transitioning the session state to listening.
    • Alternative: strict half-duplex turn-taking — system only listens after it has finished speaking.
    • Trade-off: half-duplex is much simpler (no echo cancellation needed, no race conditions between playback and listening) but feels distinctly robotic and is a poor user experience for anything beyond simple command-response (users naturally interrupt in real conversation, especially to correct a misunderstood request early). Full-duplex barge-in requires acoustic echo cancellation (to avoid the system hearing its own TTS output as user speech and self-interrupting) and careful low-latency signal processing, a meaningfully harder engineering problem.
  3. Sentence/phrase-level TTS chunking vs. word-level or full-response chunking.

    • Chosen: LLM output is segmented at natural phrase/clause boundaries (using punctuation and lightweight streaming sentence-boundary detection) before being sent to TTS, balancing latency against audio naturalness.
    • Alternative A (word-level): synthesize and play each word as soon as generated. Alternative B (full-response): wait for the entire LLM response before any TTS.
    • Trade-off: word-level minimizes time-to-first-audio further but produces choppy, unnatural prosody (TTS models generate more natural intonation with sentence-level context, since prosody depends on where a sentence is going) and adds overhead from many small synthesis calls; full-response has the best prosody but the worst latency. Phrase/sentence chunking is the practical middle ground used by most production voice AI systems.
  4. Function-calling/tool-use for dynamic data (order status, account lookups) synchronously within the reasoning turn vs. a separate pre-fetch step.

    • Chosen: the LLM reasoning engine supports mid-generation tool calls (pause generation, call an internal API/tool, resume generation with the result incorporated) as part of the same streaming turn, with a timeout budget on tool calls (e.g., 300-500ms) since this adds directly to the perceived latency.
    • Alternative: a separate upfront step that pre-fetches likely-needed data before invoking the LLM.
    • Trade-off: pre-fetching only works if you can predict what data is needed before understanding the user’s actual request (often you can’t, especially in open-ended conversation), while inline tool-calling is more flexible but directly extends the response-latency critical path — every tool call is latency budget spent, so tool APIs used in this synchronous path must themselves be held to aggressive SLAs (sub-300ms), and slow backend systems need a caching or async-with-filler-response strategy (“let me check on that…” spoken while the tool call completes) to avoid dead air.
  5. Escalation/handoff logic as a first-class, continuously-computed signal vs. a reactive-only fallback (only escalate on explicit user request).

    • Chosen: the LLM reasoning stage computes an ongoing confidence/frustration signal (e.g., detecting repeated re-asks of the same question, explicit negative sentiment, or the model’s own low-confidence/refusal patterns) that can proactively trigger escalation, in addition to reactive triggers (user says “talk to a person”).
    • Alternative: only escalate when the user explicitly asks.
    • Trade-off: purely reactive escalation leaves users stuck in frustrating loops if they don’t think to ask for a human (common in older/less tech-savvy users, or simply mid-frustration), producing poor CSAT and increased call abandonment; proactive escalation risks over-triggering (handing off calls the AI actually could have resolved, increasing human-agent cost unnecessarily) — this is tuned like the fraud-detection threshold problem, balancing automation-resolution-rate against user-experience-and-cost.
  6. Warm handoff with full context transfer vs. cold transfer (agent starts fresh, asks user to repeat).

    • Chosen: on escalation, the full conversation transcript, extracted intent/entities, and any tool-call results already gathered are pushed to the agent’s desktop before or as the call connects; the AI can optionally remain silently in the loop as a real-time assist to the human agent (e.g., suggested responses) rather than a hard handoff.
    • Trade-off: warm handoff requires the human-agent platform and the AI platform to share a common session/context data model and requires that transcript/context data be available with very low latency at handoff time (no one wants a caller waiting while systems sync); building and maintaining that integration is real cross-team engineering investment, but cold handoff (make the user repeat everything) is one of the most commonly cited reasons for poor CSAT in AI-to-human escalation flows, so it’s treated as a hard requirement, not a nice-to-have.

Scale Math

  • 10,000 concurrent active voice sessions. Each session holds: an open audio stream (bidirectional), streaming STT connection, LLM context/session state, TTS connection. Audio bandwidth: assume 16kHz/16-bit mono for app audio (~256kbps uncompressed, typically compressed via Opus to ~24-32kbps) or 8kHz narrowband for PSTN (~64kbps uncompressed, G.711); at 10,000 concurrent sessions using compressed codecs (~32kbps average) → ~320Mbps aggregate bidirectional media bandwidth, well within standard media-server capacity when horizontally sharded.
  • Latency budget breakdown for the <800ms target: VAD/endpoint detection ~100-150ms (need enough silence to confidently detect end-of-utterance without cutting off a user mid-thought — this alone is a meaningful chunk of the budget and a tuning trade-off between responsiveness and premature cutoff), streaming STT finalization ~100-150ms after endpoint, LLM time-to-first-token ~150-300ms (favors a smaller/faster model or aggressive prompt/context optimization over the largest available model), TTS time-to-first-audio-chunk ~100-150ms, network/jitter buffer overhead ~50-100ms. This is a tight budget that argues strongly for co-locating STT/LLM/TTS services in the same region/data center as the media gateway to avoid extra network round trips, and for using smaller, faster models tuned for latency over raw quality where the trade-off is acceptable.
  • STT/TTS compute: streaming STT models at 10,000 concurrent sessions typically need dedicated GPU or optimized-CPU inference pools sized for real-time-factor well under 1.0 (must process audio faster than real-time with margin); similarly for neural TTS. Capacity planning here is concurrency-bound (need enough resident model instances/replicas for 10,000 simultaneous streams), not just QPS-bound, since sessions are long-lived (minutes), unlike stateless request/response APIs — this is a materially different scaling model than typical web services and needs to be called out explicitly.
  • LLM inference: assume average 5-8 conversational turns per call, each turn generating ~50-150 tokens of response; at 10,000 concurrent calls with turns spread over a 3-5 min average call duration, instantaneous concurrent LLM generation load is much lower than 10,000 (most sessions are mid-listening or mid-TTS-playback at any instant, not mid-generation) — realistic concurrent LLM generation load might be a few hundred to ~1,000 concurrent generations at any instant, informing GPU pool sizing distinctly from raw session count.

Failure Modes & How They’re Handled

  • STT misrecognition on noisy telephony audio: narrowband/noisy audio produces garbled transcripts, leading the LLM to respond to the wrong intent. Mitigated with confidence scores from STT surfaced to the reasoning stage (low-confidence transcripts trigger a clarifying question rather than confidently acting on a likely-wrong transcript) and audio pre-processing (noise suppression, automatic gain control) in the media pipeline.
  • Barge-in false trigger from echo/background noise: poor acoustic echo cancellation causes the system to “hear” its own TTS output or background noise as a user interruption, cutting itself off unnecessarily. Mitigated with robust AEC tuned per audio channel type (app vs. PSTN have very different echo characteristics), a minimum-confidence/duration threshold before treating detected audio as genuine barge-in (very short blips don’t trigger), and continuous AEC quality monitoring per call.
  • LLM tool-call timeout stalls the conversation: a backend lookup takes too long, and dead air makes the assistant feel broken. Mitigated with a hard timeout on tool calls plus a filler-response strategy (a short, natural “let me check on that” spoken while the async call completes) so there’s never silence beyond a couple hundred milliseconds, and a fallback response path if the tool call ultimately fails/times out.
  • Session/pipeline component crash mid-call: any of STT/LLM/TTS/orchestrator instance dies mid-conversation. Mitigated by session state (conversation history, in-flight context) being externalized to a fast, replicated store rather than held only in a single process’s memory, so a new instance can pick up the session with minimal disruption; media gateway maintains the audio connection independent of backend processing instance identity, enabling failover without dropping the call outright where possible (best-effort — a brief reconnect glitch is preferable to a dropped call).
  • Escalation signal false negative (AI keeps trying, user gets increasingly frustrated, no handoff triggers): Mitigated with hard-cap circuit breakers independent of the confidence model — e.g., after N failed clarification loops on the same apparent intent, force an escalation offer regardless of what the confidence signal says, as a backstop against the ML-based escalation detector itself being wrong.
  • Regional/network jitter causing audio choppiness: Mitigated with adaptive jitter buffering at the media gateway and regional deployment of the full pipeline close to users (same latency-driving logic as decision on co-location), rather than relying on a single centralized region for global traffic.

Interviewer Follow-Up Q&A

Q: Your latency budget is extremely tight — where would you spend engineering effort first if you had to cut 200ms out of the pipeline? A: Profile every stage under real production load first rather than guessing, but the highest-leverage targets are typically: (1) LLM time-to-first-token, since a smaller/distilled model or better prompt/context caching often yields the biggest single-stage win without touching audio infrastructure; (2) VAD endpoint-detection silence threshold, which is a pure tuning trade-off — shortening it saves latency but risks cutting off users who pause mid-thought, so it needs to be tuned against real conversational data, not guessed; and (3) removing any avoidable network hop by co-locating pipeline stages, since raw network RTT is “free” latency to cut if the architecture wasn’t already collocated.

Q: How do you test/validate barge-in behavior, since it’s inherently a race condition between playback and listening? A: Automated conversational testing with synthetic audio injection that deliberately overlaps simulated user speech with assistant TTS playback at varied offsets (early, mid-sentence, late), verifying the system halts playback within the target window and correctly discards vs. correctly incorporates the interruption; this needs to be a continuous regression suite, not a one-time manual test, since barge-in behavior is sensitive to any change in the audio pipeline, AEC tuning, or VAD thresholds.

Q: What’s the failure mode if the LLM itself hallucinates or gives a wrong answer confidently (not a low-confidence case that would trigger escalation)? A: This is the hardest case precisely because the confidence-based escalation signal doesn’t catch it. Mitigations: constrain the LLM’s authority for consequential actions (e.g., anything involving money movement, account changes) to require tool-call-verified data rather than free-generation, use retrieval/grounding for factual claims where possible rather than relying on parametric knowledge, and accept that some hallucination risk remains — mitigated at the product level with clear disclosure to users that they’re talking to an AI and an easy, always-available path to request a human, rather than claiming the AI is infallible.

Q: Why not just always run STT, LLM, and TTS in the same region as the caller — isn’t that obviously correct? What makes it hard? A: It’s the right target, but multi-region deployment of a full real-time voice AI stack is nontrivial: you need regional capacity for STT/LLM/TTS model serving (not just stateless web tier replication — these are GPU-backed, stateful-ish services), regional session-state consistency if a call needs to fail over, and often language/accent-specific model variants that may not have uniform regional coverage. In practice, most platforms start with a few major regions covering the bulk of traffic and accept higher latency (with a relaxed budget) for long-tail geographies, rather than achieving true global low-latency parity on day one.

Q: How would you extend this design to support a multi-modal channel (e.g., a video call, or a chat+voice hybrid app)? A: The core streaming orchestration pattern (VAD/turn-detection driving a reasoning engine with tool-calling, streaming output) generalizes, but you’d add a modality-fusion layer — e.g., for video, incorporating visual context (screen-share content, camera feed for sentiment/attention) as additional input to the reasoning stage, and for chat+voice hybrid, the orchestrator needs to unify turn-taking across a synchronous voice channel and an asynchronous text channel, which requires rethinking the strict low-latency turn-based state machine to allow either channel to drive the next turn.