Voice Agent Architecture and Real-Time Audio

A voice agent is an ordinary agent with a clock running. Every design choice shows up as a pause, a misheard word or an interruption.

BeginnerIntermediateExpert · 13 min read · Last updated:

In short

A voice agent listens, decides and speaks while the audio is still flowing. You can chain separate parts (speech to text, a language model, text to speech) or use a speech-to-speech model that handles audio directly. The chain gives you visibility and control; direct audio can feel quicker and more natural. Either way, tools, permissions and records belong in your server, not in the audio stream.

What you will learn: the stages of a spoken turn, the two main architectures, transports, streaming, session state and tool calls, and two runnable measurements.
Prerequisites: The Agent Loop: Observe, Reason, Plan, Act, Reflect and Agent Tools, Function Calling and Tool Registries.

Versions used

Examples run in November 2026 with Python 3.13, eSpeak NG 1.51, FFmpeg and PocketSphinx 5.1.1. PocketSphinx is a small classic recognizer chosen because it runs offline; it does not represent the accuracy of current speech services. Latency figures in the pipeline example are assumptions, not measurements of any product.

Beginner One spoken turn

What happens between question and answer

Capturemicrophone or phone
Detect speechstart and end of turn
Recognizeaudio to text
Reason and actmodel and tools
Speaktext to audio
Real systems overlap these stages instead of waiting for each to finish.
TermPlain meaning
STT or ASRSpeech to text, also called automatic speech recognition
TTSText to speech, or speech synthesis
VADVoice activity detection: is someone speaking in this slice of audio?
EndpointingDeciding the speaker has finished a turn
Barge-inThe caller talks while the agent is speaking
FrameA short slice of audio, often around 20 milliseconds

Why voice is harder than chat

  • Time is visible. Silence feels broken. A study of ten languages found speakers generally avoid overlap and keep gaps short.
  • Input is uncertain. Names, numbers, accents, noise and bad lines cause errors.
  • Output cannot be skimmed. A list of nine options that reads well on screen is tiring to hear.
  • Nothing stays on screen. The caller must remember what was said, so confirm important details.
  • Interruptions change history. The caller may hear only half of the reply.

Two architectures

Audio in
STTtext you can log
Text modeltools, checks
TTSchosen voice
Audio out
Audio in
Speech-to-speech modelhears and speaks; requests tools
Audio out
Top: cascaded. Bottom: direct audio, with your server still running the tools.
QuestionCascaded pipelineSpeech-to-speech
Can I inspect the input?Yes, the transcript drives the modelTranscripts may be produced separately and differ from what the model heard
Can I check output before it is spoken?Yes, text passes through your codeHarder; audio is generated directly
Tone, hesitation, emphasisMostly lost at the text stepCan be used by the model
Swap one partEasyTied to one model
LatencyDepends on good streamingFewer hand-offs, but measure it
CostThree metersAudio token pricing; compare on real call lengths

Choose the cascade when you need text checks before anything is said, strong audit records, a particular voice or recognizer, or regulated wording. Try direct audio when natural conversation is the main value and you can accept the control trade-off. Many teams prototype both against the same test calls.

Intermediate Streaming and transport

Stream everything you can

Streaming means each stage starts on partial input. The recognizer emits interim text while the caller speaks, the model produces tokens, and the synthesizer starts on the first complete sentence or clause. This script shows the effect using assumed stage times.

"""Why stream? Time to first sound for three ways of wiring the same three stages.

All timings are assumed values on a virtual clock, so the result is repeatable.
Replace them with numbers measured on your own system.
"""
ENDPOINT_MS = 500          # silence waited before deciding the caller has finished
STT_FINAL_MS = 150         # streaming recognizer finalizes the transcript
STT_BATCH_MS = 900         # recognizer that starts only after the audio ends
FIRST_TOKEN_MS = 400       # model starts answering
PER_TOKEN_MS = 20
TTS_FIRST_MS = 180         # synthesizer returns the first audio for a piece of text
TTS_PER_TOKEN_MS = 8       # extra time when it must finish a whole piece first

REPLY = ("Your order shipped yesterday. It should arrive on Tuesday. "
         "Shall I send the tracking link to your phone?").split()


def sentences(tokens):
    piece = []
    for token in tokens:
        piece.append(token)
        if token.endswith((".", "?", "!")):
            yield piece
            piece = []
    if piece:
        yield piece


def batch():
    """Each stage waits for the whole output of the stage before it."""
    return (ENDPOINT_MS + STT_BATCH_MS + FIRST_TOKEN_MS + len(REPLY) * PER_TOKEN_MS
            + TTS_FIRST_MS + len(REPLY) * TTS_PER_TOKEN_MS)


def stream_text():
    """Streaming recognition, but speech starts only after the full reply."""
    return (ENDPOINT_MS + STT_FINAL_MS + FIRST_TOKEN_MS + len(REPLY) * PER_TOKEN_MS
            + TTS_FIRST_MS)


def stream_sentences():
    """Send each finished sentence to speech while the model keeps writing."""
    first = next(sentences(REPLY))
    return (ENDPOINT_MS + STT_FINAL_MS + FIRST_TOKEN_MS + len(first) * PER_TOKEN_MS
            + TTS_FIRST_MS)


print(f"reply: {len(REPLY)} words in {len(list(sentences(REPLY)))} sentences "
      "(one word counted as one token)")
for label, wiring in [("batch every stage", batch),
                      ("stream recognition only", stream_text),
                      ("stream by sentence", stream_sentences)]:
    print(f"{label:<26} first sound after {wiring():>5} ms")
print(f"of which endpoint silence: {ENDPOINT_MS} ms in every design")

Output:

reply: 18 words in 3 sentences (one word counted as one token)
batch every stage          first sound after  2484 ms
stream recognition only    first sound after  1590 ms
stream by sentence         first sound after  1310 ms
of which endpoint silence: 500 ms in every design

With these assumptions, streaming roughly halves the wait before the first sound. Notice what streaming cannot remove: the silence you wait before deciding the caller has finished. That setting is a trade-off studied in Voice Latency, Turn-Taking, Quality and Privacy.

Streaming has a price

Once a sentence is spoken it cannot be taken back. If a safety check needs the whole reply, either check each chunk before it is spoken, or hold the reply for risky topics. Decide this per kind of answer rather than turning checks off to gain speed.

Chunking text for speech

Split at sentence or clause boundaries so the voice sounds natural. Watch for abbreviations and decimals ("Dr.", "3.50"), which simple splitting gets wrong. Normalize text before synthesis: dates, amounts, codes and web addresses need a spoken form, and order numbers should be read in groups.

Choose a transport

TransportTypical useNotes
WebRTCBrowsers and mobile appsBuilt for live media; handles jitter and changing networks
WebSocketServer to server streamsSimple; you manage buffering and timing
SIP and telephonyPhone numbers and contact centersSee Contact Center and Telephony Voice Agents

Providers differ. For example, Microsoft documents the OpenAI Realtime API in Azure as usable through WebRTC, SIP or WebSocket. For a browser client, never ship a long-lived API key: have your server create a short-lived credential for the session, if the provider offers one, or relay the audio through your server.

Audio details that cause bugs

  • Sample rate and encoding must match at every hop. Traditional phone audio is narrowband, commonly 8 kHz, which removes detail a recognizer would use.
  • Echo cancellation stops the agent hearing itself and interrupting its own sentence.
  • Jitter buffers smooth uneven arrival but add delay.
  • Resampling poorly can reduce recognition accuracy.

Test recognition under changing conditions

The next script synthesizes four phrases in two voices at two speeds and recognizes them twice: with an open vocabulary and with a grammar that only allows those phrases. Install eSpeak NG and FFmpeg, then run pip install pocketsphinx.

"""Speak phrases with a synthesizer, recognize them offline, and score the result."""
import subprocess
import tempfile
from pathlib import Path

from pocketsphinx import Decoder

PHRASES = ["where is my order", "i want to cancel my subscription",
           "please send the invoice to my email", "can i speak to a person"]
CONDITIONS = [("en-us", 120), ("en-us", 160), ("en-gb", 120), ("en-gb", 160)]


def speak(text, voice, rate):
    """Text to speech, then convert to 16 kHz mono PCM for the recognizer."""
    wav = subprocess.run(["espeak-ng", "-v", voice, "-s", str(rate), "--stdout", text],
                         check=True, capture_output=True).stdout
    return subprocess.run(["ffmpeg", "-loglevel", "quiet", "-i", "pipe:0", "-ar", "16000",
                           "-ac", "1", "-f", "s16le", "pipe:1"],
                          input=wav, check=True, capture_output=True).stdout


def recognize(decoder, audio):
    decoder.start_utt()
    decoder.process_raw(audio, full_utt=True)
    decoder.end_utt()
    result = decoder.hyp()
    return result.hypstr if result else ""


def word_errors(expected, heard):
    """Smallest number of word insertions, deletions and substitutions."""
    a, b = expected.split(), heard.split()
    row = list(range(len(b) + 1))
    for i, x in enumerate(a, 1):
        previous, row[0] = row[0], i
        for j, y in enumerate(b, 1):
            previous, row[j] = row[j], min(row[j] + 1, row[j - 1] + 1, previous + (x != y))
    return row[-1]


def main():
    with tempfile.TemporaryDirectory() as tmp:
        grammar = Path(tmp) / "phrases.gram"
        grammar.write_text("#JSGF V1.0;\ngrammar phrases;\npublic <phrase> = "
                           + " | ".join(PHRASES) + ";\n")
        decoders = {
            "open vocabulary": Decoder(samprate=16000, loglevel="FATAL"),
            "fixed phrases": Decoder(samprate=16000, loglevel="FATAL",
                                     lm=None, jsgf=str(grammar)),
        }
        total_words = sum(len(p.split()) for p in PHRASES)
        print(f"{'voice':<6} {'speed':>5}   " + "   ".join(f"{n:>22}" for n in decoders))
        for voice, rate in CONDITIONS:
            cells = []
            for decoder in decoders.values():
                heard = [recognize(decoder, speak(p, voice, rate)) for p in PHRASES]
                errors = sum(word_errors(p, h) for p, h in zip(PHRASES, heard))
                exact = sum(p == h for p, h in zip(PHRASES, heard))
                cells.append(f"WER {errors / total_words:>4.0%}, exact {exact}/{len(PHRASES)}")
            print(f"{voice:<6} {rate:>5}   " + "   ".join(f"{c:>22}" for c in cells))


if __name__ == "__main__":
    main()

Output:

voice  speed          open vocabulary            fixed phrases
en-us    120      WER  96%, exact 0/4      WER   0%, exact 4/4
en-us    160      WER  74%, exact 0/4      WER  30%, exact 2/4
en-gb    120      WER  96%, exact 0/4      WER  22%, exact 3/4
en-gb    160      WER 100%, exact 0/4      WER  26%, exact 3/4

WER, word error rate, is the number of inserted, deleted and replaced words divided by the number of words expected. Three lessons carry over to better recognizers, even though the numbers will not:

  1. Telling a recognizer what to expect (grammars, phrase hints, custom vocabulary) can change results sharply.
  2. A change of speaker or speed can move accuracy from perfect to poor, so one test voice proves little.
  3. A constrained recognizer can only hear what you allowed. Callers who say something else need a fallback, and a confident wrong match is a risk.

Synthetic speech is not a substitute for recordings of real people, collected with consent, on the phones and in the places your callers use.

Expert The reference architecture

Components of a production voice agent

Edgeweb, app or telephony; media server; echo control
Turn managerspeech detection, endpointing, barge-in, timeouts
Speech and model layercascade or speech-to-speech, with fallbacks
Agent corestate, policy, tools, approvals
SystemsCRM, orders, knowledge, human queue
Evidencetraces, redacted transcripts, quality metrics

Session state

Keep conversation state on the server, keyed by a call id: verified identity and how it was verified, the current task, collected values with confirmation status, pending actions, what the caller actually heard, and language. If the connection drops, a reconnect should resume safely rather than repeat an action. See Stateful and Long-Running Agent Architecture.

Tools while someone waits

  1. Say what you are doing when a call may take more than a moment ("Let me check that order").
  2. Set a timeout and a spoken fallback for every tool.
  3. Collect and confirm required values before calling anything that changes data.
  4. Use an idempotency key so a retry cannot refund twice (Reliable Tool Execution and Error Recovery).
  5. Cancel or ignore results that arrive after the caller changed their mind, but check whether the action already happened.
A voice is not an identity

Synthetic voices can imitate people. Do not treat "it sounded like the account holder" as proof, and do not rely on caller ID alone. Use a separate factor suited to the risk (Agent Identity, Authorization and Secrets).

Prompting for speech

Ask for short sentences, one question at a time, no markdown, no lists longer than three items and clear read-back of numbers. State what to do when audio is unclear: ask again once, rephrase, then offer another channel. Instructions spoken by a caller, or heard from a recording or a television in the background, are untrusted input like any other (Prompt Injection Attacks and Defenses).

Degrade gracefully

FailureFallback
Recognizer slow or downSecond provider, keypad input or human transfer
Model timeoutShort apology, retry once, then transfer
Synthesis failurePre-recorded essential messages
Poor line qualityOffer a callback or a text message link
Repeated misunderstandingEscalate after a fixed number of attempts

Languages, voices and access

Each language you offer is a separate quality problem. Recognition, turn-taking habits, number and date formats, synthesis quality and tool data all differ. Decide how the agent learns the language (a menu, the first utterance or the customer record), let callers change it, and do not switch because of one borrowed word. Test mixed-language speech if your callers use it.

Choose a voice that is clear on a poor line before one that sounds impressive in headphones. Offer slower speech and repetition on request. Some people cannot use a voice channel at all, so provide text, relay or human routes to the same service and mention them early.

What to record for every turn

FieldWhy you will want it
Call and turn identifiersJoin audio events to traces
Speech start, end of turn, first audioCompute real delay
Recognized text and confidence, redactedDiagnose misunderstanding
Tool calls, results and approvalsExplain what changed
Interruption pointKnow what the caller heard
Component versionsTie a change in quality to a release

A sensible build order

  1. Write ten real tasks and the facts each needs.
  2. Make the agent work in text, with its tools and permissions tested.
  3. Add recognition and synthesis in a quiet browser test.
  4. Add endpointing and barge-in, and measure latency per stage.
  5. Record consented test calls with noise and varied speakers.
  6. Connect telephony and the human handoff.
  7. Pilot with a small share of calls and review failures weekly.
Keep text as a test harness

Most task logic can be tested quickly and cheaply in text. Keep audio tests for what only audio can break.

Common mistakes

MistakeBetter practice
Waiting for each stage to finishStream between stages and measure first sound
Reusing a chat prompt unchangedWrite for listening: short, one question at a time
Putting business rules in the audio model's prompt onlyEnforce rules in server code
API keys in the browserShort-lived credentials or a relay
Assuming the caller heard the whole replyTrack played audio and update history
Testing with one clear voiceVary speakers, noise, devices and speed

Checklist

  • Architecture chosen with its control trade-off written down
  • Latency measured per stage and at the first sound
  • State kept server side and safe to resume
  • Tools have timeouts, idempotency and confirmation
  • Callers are told they are talking to an AI
  • Human transfer works and carries context
  • Every component has a fallback

Frequently asked questions

How fast must a voice agent reply?

There is no single threshold. Faster is usually better until the agent starts cutting people off, so test several settings with real callers and watch both delay and interruptions.

Do I need a speech-to-speech model?

No. A well-streamed cascade serves many tasks and is easier to inspect. Compare both on your own calls.

Can I add voice to an existing chat agent?

You can reuse its tools and policies, but rework prompts, confirmations, timeouts, error handling and tests for speech.

Should audio be stored?

Only if you have a lawful purpose and have told people as required. Often a redacted transcript or just the outcome is enough.

References and further reading

Next steps