Real-Time Voice Agents

Generative & Agentic AI · Frontier GenAI · Advanced · 26 min

Build voice agents that feel natural: choose a cascaded or speech-to-speech pipeline, budget the time to first audio, detect the end of a turn with VAD, handle barge-in, stream every stage, call tools mid-conversation, and connect phone lines on AWS.

Two people on a walkie-talkie who keep stepping on each other, versus two friends at a café: the friend starts answering a moment after you stop, and stops talking the instant you cut in.

The idea in everyday words

A good waiter listens until you have clearly finished ordering (not at your first pause for breath), answers quickly, and if you interrupt with 'actually, no onions', stops mid-sentence and listens. A voice agent needs the same three skills: knowing when you are done, answering fast, and shutting up when interrupted. Text chat never needed any of them.

Two ways to build a voice agent

A voice agent listens to speech and speaks back, in real time, usually while also calling tools (look up an order, book a table).

1. Cascaded pipeline: three models in a row.

microphone → speech-to-text (STT) → LLM (text) → text-to-speech (TTS) → speaker

2. Speech-to-speech (S2S): one model takes audio in and produces audio out directly, with understanding and generation in the same model.

Cascaded Speech-to-speech
Latency Three hops add up Usually lower: one model, no hand-offs
Tone and emotion Lost at the STT step (text has no tone of voice) Can hear and respond to prosody (how something is said)
Control Swap any part; inspect and edit the text between stages; any LLM Fewer knobs; you pick from the voices and models offered
Debugging Easy: you have the exact transcript and answer text Transcripts are provided, but the reasoning is inside one model
Best for Complex reasoning with a strong text LLM, strict compliance wording, many languages Natural, fast conversation: support lines, assistants

Either way the agent is still an agent: a system prompt, tools, history, guardrails. Only the input and output became sound.

Key idea: cascaded gives control, speech-to-speech gives speed and natural tone. Many teams start cascaded and move hot paths to S2S.

The latency budget: time to first audio

In conversation, people usually start replying within a few hundred milliseconds of each other. A voice agent that takes 3 seconds feels broken, even if its answer is perfect.

The number to watch is time to first audio (TTFA): from the moment the user stops speaking to the moment they hear the first sound of the reply. It is a sum:

Stage What happens Typical size
Endpointing wait How long we wait in silence before deciding the user is done 200 to 800 ms, your choice
STT final The last words are transcribed ~100 to 300 ms
LLM time to first token Prefill the prompt, start generating a few hundred ms, grows with prompt length
TTS first chunk Synthesise the first bit of audio ~100 to 300 ms
Network and playback buffer Both directions tens to ~100+ ms

These are illustrative ranges: measure your own.

The single biggest win is streaming: do not wait for the whole answer. Start TTS as soon as the LLM has produced its first sentence, and play TTS audio while the rest is still being made.

# Time to first audio (ms) for three designs. Illustrative numbers.
designs = {
    "cascaded, no streaming": [("endpoint", 500), ("stt", 200), ("llm full answer", 1800), ("tts full answer", 700), ("net", 100)],
    "cascaded, streaming": [("endpoint", 500), ("stt", 200), ("llm first sentence", 400), ("tts first chunk", 200), ("net", 100)],
    "speech-to-speech": [("endpoint", 500), ("model first audio", 300), ("net", 100)],
}
for name, stages in designs.items():
    print(name.ljust(24), sum(ms for _, ms in stages), "ms")

Other levers: a smaller or faster model for the first reply, short system prompts with prompt caching, Regions close to the caller, and a short filler ("Let me check that for you") when a slow tool call is unavoidable.

Key idea: TTFA is a sum, so attack the biggest term first, and stream every stage so they overlap instead of adding up.

Hearing the end of a turn: VAD, endpointing and barge-in

Voice activity detection (VAD) decides, for each small chunk of audio (say every 20 to 100 ms), "is someone speaking?". The simplest VAD compares the chunk's energy (loudness) with a threshold; production VADs are small neural networks that ignore background noise.

Endpointing (turn detection) decides "has the user finished?". The classic rule: the turn ends after N chunks of continuous silence.

  • N too small: the agent jumps in at every pause for breath ("I want to book a... [agent starts talking]").
  • N too large: every reply feels slow, because the wait is part of TTFA.
  • Smarter systems also use semantic cues: "I want to book a" is clearly unfinished, "Thanks, bye" clearly is.

Short blips (a cough, a door slam, a click on the line) should not start a turn: require a minimum speech length.

Barge-in means the user interrupts the agent while it is talking. Doing it right takes four things:

  1. Keep listening while the agent speaks (full duplex).
  2. When VAD hears real user speech, stop playback immediately and clear the queued audio (the model often generates faster than real time, so seconds of audio may be waiting).
  3. Cancel the in-flight LLM or TTS generation.
  4. Record what was actually heard in the history (the agent did not say the rest).

Also needed: echo cancellation, so the agent's own voice from the speaker does not trigger barge-in, and care with backchannels ("mm-hm", "right") that are not real interruptions.

energy = [1, 7, 9, 2, 8, 9, 1, 1, 1, 1]   # one number per 100 ms chunk
threshold, min_silence = 5, 3
silence = 0
for t, e in enumerate(energy):
    if e >= threshold:
        silence = 0
        print(t, "speech")
    else:
        silence += 1
        print(t, "quiet", silence, "of", min_silence)
        if silence == min_silence:
            print("end of turn detected at chunk", t)
            break

Key idea: the endpointing wait is a trade-off between interrupting people and making them wait. Barge-in is the agent's ability to stop talking, instantly and cleanly.

Streaming everything, tools mid-call, and telephony

Stream every stage.

  • STT streams partial transcripts as the user speaks, then a final one. You can start retrieval early from partials.
  • The LLM streams tokens; cut them into sentences for TTS.
  • TTS streams audio chunks; play the first while the next is generated.
  • The transport is a long-lived two-way connection (WebSocket, WebRTC, or an HTTP/2 bidirectional stream), not request and response.

Tools mid-conversation. A voice agent that says nothing for 4 seconds while a tool runs feels dead.

  • Say a short filler first ("One moment, checking your order"), or keep talking while the tool runs (some S2S models handle tool calls asynchronously).
  • Give tools tight timeouts and a spoken fallback ("I can't reach the order system right now").
  • Confirm anything risky out loud with the details ("Refund 42 dollars to the card ending 1234, shall I go ahead?").

Speaking style is different from writing. Keep answers short, no bullet lists or tables, spell out numbers and codes in a speakable way ("12.50" → "twelve dollars fifty"), and ask one question at a time.

Telephony. Phone calls arrive over the public phone network or SIP, often as narrowband 8 kHz audio, with more noise and network delay than an app. You also need: call transfer to a human with context, keypad input (DTMF) for things like PINs, call recording consent, and graceful handling of silence ("Are you still there?").

Safety. Voice does not remove any agent risk: callers can still try prompt injection out loud, and transcripts contain personal data. Run guardrails on transcripts and answers, mask PII in logs, and verify identity before account actions.

Key idea: a voice agent is a streaming system first and an LLM app second.

Step by step

  1. The user speaks:

    Every 100 ms the microphone sends a chunk. Its energy is 7, 9, 8, 6: all at or above the threshold of 5, so VAD marks them as speech. A user turn is open from chunk 2.

  2. A short pause is not the end:

    Chunk 6 has energy 2 (a breath). The silence counter goes to 1 of 5. Then chunk 7 is speech again, so the counter resets to 0. Waiting for 5 quiet chunks in a row stops the agent from cutting in at every pause.

  3. End of turn:

    After the last speech chunk (9), chunks 10 to 14 are quiet. At chunk 14 the counter reaches 5: the turn is over. That 500 ms wait is already part of the latency.

  4. The pipeline runs:

    Cascaded: speech-to-text finalises 'what's my balance' (200 ms), the LLM streams its first sentence (400 ms), TTS synthesises the first chunk (200 ms). Every stage streams, so the reply can start before the full answer exists.

  5. First audio:

    The first reply audio plays at chunk 23: time to first audio = 500 + 200 + 400 + 200 = 1,300 ms after the user stopped. Switch to speech-to-speech and it drops to 800 ms.

  6. Barge-in:

    0.4 s into the reply the user says 'wait, savings'. VAD hears 2 speech chunks in a row while the agent is talking, which counts as a real interruption, not a cough.

  7. Stop and listen:

    Playback stops at once, the queued reply audio is thrown away, and generation is cancelled. The history records only the words the user actually heard. A new user turn is open and VAD waits for its end.

Code example

# Simulate one voice turn: VAD endpointing, then a streamed reply, then a barge-in.
# One tick = 100 ms. Numbers are illustrative.
energy = [1, 1, 7, 9, 8, 6, 2, 8, 9, 7] + [1] * 17 + [8, 9, 8, 7, 1, 1]
THRESHOLD, MIN_SILENCE = 5, 5
STAGES = [("stt", 2), ("llm first sentence", 4), ("tts first chunk", 2)]

silence, last_speech, turn_end = 0, None, None
for t, e in enumerate(energy):
    if e >= THRESHOLD:
        silence, last_speech = 0, t
    elif last_speech is not None:
        silence += 1
        if silence == MIN_SILENCE:
            turn_end = t
            break
print("user stopped after tick", last_speech, "| end detected at tick", turn_end)

first_audio = turn_end + 1 + sum(ticks for _, ticks in STAGES)
print("first audio at tick", first_audio, "| TTFA =", (first_audio - last_speech - 1) * 100, "ms")

reply = ["Your", "balance", "is", "four", "hundred", "twenty", "dollars."]
heard, run = [], 0
for k, word in enumerate(reply):
    t = first_audio + k
    run = run + 1 if t < len(energy) and energy[t] >= THRESHOLD else 0
    if run >= 2:   # two speech ticks in a row while we talk: a real interruption
        print("barge-in at tick", t, "-> stop playback, drop", len(reply) - k, "queued words")
        break
    heard.append(word)
print("history keeps only what was heard:", " ".join(heard))

Complexity

  • Time: O(n) for segment_turns: one pass over the energy chunks
  • Space: O(t) for the list of t turns

Interview tips

  • Design a voice support agent for a bank's phone line. Cascaded or speech-to-speech, and why? Walk through the latency budget.

  • What is barge-in, and what exactly must happen in the client and the server when the user interrupts?

  • How do you choose the endpointing silence threshold, and what goes wrong at each extreme? What is semantic turn detection?

  • The agent needs a 3-second tool call in the middle of a call. How do you keep the conversation natural?

  • How would you build this on AWS? (Nova Sonic over a bidirectional stream, or Transcribe + Bedrock + Polly, Amazon Connect for phone numbers, guardrails, logging)

Challenge: Find the turns in a VAD energy stream

Write segment_turns(energy, threshold, min_silence, min_speech) to split a stream of audio chunks into user turns.

  • energy: one integer per audio chunk, in time order. A chunk is speech when energy >= threshold, otherwise quiet.
  • A turn opens at the first speech chunk while no turn is open.
  • While a turn is open, count consecutive quiet chunks. Any speech chunk resets the count to 0 (short pauses do not split a turn).
  • When the count reaches min_silence, the turn closes. Record [start, end, detected_at]: start is its first speech chunk, end its last speech chunk, and detected_at the index of the chunk where the count reached min_silence.
  • If end - start + 1 < min_speech, the turn was a blip (a cough, a click): do not record it.
  • If the stream ends while a turn is open, record it with detected_at = None (null in JavaScript), if it is long enough.

Return the list of turns in order.

segment_turns([1, 1, 7, 9, 8, 6, 2, 8, 9, 7, 1, 1, 1, 1, 1, 1, 1], 5, 5, 2)
# → [[2, 9, 14]]   one turn: the quiet chunk 6 is only a short pause

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Frontier GenAI

Previous: Computer-Use, Browser & Coding Agents · Next: AI Agent Security: Prompt Injection & Tool Abuse