09.6 Audio-Native Models and Realtime Foundations
Lesson 09.4 taught you to turn recordings into text, and 09.5 to turn text into speech. This lesson asks the harder question: what if the model should hear and speak directly, in a live conversation, with no transcript in between? There are two fundamentally different architectures for that — the cascaded pipeline (speech-to-text → language model → text-to-speech) and speech-to-speech / audio-native models that take audio in and produce audio out. Choosing between them, and building the plumbing either way needs, is the engineering of realtime voice. This lesson covers both architectures and their honest trade-offs, sending audio to ordinary chat models for understanding, the realtime transports (WebSocket, WebRTC, SIP), the audio formats on the wire, turn-taking (voice activity detection, end-of-turn detection, barge-in), the event-driven session model, telephony basics, a pure-Python lab for every piece of audio plumbing, and the cost and latency arithmetic that decides whether a voice feature is viable.
What you'll learn
- The two architectures for voice AI — cascaded pipeline vs speech-to-speech — with a rigorous trade-off table and when each wins
- How to send audio files to general chat models (OpenAI, Gemini, OpenRouter) for understanding beyond transcription: tone, music, sound events
- The four realtime transports — HTTP streaming, WebSocket, WebRTC and SIP/telephony — and which to pick for which client
- Audio formats on the wire: PCM16 at 16/24 kHz, μ-law at 8 kHz, base64 chunks in JSON events, frame sizes and chunking cadence
- Jitter, buffering, packet loss, echo cancellation and noise suppression — and why they decide whether voice feels natural
- Latency budgets: every stage from microphone to speaker, what humans expect (turn gaps of roughly 0–300 ms), and a calculator you can run
- Turn-taking: energy VAD vs ML VAD (Silero) vs semantic turn detection, provider server-VAD options, barge-in and truncating the assistant's turn, backchannels, half- vs full-duplex
- The event-driven session model: client events and server events mapped across providers, session state machines, idempotent event handling, reconnection and session limits
- Telephony basics: SIP/PSTN, carriers like Twilio, Telnyx and Vonage, μ-law audio, DTMF, consent and cost per minute
- A pure-Python lab — WAV generation, resampling, PCM16 ↔ float, μ-law, base64 chunking, energy VAD, a jitter-buffer simulation — all runnable with no API keys
- Cost and latency arithmetic for realtime sessions, and the privacy, consent and safety obligations of voice systems
What you don't need
- API keys. Every concept has something you can run for free: the entire audio-plumbing lab is pure Python standard library. The provider samples are written against official documentation and labelled illustrative; lesson 03.1, Part 12 covers a free local stand-in for text models.
- How STT, TTS or tool calling work in depth — those are 09.4, 09.5, 09.7 and Module 08A.
- WebRTC or SIP expertise. This lesson explains what each transport is for; the provider samples show the parts your code touches.
Setup
The lab needs only Python 3.11+ and the standard library — no packages, no keys:
python3 --version # needs 3.11 or newer; tested on 3.14The illustrative provider samples use the SDKs from Module 03 (openai, google-genai, python-dotenv) plus websocket-client for the raw WebSocket example; they were checked against openai 3.42.1, google-genai 2.34.0 and websocket-client 1.9.2 as of November 2026, and a plain install gives you the newest release of each. If you don't have the llm-apis project yet, create one first (uv init llm-apis --bare --python 3.13 && cd llm-apis, see lesson 03.1, Part 4), then:
uv add openai google-genai python-dotenv websocket-client
# or: pip install openai google-genai python-dotenv websocket-clientKeys go in .env (OPENAI_API_KEY, plus the optional GEMINI_API_KEY and OPENROUTER_API_KEY) — never hard-code them. The lab file is audio_lab.py in the lesson's work directory; every output shown is real output from running it.
What you must be able to do after this lesson#
- Compare cascaded and speech-to-speech voice architectures
- Send audio to a general chat model for understanding
- Choose a realtime transport such as WebSocket, WebRTC or SIP
- Explain how turn-taking and barge-in work
- Calculate a latency and cost budget for a realtime session
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "Should we use a speech-to-speech model or chain STT → LLM → TTS?" | Part 1: Two architectures |
| "The cascaded pipeline is more debuggable." | 1.3 The honest trade-off table |
| "Can the model hear the customer's frustration, not just the words?" | Part 2: Audio into text models |
| "WebRTC or WebSocket for the voice app?" | 3.1 The four transports |
| "Why is the audio all crackly / robotic / out of sync?" | 3.3 Jitter, loss, echo and noise |
| "The agent always interrupts me / never interrupts me." | Part 4: Turn-taking |
| "It keeps answering things I didn't finish saying." | 4.2 End-of-turn detection |
| "The agent forgot what it said before I interrupted." | 4.3 Barge-in and truncation |
| "What events does a realtime session send?" | Part 5: Session design |
| "The call drops after 15 minutes." | 5.4 Session limits and reconnection |
| "How do we put this on a phone line?" | Part 6: Telephony |
| "Why does a 3-minute call cost so much?" | Part 8: Cost and latency arithmetic |
Part 1: Two architectures for voice AI#
1.1 The cascaded pipeline#
The cascaded pipeline — also called a chained or pipeline voice agent — runs three separate models in sequence:
flowchart LR
Mic["🎤 microphone"] --> STT["Speech-to-text<br/>(09.4)"]
STT -->|"transcript text"| LLM["LLM<br/>(any text model)"]
LLM -->|"reply text"| TTS["Text-to-speech<br/>(09.5)"]
TTS --> Spk["🔊 speaker"]Each stage is a separate API call (or a local model), and your application orchestrates them: it streams audio to the STT service, feeds partial transcripts to the LLM, streams the LLM's text output into the TTS service, and plays the audio that comes back. Every stage is observable: you can log the exact transcript, the exact prompt, the exact text sent to TTS, and the exact audio produced. You can swap any stage independently — a cheaper STT, a stronger LLM, a more natural voice — and you can insert your own logic between stages (redact PII from the transcript before the LLM sees it, validate the reply before it's spoken).
The cost of that control is latency stacking. Each stage adds its own delay: STT finalisation, LLM time-to-first-token, TTS time-to-first-audio. Naively summed, a cascaded agent can take 1.5–3+ seconds from end-of-speech to first audio — too slow for natural conversation, though fine for voicemail-style or asynchronous "speak a notification" use cases. The engineering of a good cascaded agent is mostly about hiding that latency: streaming every stage, starting TTS on the first sentence rather than the whole reply, and pre-empting work (see 09.5 and 09.7).
1.2 Speech-to-speech / audio-native models#
A speech-to-speech (also called audio-native or realtime) model takes audio in and produces audio out inside one model. There is no transcript in the middle: the model hears your tone, your hesitation, the street noise behind you, and it answers in a voice with its own prosody. As of November 2026, the hosted options are:
| Provider | Product | Models (as of November 2026) | Transport |
|---|---|---|---|
| OpenAI | Realtime API | gpt-realtime-2.1 (flagship reasoning model), gpt-realtime-2, gpt-realtime-1.5, gpt-realtime-mini, gpt-realtime-2.1-mini, plus gpt-audio-1.5 / gpt-audio-mini audio chat models; gpt-realtime is deprecated (shutdown 20 January 2027) but still callable |
WebRTC, WebSocket, SIP |
| OpenAI | Live API (v1/live/sessions) |
gpt-live-1 — a full-duplex voice model that delegates reasoning and tool use to a separate backend agent |
WebRTC, WebSocket |
| Anthropic | — | No audio or realtime API. The Messages API accepts text and image input and returns text. A Claude voice agent is always cascaded (verified on Anthropic's models documentation, November 2026) | — |
| Gemini Live API | gemini-3.8-live, gemini-3.8-live-extended-thinking, gemini-3.1-flash-live-preview (retires 17 Nov 2026), gemini-2.5-flash-native-audio-preview-12-2025 (retires 17 Nov 2026); gemini-live-2.5-flash-native-audio on Vertex AI |
WebSocket (WSS) | |
| OpenRouter | — | No realtime session API. It proxies audio-input chat models and offers /audio/speech + /audio/transcriptions endpoints, but nothing that holds a live audio session |
— |
Two things are worth noticing immediately:
- "Audio-native" doesn't mean one thing. OpenAI's Realtime API is a single speech-to-speech model that also does reasoning and tool calls in-session. OpenAI's newer
gpt-live-1is a full-duplex voice frontend that delegates the hard thinking to a separate backend model — a hybrid by design. Gemini's Live API is a single audio-native model with optional non-blocking function calls. All three are "realtime", but they sit at different points on the controllability spectrum. - Anthropic's absence is real and structural. Claude is a text-and-image model; there is no audio modality to call. Any "Claude voice agent" is a cascaded pipeline where Claude is the brain — which is a perfectly good design, and 09.7 builds one.
1.3 The honest trade-off table#
This is the table that decides architecture. Read it before you fall in love with either approach.
| Dimension | Cascaded (STT → LLM → TTS) | Speech-to-speech (Realtime / Live API) |
|---|---|---|
| Time to first audio | Poor out of the box (1.5–3 s); good pipelines reach ~0.8–1.5 s with streaming tricks | Best-in-class; models are trained for it. Typically the lowest of any architecture, though exact figures are provider- and network-dependent — measure your own |
| Naturalness / prosody | Good, and improving; limited by the TTS voice and the loss of vocal nuance in the transcript | Highest: the model hears tone, hesitation, emotion and answers with matched expressiveness |
| Interruptibility (barge-in) | You build it: VAD on input, cancel TTS playback, decide what the LLM "heard" | Built in: provider VAD detects speech over the model's own audio and cancels generation |
| Tool use | Full control: the LLM calls tools exactly as in text (Module 08A); results come back as text and get spoken | Varies: OpenAI Realtime and Gemini Live support function calling mid-session; gpt-live-1 delegates tools to your backend. Constraints and latencies differ — check the current docs |
| Controllability / debuggability | Highest: every stage's input and output is text or a file you can log, replay and test | Lower: audio tokens are opaque; you get transcripts if you enable them, but the model "heard" more than the transcript shows |
| Cost model | Sum of three metered services (STT minutes + LLM tokens + TTS characters), each optimisable separately | One session, billed by audio/text tokens (OpenAI Realtime), per-minute audio rates (Gemini Live), or per-second session time plus backend (gpt-live-1) — see Part 8 |
| Transcript availability | You own the transcript by construction | Optional: both OpenAI and Gemini can emit input/output transcription events; you must enable and store them yourself |
| Languages | Depends on the weakest stage (STT and TTS language coverage) | Often broader and code-switching is handled inside the model (Gemini Live advertises ~99 languages and seamless switching) |
| Voice choice | Any TTS voice on the market, including cloned/brand voices | A fixed catalogue of provider voices (e.g. OpenAI's marin, cedar, ash…; Gemini Live exposes its TTS voice set) |
| Determinism | Same text pipeline as your chat products — you know its failure modes | New failure modes: it may "hear" things that weren't said, respond to background noise, or adopt a persona you didn't intend |
| Vendor lock-in | Low: swap any stage; the LLM brain can be any provider | High: the session API, event model and voice are provider-specific |
The pattern to internalise: cascaded buys you control and observability; audio-native buys you latency and presence. The right answer is rarely pure — see hybrids next.
1.4 Hybrid designs#
Because the extremes each have a real cost, production systems mix them:
gpt-live-1-style delegation (OpenAI's own answer to this): a full-duplex voice model handles the conversation — listening, speaking, interruptions — while delegating reasoning and tool use to a backend agent you control (any Responses model, your own logic). You get realtime feel with a text brain you can debug.- Audio-native conversation + text tools: use the realtime model for the dialogue, but let it call your tools (order lookup, calendar) whose results come back as text the model then speaks. This is what OpenAI Realtime's function calling and Gemini Live's function calling do; 09.7 implements it.
- Cascaded with a realtime front-end: streaming STT → your LLM → streaming TTS, but with every stage streaming and sentence-level TTS pipelining, so first audio lands near a speech-to-speech model's latency while keeping full text observability. Frameworks like Pipecat and LiveKit Agents exist precisely to assemble this well.
- Route by need: a simple FAQ voice bot on a cheap cascaded pipeline; a sales or support conversation on an audio-native model where prosody and interruption handling earn their cost.
1.5 Choosing: the decision table#
| Your situation | Pick |
|---|---|
| Notifications, IVR menus, read-backs, "speak this text" | Cascaded or pure TTS — no conversation needed |
| Voice Q&A over your docs, moderate latency tolerance, tight cost control | Cascaded with streaming stages |
| Customer-facing conversation where interruptions and tone matter | Speech-to-speech (Realtime / Live API) |
| You must log/audit every word and reasoning step | Cascaded, or gpt-live-1-style delegation with a text backend |
| Complex tool use, RAG, business rules mid-call | Cascaded, or hybrid (audio-native front + tool-using backend) |
| Multi-language callers, code-switching | Audio-native (Gemini Live's multilingual handling is a real advantage) |
| Phone calls at scale, per-minute pricing pressure | Compare per-minute telephony + STT/TTS stack vs per-token realtime session — Part 8 has the arithmetic |
| Prototype / proof of concept | Cascaded: faster to build, easier to debug, works with any LLM |
Part 2: Audio input to general models#
Deep-dive
Before realtime, there's a quieter capability worth knowing: several ordinary chat models accept audio files as input. This isn't transcription — it's understanding. You can ask a model to describe the mood of a voice note, identify instruments in a song, classify a sound event (a door slam, a dog bark, glass breaking), or answer questions about a recording that a transcript would lose entirely.
2.1 Which providers take audio, and how#
The request mechanics — inline base64 vs file upload, MIME types, size limits — are owned by lesson 03.6, Part 8; this section is about when audio understanding beats STT + text and what it costs. As of November 2026:
| Provider | Audio input? | Route | Notes |
|---|---|---|---|
| OpenAI | ✅ Chat Completions audio models (e.g. gpt-audio-1.5) |
input_audio content part {"data": "<base64>", "format": "wav"} |
The Responses API's text/image input doesn't cover audio chat models the same way — check the model page. Audio is billed as audio tokens; OpenAI doesn't publish a fixed audio-tokens-per-second rate for chat audio models, so estimate with the tokenizer/usage on a real clip, as with Gemini |
| Anthropic | ❌ | — | Messages API has no audio block; verified against Anthropic's docs, November 2026 |
| Gemini | ✅ | Part.from_bytes(data=..., mime_type="audio/mp3") on generate_content, or Files API for longer clips |
Up to ~9.5 hours per prompt per Google's docs; billed ~25–32 audio tokens/second (Google's pages disagree — measure with count_tokens, see 03.6 §2.4) |
| OpenRouter | ✅ per model | input_audio content part, base64 only ("direct URLs are not supported for audio content") |
Filter the catalogue by architecture.input_modalities containing "audio" — the field 03.6 §2.5 shows |
2.2 When audio understanding beats STT → text#
| Situation | Better tool | Why |
|---|---|---|
| You need the exact words | Dedicated STT (09.4) | ASR models are more accurate and cheaper per minute than a chat model "listening" |
| Tone, emotion, sarcasm, hesitation matter | Audio-native understanding | The transcript throws away prosody; "fine." said flatly vs cheerfully are different inputs |
| Music, sound effects, non-speech audio | Audio understanding | There are no words to transcribe |
| Meeting notes, subtitles, search over speech | STT (09.4), then text | Text downstream is cheaper and composable |
| "What did they mean?" follow-ups on a recording | Audio understanding | The model can re-listen; a transcript can't |
| Long recordings (hours) | STT + chunked text | Audio tokens accrue per second; an hour of audio is ~90k–115k tokens on Gemini — count before you send |
2.3 A minimal example (illustrative)#
# audio_qa_gemini.py — ask Gemini about a voice memo's *delivery*, not just its words.
# Needs GEMINI_API_KEY in .env. Output is illustrative.
import os
from pathlib import Path
from dotenv import load_dotenv
from google import genai
from google.genai import types
load_dotenv()
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
audio = Path("voice_memo.mp3").read_bytes() # your own recording
response = client.models.generate_content(
model="gemini-3.8-flash",
contents=[
types.Part.from_bytes(data=audio, mime_type="audio/mp3"),
"In one sentence: what is the speaker's emotional state, "
"and did they sound hesitant anywhere?",
],
)
print(response.text)The speaker sounds mildly frustrated but controlled; the hesitation is
noticeable around "the deadline", where they pause and lower their voice.The same file sent to a chat model with only its transcript could answer "what did they say" but not "how did they say it". That distinction is the entire reason audio input exists.
Part 3: Realtime transport fundamentals#
A realtime voice session moves audio continuously between client and server. How it moves decides latency, robustness and which clients you can support. There are four transports, and they solve different problems.
3.1 The four transports#
| Transport | What it is | Audio path | Strengths | Weaknesses | Used for |
|---|---|---|---|---|---|
| HTTP streaming (SSE/chunked) | Ordinary request/response, response body streamed | Not suitable for bidirectional live audio; fine for "send a clip, get a streamed transcript/answer" | Simplest; works through every proxy/firewall | One direction at a time; reconnect = new request; high per-request overhead | File transcription, one-shot audio Q&A, TTS streaming output |
| WebSocket (WSS) | Persistent bidirectional text/binary socket | You send base64 PCM in JSON events; server sends base64 PCM events back | Full control; works from any server-side language; exact event model | You handle jitter/buffering/playback yourself; browsers can use it but WebRTC is better | Server-side agents, telephony gateways, non-browser clients, provider server SDKs |
| WebRTC | Peer-to-peer-ish media protocol with built-in codecs, jitter buffers, echo cancellation, NAT traversal | Raw audio tracks (Opus typically) + a data channel for JSON events | Media handled by battle-tested stack; browser-native (getUserMedia, RTCPeerConnection); built-in AEC/NS/jitter buffer |
More setup (SDP offer/answer, ICE, ephemeral tokens); less control over the media path | Browser and mobile clients — the default choice for web voice apps |
| SIP / PSTN | The telephone network's signalling (SIP) and circuit/packet voice (PSTN) | μ-law 8 kHz audio through carrier infrastructure | Reaches any phone on Earth; carriers handle the messy media | 8 kHz narrowband audio; carrier costs; signalling complexity lives at the carrier | Phone-call voice agents (inbound and outbound) |
The rule of thumb: browser or mobile app → WebRTC; server-side or telephony gateway → WebSocket; a phone call → SIP via a carrier. OpenAI's Realtime API supports all three (WebRTC for browsers via ephemeral client secrets, WebSocket for servers, SIP for calls); Gemini Live API is WebSocket-only — browsers connect directly with ephemeral tokens, or you proxy through your server.
3.2 Audio formats on the wire#
Whatever the transport, the audio itself is almost always raw PCM — uncompressed pulse-code modulation — because codecs add latency and complexity you don't want inside a realtime loop.
| Parameter | Typical values | Who uses it |
|---|---|---|
| Sample rate | 16 kHz (speech-standard input), 24 kHz (high-quality output), 48 kHz (studio/mic native) | Gemini Live: input natively 16 kHz (resamples anything you send), output fixed 24 kHz. OpenAI Realtime: PCM at 24 000 Hz in the session examples; output configurable audio/pcm or audio/pcmu |
| Bit depth | 16-bit signed little-endian (PCM16) — the universal choice | Both providers; telephony's μ-law is 8-bit companded |
| Channels | Mono (1) | Always for voice agents |
| μ-law / A-law (G.711) | 8 kHz, 8-bit companded | PSTN/telephony only — narrowband but battle-tested |
| Frame/chunk size | 20–40 ms of audio per send | Guidance varies between provider docs and samples — Gemini recommends 20–40 ms chunks; one OpenAI Go sample uses ~200 ms chunks (9600 bytes of PCM16@24k). Pick per provider docs and measure |
| Encoding in JSON events | Base64 of raw PCM bytes | WebSocket transports wrap audio in base64 inside JSON events — the "33% tax" of 03.6 §1.3 applies here too |
Why these numbers? 16 kHz captures the 8 kHz bandwidth speech needs (telephone quality and better); 24 kHz leaves headroom for the model's richer output voice; 20 ms frames balance overhead (too small = too many messages) against latency (too large = chunky, delayed audio). A 20 ms frame of 16 kHz mono PCM16 is 320 samples = 640 bytes → 856 base64 chars inside one input_audio_buffer.append JSON event (~906 chars with the JSON envelope, as measured in 7.4) — small enough to send 50×/second without strain.
3.3 Jitter, loss, echo and noise#
Realtime audio is a stream, not a file: packets arrive with variable delay (jitter), some never arrive (loss), and the two directions can bleed into each other (echo). Each has a standard countermeasure:
- Jitter buffer: hold incoming audio briefly and play it at a steady cadence. WebRTC does this internally; on WebSocket you implement it (the lab's jitter-buffer simulation shows the mechanics). Too small a buffer → choppy audio; too large → added delay. Typical targets are tens of milliseconds.
- Packet loss: WebRTC's Opus codec is loss-resilient; on WebSocket PCM there's no resilience — a lost chunk is a click of silence. This is why WebRTC is preferred for browser media and WebSocket is fine for server/gateway hops on reliable networks.
- Echo cancellation (AEC): the speaker's own output leaks into the mic. Browsers and phones do AEC in hardware/software if you use their audio stacks (WebRTC's
getUserMedia/RTCPeerConnectiongives you this for free). On a raw WebSocket pipeline you must AEC yourself or require headsets. This is the single biggest reason "speakerphone voice agents" are hard. - Noise suppression (NS): same story — WebRTC gives you NS; raw pipelines need RNNoise-class processing or a quiet room.
3.4 Latency budgets#
A voice round trip has measurable stages. Here's a realistic budget for a speech-to-speech agent (your numbers will differ — the point is the shape):
| Stage | Typical ms | What drives it |
|---|---|---|
| Mic capture + resample to 16 kHz | ~10 | Buffer size, resampler quality |
| Uplink network (client → provider) | 20–80 | Geography, connection type (Wi-Fi vs cellular) |
| Server VAD: detect end-of-speech | 200–800 | silence_duration_ms / end_of_speech_sensitivity settings |
| Model: end-of-turn → first audio token | 200–600 | Model size, reasoning effort, load |
| Downlink network (provider → client) | 20–80 | Same as uplink |
| Jitter buffer + playback start | 20–80 | WebRTC internal; your buffer on WebSocket |
| Total: speech end → first audio heard | ~0.5–2.0 s | Everything above, summed |
What do humans expect? Conversational turn gaps in natural speech are typically 0–300 ms (median under 300 ms across ten languages in the cross-linguistic study by Stivers et al., PNAS 2009), and speakers anticipate turn endings because producing speech takes 600–1,500 ms. A voice agent answering within ~0.5–1.0 s of your finishing feels responsive; past ~1.5–2 s it feels like a slow IVR. The VAD silence wait and the model's time-to-first-audio are the two biggest levers — everything else is tens of milliseconds.
# latency_budget.py — pure Python; run it and tweak the numbers.
def latency_budget(stages):
total = 0
print(f"{'stage':<36}{'ms':>6}")
for name, ms in stages:
total += ms
print(f"{name:<36}{ms:>6}")
print(f"{'TOTAL':<36}{total:>6}")
verdict = ("feels conversational" if total <= 800
else "noticeable pause" if total <= 1500
else "feels broken/IVR-like")
print(f"\n{total} ms end-of-speech -> first audio: {verdict}")
latency_budget([
("mic capture + resample", 10),
("uplink network", 40),
("server VAD end-of-turn wait", 500),
("model time-to-first-audio", 350),
("downlink network", 40),
("jitter buffer", 60),
("playback start", 10),
])stage ms
mic capture + resample 10
uplink network 40
server VAD end-of-turn wait 500
model time-to-first-audio 350
downlink network 40
jitter buffer 60
playback start 10
TOTAL 1010
1010 ms end-of-speech -> first audio: noticeable pauseThe lesson: shaving the VAD wait from 500 → 300 ms and the model's first-audio from 350 → 250 ms takes you under 800 ms — that's the difference between "okay" and "good". This is why providers expose VAD sensitivity and why reasoning effort is a latency knob on realtime models.
Part 4: Turn-taking#
Conversation is a turn-taking protocol. Humans yield and take turns with gaps of ~0–300 ms and almost no overlap; a voice agent must detect when you've finished speaking (so it can reply) and when you're interrupting it (so it can stop). Two different detectors do this work.
4.1 Voice activity detection (VAD)#
VAD answers "is someone speaking right now?" — it does not answer "are they done?" (that's end-of-turn detection, §4.2). There are three generations:
| Type | How it works | Examples | Trade-offs |
|---|---|---|---|
| Energy VAD | Frame the audio; flag frames whose RMS energy exceeds a threshold, with hangover | The lab's energy_vad below |
Free, instant, works anywhere — but fires on any loud noise (a cough, a dog, keyboard clatter) and misses quiet speech |
| ML VAD | A small neural net scores each frame for "speech vs non-speech" | Silero VAD (MIT licence, ONNX, ~2 MB, 8/16 kHz, <1 ms per 30 ms chunk on one CPU thread — the de-facto standard, pip install silero-vad) |
Far more robust to noise; still only detects activity, not turn ends |
| Semantic turn detection | A model judges whether the words so far form a complete thought | OpenAI's semantic_vad (below); LiveKit/Pipecat's Smart Turn-style models |
Best end-of-turn judgement; costs a model call's worth of latency/complexity |
# energy_vad.py — the classic baseline, pure stdlib. Works on any PCM16 bytes.
import math, struct
def rms(frame: bytes) -> float:
s = struct.unpack(f"<{len(frame)//2}h", frame)
return math.sqrt(sum(x*x for x in s) / len(s))
def energy_vad(pcm: bytes, rate: int, frame_ms: float = 20.0,
threshold: float = 500.0, hangover_frames: int = 5):
frame_bytes = int(rate * frame_ms / 1000) * 2
flags = [rms(pcm[i:i+frame_bytes]) > threshold
for i in range(0, len(pcm), frame_bytes)]
out, quiet = [], 0
for f in flags:
if f: quiet, out = 0, out + [True]
elif out and out[-1]:
quiet += 1; out.append(quiet <= hangover_frames)
else: out.append(False)
return outRun on the lab's synthetic "voice-like" signal (three syllable bursts over noise): energy_vad flagged 69 of 100 frames as speech — the three bursts (~58%) plus hangover tails. Tune threshold for noisy rooms (higher) and hangover_frames for slow speakers (higher = more tolerant of mid-sentence pauses).
4.2 End-of-turn detection#
VAD tells you speech started/stopped; end-of-turn detection decides the stop was real — you actually finished your thought. Providers expose this directly:
OpenAI Realtime — session.audio.input.turn_detection in session.update:
{
"type": "session.update",
"session": {
"type": "realtime",
"audio": {"input": {"turn_detection": {
"type": "server_vad",
"threshold": 0.5,
"prefix_padding_ms": 300,
"silence_duration_ms": 500,
"create_response": true,
"interrupt_response": true
}}}
}
}server_vad(default): chunks on silence.threshold(0–1, higher = louder audio needed, better in noise),prefix_padding_ms(audio kept before detected speech — prevents clipping word onsets),silence_duration_ms(silence before declaring the turn over — the latency/accuracy knob).create_response/interrupt_responsedecide whether turns auto-trigger replies and barge-in.semantic_vad: a semantic classifier judges completeness;eagerness(auto/low/high) tunes how long it waits. Better for "um… let me think" mid-sentence pauses; slightly more complex.turn_detection: null: manual mode — you sendinput_audio_buffer.commit+response.createyourself (push-to-talk).
Gemini Live API — realtime_input_config.automatic_activity_detection in the setup message:
config = {
"response_modalities": ["AUDIO"],
"realtime_input_config": {"automatic_activity_detection": {
"disabled": False,
"start_of_speech_sensitivity": "START_SENSITIVITY_LOW",
"end_of_speech_sensitivity": "END_SENSITIVITY_LOW",
"prefix_padding_ms": 20,
"silence_duration_ms": 100,
}},
}Google's own guidance: silence_duration_ms of 500–800 ms is the sweet spot (their server default ≈800 ms); below ~200 ms fragments utterances into small clips that hurt transcription and response quality; above ~2000 ms adds noticeable dead air. They also document a hybrid VAD: keep automatic VAD for speech-start detection but run your own client-side VAD for end-of-speech, then send audio_stream_end to finalise immediately (server VAD remains as fallback). And fully manual mode: automatic_activity_detection.disabled: true + you send activityStart/activityEnd — but then you own the pre-speech buffer and silence tolerance.
4.3 Barge-in and truncation#
When you speak while the agent is speaking, two things must happen: playback stops immediately, and the agent's context is corrected to reflect that you only heard part of its reply. This second part is the subtle one.
On interruption, the provider cancels generation (OpenAI sends response.done with status: "cancelled"; Gemini sends server_content.interrupted: true and cancels pending function calls). But the model's conversation history still contains the full reply it generated — including the part you never heard. If you then say "wait, what was that?", the model may answer as if you heard all of it. The fix is truncation: tell the API exactly how much audio you actually played.
- WebRTC / SIP (OpenAI): the server tracks its output buffer and auto-truncates unplayed audio on interruption.
- WebSocket (OpenAI): you must do it. On
input_audio_buffer.speech_started: stop playback, discard queued audio, noteaudio_end_ms= how many ms the user actually heard, then send:
{"type": "conversation.item.truncate",
"item_id": "item_1234",
"content_index": 0,
"audio_end_ms": 1500}Truncation removes the unplayed audio and its transcript tail — there's no partial-transcript alignment, so the text of the unheard part is dropped too (OpenAI documents this explicitly).
4.4 Backchannels, duplex and the feel of conversation#
- Backchannels ("mm-hm", "yeah", "right") are the short listener noises humans produce mid-turn. Good voice agents tolerate them: server-VAD shouldn't treat a backchannel as a new turn (tune
threshold/silence_duration_ms), and semantic-VAD handles them better than energy thresholds. - Half-duplex = only one side speaks at a time (walkie-talkie). Most cascaded and early realtime agents are effectively half-duplex because the pipeline can't listen while TTS plays. Full-duplex = both can speak simultaneously —
gpt-live-1is OpenAI's full-duplex model (it listens and speaks at once, delegating reasoning to a backend), and Gemini Live's "proactive audio" (always-on forgemini-3.8-live) lets the model decide a sound doesn't warrant a response rather than replying to everything. - The engineering consequence: full-duplex removes the "agent talks over you" failure but adds cost and complexity; half-duplex with good barge-in is the pragmatic default for most agents.
Part 5: Event-driven session design#
Realtime APIs aren't request/response — they're event streams: you send client events, the server streams server events, and the session is a stateful object living between them. Understanding the event model is the core skill of this lesson.
5.1 The common event vocabulary#
Every provider names things differently, but the concepts map cleanly:
| Concept | OpenAI Realtime (client → server / server → client) | Gemini Live API |
|---|---|---|
| Session config | session.update → session.created / session.updated |
setup message in the WebSocket handshake → setupComplete |
| Stream audio in | input_audio_buffer.append (base64 PCM chunks, ≤15 MB each) |
send_realtime_input(audio=Blob(...)) / audio field |
| Commit a turn (VAD off) | input_audio_buffer.commit |
audio_stream_end / activityEnd |
| Ask for a response | response.create |
automatic on VAD, or send_client_content(turn_complete=True) |
| Cancel response | response.cancel |
interruption via new speech / send_client_content(turn_complete=True) |
| Audio out | response.output_audio.delta (base64) / .done |
server_content.model_turn.parts[].inline_data |
| Clear output buffer | output_audio_buffer.clear — WebRTC/SIP only; send after response.cancel to cut off buffered playback |
n/a (server-managed) |
| Output transcript | response.output_audio_transcript.delta / .done |
server_content.output_transcription |
| Input transcript | conversation.item.input_audio_transcription.* |
server_content.input_transcription |
| Speech started/stopped | input_audio_buffer.speech_started / .speech_stopped / .committed |
VAD events / interrupted flag |
| Function call | response.function_call_arguments.delta; result via conversation.item.create (function_call_output) |
toolCall server→client; result via toolResponse / session.send_tool_response(function_responses=...) (FunctionResponse) |
| Errors | error event with event_id correlation |
error messages / GoAway |
| Usage/limits | rate_limits.updated, token usage in response.done |
usage_metadata, usageMetadata |
| Session end | session.closed-style terminal events |
goAway, connection close |
5.2 The session state machine#
A voice session moves through a small set of states. Model yours on this:
stateDiagram-v2
[*] --> Connecting: open socket / SDP
Connecting --> Configured: session.created / setupComplete
Configured --> Listening: session.update / VAD armed
Listening --> UserSpeaking: speech_started / activityStart
UserSpeaking --> Listening: speech_stopped (turn end)
Listening --> Generating: response.create / VAD auto-response
Generating --> Playing: output_audio.delta arrives
Playing --> Listening: response.done (completed)
Playing --> Listening: speech_started (barge-in → truncate)
Generating --> Listening: response.cancel / interrupted
Listening --> ToolCall: function_call_arguments
ToolCall --> Generating: function_call_output sent
Listening --> Closed: session end / error / limit
Generating --> Closed: session end / error / limit
Closed --> [*]Key engineering rules that fall out of the state machine:
- One response at a time (mostly): don't fire
response.createwhile one is in flight unless you intend overlap; cancel first. - Every state has an exit on error: network drop, provider error event, session limit — all must land you in a defined recovery path (§5.4), not a hung socket.
- Barge-in is a transition, not an exception:
Playing → Listeningon user speech is normal operation, and the truncation bookkeeping (§4.3) is part of that transition.
5.3 Idempotent, ordered event handling#
Realtime sessions drop, duplicate and reorder events under real networks. Design rules:
- Tag every client event you care about with
event_id; the server'serrorevents reference it, so you can tell which of your sends failed (OpenAI documents this explicitly). - Audio appends are order-sensitive: send frames in sequence on one socket; don't fan out audio across parallel connections unless the API supports it.
- Deduplicate server events by ID where the API provides them; treat
deltaevents as cumulative-state hints, not commands — thedoneevent is authoritative. - Never assume a delta arrives: networks reorder; your playback buffer should tolerate gaps and your transcript assembly should tolerate missing deltas (rebuild from
done/completedevents). - Tool calls are the dangerous overlap: a function call may arrive while audio is still playing or while the user interrupts — decide your policy (cancel the call? finish it? speak the result anyway?) and encode it in the state machine.
5.4 Session limits and reconnection#
Sessions are finite. As of November 2026:
| Provider | Session limit | Reconnection story |
|---|---|---|
| OpenAI Realtime | 60 minutes max session duration | Ephemeral client secrets (POST /v1/realtime/client_secrets) mint short-lived credentials for clients; design for session rollover (new session + context seeding) on long calls |
OpenAI Live (gpt-live-1) |
Tier-based concurrent session limits (Build 50, Launch 300, Grow 500; Free tier unsupported, per OpenAI's gpt-live-1 model page, 12 November 2026) |
session.close/session.closed, store: true sessions can be forked; context restored via input on a new session |
| Gemini Live | 15 min audio-only, 2 min audio+video per session; ~10 min per WebSocket connection | sessionResumption handle (valid ~2 hr) resumes across reconnects; contextWindowCompression extends sessions indefinitely; GoAway message warns before disconnect |
The pattern is universal: long conversations must be designed as chains of sessions, not one immortal connection. Persist enough state (transcript, task state, last resumption handle) to resume or restart gracefully. Gemini's sessionResumption + GoAway + context compression is the most explicit version of this; OpenAI's 60-minute cap and tiered concurrency mean you roll sessions yourself.
Tools in realtime sessions (function calling mid-conversation, async tool execution, filler phrases, confirmations) are 09.7's subject — the foundation you need is that tool calls are just events in the same stream.
Part 6: Telephony basics#
Deep-dive
Putting a voice agent on a phone number adds a whole second stack: the public switched telephone network (PSTN) and its signalling protocol SIP (Session Initiation Protocol). Awareness level is enough — the carriers abstract most of it.
6.1 How a phone-call agent is wired#
flowchart LR
Caller["📞 caller's phone"] <-->|"PSTN / SIP"| Carrier["Carrier<br/>(Twilio / Telnyx / Vonage…)"]
Carrier <-->|"WebSocket (audio or text)"| App["Your voice-agent backend"]
App <-->|"realtime API or STT+LLM+TTS"| Model["Voice model / pipeline"]The carrier owns the phone number, the PSTN connection, and (usually) the audio codec. Your application connects to the carrier over a WebSocket — either raw bidirectional audio (Twilio Media Streams, Telnyx Media Streaming) or pre-transcribed text (Twilio Conversation Relay, Telnyx Conversation Relay), which is the telephony equivalent of the cascaded pipeline where the carrier runs STT/TTS for you. On the model side, OpenAI Realtime accepts SIP connections directly; Gemini Live has no native telephony — you bridge it yourself or use a partner (Google's docs list LiveKit, Pipecat, Daily, Voximplant, Agora integrations).
As of November 2026 the carriers worth knowing: Twilio (Conversation Relay managed speech loop, or Media Streams for raw audio; the largest ecosystem), Telnyx (licensed carrier with Voice API, Conversation Relay as text-over-WebSocket, Media Streaming for raw audio, often cheaper US rates), Vonage (NCCO call flows with WebSocket audio). SignalWire and others offer similar primitives. Verify current pricing per destination — carrier rates vary by country and change often.
6.2 What telephony does to your audio#
- μ-law (G.711) at 8 kHz: PSTN carries 8-bit companded audio at 8 kHz — narrower than the 16/24 kHz your realtime APIs prefer. The carrier transcodes for you; you receive whatever the carrier's WebSocket gives (often base64 μ-law or PCM). Your audio is now telephone-quality: fine for speech agents, hostile to music or wideband sound.
- DTMF: touch-tone digits (0–9, *, #) for IVR-style input — "press 1 for sales". Carriers deliver DTMF as events/out-of-band; never make the user say card numbers.
- Latency pitfalls: PSTN adds its own hops; carrier transcoding and jitter buffers add tens of ms each way. A voice agent that's 800 ms on web can be 1.2 s+ on a phone line. Budget for it.
- Cost per minute: carrier per-minute charge plus your model cost plus any managed STT/TTS the carrier bills. A 5-minute support call might cost cents of carrier + tens of cents of realtime audio — model the total, not just the API.
6.3 Consent and compliance on calls#
Phone calls raise the stakes on Part 9: recording consent laws vary by jurisdiction (some US states are all-party consent), callers must often be told they're talking to a machine and whether the call is recorded, and card/payment data must never reach the model (use DTMF masking or a PCI-compliant capture — awareness only, not legal advice).
Part 7: The pure-Python lab#
Everything a realtime pipeline does to audio — generate, convert, resample, encode, chunk, detect speech, buffer jitter — is pure signal processing you can do in the standard library. This lab (audio_lab.py) runs with no packages and no keys; every output below is real.
7.1 Generate a test signal and write a WAV#
import math, random, struct, wave
from pathlib import Path
def synth_voice_like(seconds=2.0, rate=16000):
"""PCM16 samples: three warbling 'syllable' bursts over a noise floor."""
rng = random.Random(42)
bursts = [(0.20, 0.55), (0.85, 1.30), (1.60, 1.95)]
out = []
for i in range(int(seconds * rate)):
t = i / rate
amp = 0.0
for s, e in bursts:
if s <= t < e:
env = math.sin(math.pi * (t - s) / (e - s))
freq = 220 + 60 * math.sin(2 * math.pi * 7 * t)
amp = 0.55 * env * math.sin(2 * math.pi * freq * t)
v = max(-1.0, min(1.0, amp + rng.uniform(-0.004, 0.004)))
out.append(int(v * 32767))
return out
def write_wav(path, samples, rate=16000):
with wave.open(str(path), "wb") as w:
w.setnchannels(1); w.setsampwidth(2); w.setframerate(rate)
w.writeframes(b"".join(struct.pack("<h", s) for s in samples))7.2 PCM16 ↔ float and resampling#
def pcm16_to_float(pcm: bytes):
return [s / 32768.0 for s in struct.unpack(f"<{len(pcm)//2}h", pcm)]
def float_to_pcm16(samples):
out = []
for x in samples:
x = max(-1.0, min(1.0, x))
out.append(int(x * 32768) if x < 0 else min(32767, int(x * 32767)))
return struct.pack(f"<{len(out)}h", *out)
def resample_linear(samples, src_rate, dst_rate):
"""Linear-interpolation resampler — good enough for speech."""
if src_rate == dst_rate: return list(samples)
ratio = src_rate / dst_rate
out = []
for i in range(int(len(samples) / ratio)):
pos = i * ratio; j = int(pos); frac = pos - j
a = samples[j]; b = samples[min(j + 1, len(samples) - 1)]
out.append(a + (b - a) * frac)
return outThe mic gives you 44.1/48 kHz; the API wants 16/24 kHz. Resample before framing — never after.
7.3 μ-law encode/decode (G.711, telephony)#
audioop was removed in Python 3.13, so here's the companding by hand — the same maths every telephony stack uses:
_MU_BIAS, _MU_CLIP = 0x84, 32635
def linear_to_mu(sample: int) -> int:
sign = 0x80 if sample < 0 else 0
mag = min(abs(sample), _MU_CLIP) + _MU_BIAS
exponent = next(e for e in range(7, -1, -1) if mag >= (1 << (e + 7)))
return ~(sign | (exponent << 4) | ((mag >> (exponent + 3)) & 0x0F)) & 0xFF
def mu_to_linear(code: int) -> int:
"""8-bit mu-law code -> 16-bit PCM sample."""
code = ~code & 0xFF
sign = -1 if code & 0x80 else 1
exponent = (code >> 4) & 0x07
mantissa = code & 0x0F
mag = ((mantissa << 3) + _MU_BIAS) << exponent
mag -= _MU_BIAS
return sign * magReal output (run): linear_to_mu(16000)=0x90 → mu_to_linear=15996; linear_to_mu(-16000)=0x10 → -15996; linear_to_mu(30000)=0x82 → 30076. μ-law is companded: fine quantisation near zero (quiet speech), coarse at loud levels — that's why 8-bit μ-law sounds acceptable for speech but not music. (audioop was removed in Python 3.13, which is why this is hand-rolled; the same maths lives in every telephony stack.)
7.4 Frame and base64 for the wire#
def pcm_frames(pcm: bytes, frame_ms: float, rate: int):
fb = int(rate * frame_ms / 1000) * 2 # 16-bit mono bytes per frame
return [pcm[i:i+fb] for i in range(0, len(pcm), fb)]A 20 ms frame at 16 kHz mono PCM16 is 320 samples = 640 bytes → 856 base64 chars inside one input_audio_buffer.append JSON event (the lab measured ~906 chars including JSON overhead).
7.5 Energy VAD (see §4.1 for the code)#
Real output on the synthetic signal: 69/100 frames flagged speech — bursts plus hangover. Threshold and hangover are your two knobs.
7.6 Jitter buffer simulation#
Packets arrive with jitter and loss; playback needs a steady 20 ms cadence. Simulate it:
def jitter_buffer_demo():
import random
rng = random.Random(7)
playout_ms, depth, starved = 20.0, 4, 0
arrivals, t, seq = [], 0.0, 0
while seq < 60:
t += playout_ms + rng.uniform(-8, 8)
if rng.random() < 0.02: seq += 1; continue # lost packet
arrivals.append((seq, t + rng.uniform(-30, 30))) # network jitter
seq += 1
played, buffered, max_depth = [], [], 0
clock = arrivals[0][1] + 80.0 # start after ~4 packets buffered
for seq_no, at in arrivals:
buffered.append(seq_no)
while clock <= at + depth * playout_ms and buffered:
played.append(buffered.pop(0)); clock += playout_ms
if not buffered and clock < at: starved += 1
max_depth = max(max_depth, len(buffered))
played.extend(buffered)
print(f"delivered: {len(played)}/60, lost: {60-len(played)}, "
f"max depth: {max_depth*20} ms, starved: {starved}")Real output: delivered: 59/60, lost: 1, max depth: 80 ms, starved: 0. The buffer absorbed ±30 ms of network jitter with a 4-packet (80 ms) cushion; deeper jitter needs a deeper buffer — at the cost of added latency. This is exactly the trade-off WebRTC's internal jitter buffer manages for you.
One thing the simulation doesn't model is clock drift — the classic "drifting buffer" failure. The capture clock (the device sending audio) and the playback clock (the device rendering it) are different oscillators, and even a few parts-per-million of difference accumulates: over a long call, packets that arrived on time slowly arrive "early" or "late" relative to the playout clock, so a fixed-depth buffer slowly underflows or overflows and the audio warbles, then breaks. WebRTC handles this internally by resampling the incoming stream toward the playout clock; on a raw WebSocket pipeline you must do the equivalent yourself — periodic realignment, adaptive resampling, or occasionally inserting/dropping a frame. It's why "the call was fine for ten minutes, then the audio drifted" is a real production bug rather than a myth.
7.7 What the lab proved#
Every piece of "realtime audio" plumbing — format conversion, framing, VAD, jitter buffering — is deterministic signal processing you can test without any API. When a voice agent sounds wrong, isolate which stage: capture → resample → frame → network → VAD → model → playback. Half the bugs live in stages 1–4, which you can debug locally.
Part 8: Cost and latency arithmetic#
Realtime pricing is the least intuitive part of voice AI because it mixes per-token and per-minute/per-second billing. Get the units right and the rest is arithmetic (the token-cost machinery itself is 03.7).
8.1 The three billing shapes (as of November 2026)#
| Shape | Example | How it bills |
|---|---|---|
| Per audio/text token | OpenAI Realtime (gpt-realtime-2.1: audio $32/1M in, $64/1M out; gpt-realtime-mini: $10/$20) |
Audio tokens: 1 token per 100 ms of user audio, 1 token per 50 ms of assistant audio (OpenAI's cost guide). Crucially, the whole conversation is re-sent each turn — a 5-min call's later turns re-bill earlier context |
| Per minute of audio | Gemini Live (gemini-3.8-live: audio in $0.005/min, out $0.018/min — or $3/$12 per 1M tokens; text $0.75/$4.50 per 1M) |
Billed per second of streamed audio; audio tokens accumulate ~25/sec in context so long sessions re-bill context too |
| Per second of session + backend | gpt-live-1: $0.05/min voice session, billed per second, backend model/tools billed separately |
Predictable voice cost; backend usage varies like any text call |
| Streaming STT/translation | gpt-realtime-whisper / gpt-live-transcribe: $0.017/min; gpt-realtime-translate: $0.034/min (OpenAI's pricing page marks these per-minute figures as estimates) |
Duration-based, not token-based |
8.2 Worked example: a 5-minute support call#
Cascaded (streaming STT + mid-tier LLM + TTS), rough order-of-magnitude:
- STT ~$0.01–0.05/min → ~$0.05–0.25
- LLM: ~1–2k tokens in/out per turn × ~20 turns → ~$0.02–0.10
- TTS: ~750 chars/min spoken → ~$0.01–0.05
- Total ≈ $0.08–0.40 per call (highly provider-dependent)
Speech-to-speech (gpt-realtime-2.1): user speaks ~2.5 min = 150 s × 10 tok/s = 1,500 audio input tokens; assistant ~2.5 min = 150 s × 20 tok/s = 3,000 audio output tokens → 1,500×$32/M + 3,000×$64/M ≈ $0.24 — plus the growing-context re-billing on later turns, which can double or triple it on long calls. A gpt-realtime-mini does the same call for roughly a third of that.
gpt-live-1: 5 min × $0.05 = $0.25 voice + backend model cost — the most predictable of the three.
# voice_cost.py — the arithmetic, with prices as parameters.
def realtime_token_cost(minutes_user, minutes_agent,
in_per_mtok=32.0, out_per_mtok=64.0,
context_resend_factor=1.0):
"""OpenAI-style: 1 tok/100ms in, 1 tok/50ms out, conversation re-sent.
context_resend_factor approximates the re-sent context as a flat
multiplier — the real resend grows with each turn, so treat it as
a dial for 'how much history gets re-billed', not a precise model."""
in_tok = minutes_user * 60 * 10 * context_resend_factor
out_tok = minutes_agent * 60 * 20
return (in_tok * in_per_mtok + out_tok * out_per_mtok) / 1e6
def per_minute_cost(minutes, rate_in=0.005, rate_out=0.018):
"""Gemini-Live-style: per-minute audio rates."""
return minutes * (rate_in + rate_out) / 2 # assume ~50/50 talk/listen
print(f"gpt-realtime-2.1, 5-min call, no resend: "
f"${realtime_token_cost(2.5, 2.5):.3f}")
print(f" same with 2x context resend on later turns: "
f"${realtime_token_cost(2.5, 2.5, context_resend_factor=2.0):.3f}")
print(f"gemini-3.8-live, 5-min call (~50/50): ${per_minute_cost(5):.3f}")
print(f"gpt-live-1, 5-min call: ${5*0.05:.3f} + backend")gpt-realtime-2.1, 5-min call, no resend: $0.240
same with 2x context resend on later turns: $0.288
gemini-3.8-live, 5-min call (~50/50): $0.057
gpt-live-1, 5-min call: $0.250 + backend(Prices are the verified November-2026 list prices; your negotiated rates and usage mix will differ — treat these as the shape of the maths, not a quote.)
8.3 Latency arithmetic recap#
First-audio latency = mic + uplink + VAD-end-of-turn + model-first-audio + downlink + jitter buffer. The two big levers are VAD silence wait (200–800 ms, tunable) and model time-to-first-audio (200–600 ms, model/effort-dependent). Everything else is tens of ms. Target < ~800 ms for conversational feel.
Part 9: Privacy, consent and safety#
Deep-dive
Voice is the most personal modality: your voice is biometric-adjacent, a call captures everything said (including bystanders), and realtime sessions are continuous data streams. Treat this as a design requirement, not an afterthought. (Legal specifics vary by jurisdiction — awareness, not legal advice; Module 12 owns the security depth.)
- Consent and notice. Recording-consent laws differ (some jurisdictions require all-party consent). Disclose that the caller is speaking to an AI and whether the call/session is recorded; many carriers and regulators expect an upfront notice. Never record silently.
- Voice is identifiable. Speech carries identity, accent, emotion and sometimes health cues. Don't log raw audio longer than needed; prefer storing transcripts + metadata, and define retention/deletion with the same rigour as any PII store.
- Provider retention. Realtime sessions stream continuously to the provider; check each provider's data-retention and training-use policy (02.9, Part 9 covers provider data policies generally) and whether session audio is stored, and for how long.
- Sensitive data in speech. Callers say card numbers, health details, passwords. Design so the model never needs them: use DTMF masking or a PCI-aware capture for payments, redact before logging, and never let privileged tools be reachable by unauthenticated callers.
- Prompt injection via speech. A caller can say "ignore your instructions and…" — speech is untrusted input like any other. Tool-calling voice agents need the same guardrails as text agents (Module 12); the realtime model hearing audio doesn't make it immune.
- Voice cloning and impersonation. If you use custom/cloned voices (TTS side, 09.5), get documented consent, watermark synthetic audio where the provider supports it, and disclose synthetic voices. Never clone a real person's voice without consent.
- Children and vulnerable users. Extra caution with minors' voice data and with users who may not understand they're talking to a machine.
- Accessibility. Voice agents must offer a text/caption path for deaf and hard-of-hearing users, and clear error recovery for users who struggle with speech — captions alongside audio are the baseline, not a luxury.
Failure gallery#
The realtime-specific ways production voice goes wrong, with the fix for each:
| Failure | Symptom | Cause | Fix | Covered in |
|---|---|---|---|---|
| Echo loop / self-interruption | Agent interrupts itself forever on speakerphone | Speaker output leaks into the mic; VAD hears the agent's own voice as user speech | Hardware/OS AEC via the WebRTC audio stack, or require headsets; gate VAD while the model speaks; raise threshold |
3.3 Jitter, loss, echo and noise |
| Clipped speech | Agent replies mid-sentence; the user's first word is chopped | silence_duration_ms/energy-VAD hangover too aggressive; threshold too high for quiet speech |
Raise the silence wait (Google's 500–800 ms guidance), add prefix_padding_ms, lower the threshold, or move to ML/semantic VAD |
4.1 VAD, 4.2 End-of-turn |
| Agent talks over the user | Replies overlap the user's turn; backchannels trigger new responses | interrupt_response/create_response mis-tuned; eagerness too high; energy VAD fires on "mm-hm" |
Tune VAD parameters per room noise; prefer semantic_vad/hybrid VAD; accept half-duplex with good barge-in as the pragmatic default |
4.2 End-of-turn, 4.4 Duplex |
| Sample-rate mismatch | Chipmunk or slow-motion audio; the model "hears" garbage — with no error | Mic/OS delivers 44.1/48 kHz; the API wants 16/24 kHz; the bytes are still valid PCM | Resample deliberately at the capture boundary and assert the rate in code — never discover it in production | 3.2 Formats, 7.2 Resampling |
| Jitter-buffer underflow | Choppy, gapped audio on lossy Wi-Fi/cellular | Buffer too shallow for the real jitter | Deeper buffer — at the cost of added latency; on browsers prefer WebRTC, which manages this internally | 3.3 Jitter, 7.6 Jitter buffer |
| Drifting buffer (clock drift) | Call is fine for ~10 minutes, then audio warbles and desyncs | Capture and playback clocks are different oscillators; a fixed-depth buffer can't absorb the accumulated drift | WebRTC resamples to the playout clock internally; on WebSocket do periodic realignment, adaptive resampling, or occasional frame insert/drop | 7.6 Jitter buffer |
| Untruncated barge-in | Agent "remembers" saying things the user never heard; it repeats or references unheard content | Playback stopped but the conversation context still holds the full generated reply | Record audio_end_ms of what was actually played and send conversation.item.truncate (WebSocket); WebRTC/SIP auto-truncate |
4.3 Barge-in |
| Session-limit surprise | Call drops at 15 min (Gemini audio session) or 60 min (OpenAI); reconnect loses context | Hard session/connection caps; no resumption or rollover configured | Design conversations as chains of sessions: persist transcript/task state, use sessionResumption/GoAway on Gemini, roll sessions on OpenAI |
5.4 Session limits |
Common misconceptions#
| Misconception | Reality |
|---|---|
| "Speech-to-speech is always better than STT→LLM→TTS." | It buys latency and prosody but costs observability, control and often money. Cascaded is often the right production choice. |
| "The realtime model 'hears' exactly what the transcript shows." | It hears tone, noise and everything — the transcript is a lossy summary. Context-truncation on interruption exists precisely because heard ≠ said. |
| "VAD detects when you're done speaking." | VAD detects activity; end-of-turn detection (server_vad silence / semantic_vad) decides completeness. They're different layers. |
| "If the user interrupts, the model just stops." | Playback stops, but the context must be truncated to what was heard — otherwise the model "remembers" saying things you never heard. |
| "WebSocket is fine for browser voice." | It works, but WebRTC gives you jitter buffering, AEC, noise suppression and codecs for free. Browsers → WebRTC. |
| "A longer session is just a longer connection." | Sessions have hard limits (60 min OpenAI; ~10-min connections + 15-min sessions Gemini). Long conversations are chains of sessions with resumption. |
| "Audio costs roughly the same as text." | Audio tokens accrue per second of speech and re-bill accumulated context each turn — a chatty call costs far more than its duration suggests. |
| "μ-law is just a compressed WAV." | It's 8-bit companded PCM at 8 kHz — telephone bandwidth. Fine for speech agents, wrong for music or high-fidelity audio. |
| "Anthropic has a voice API." | It doesn't — Messages API is text+image in, text out. Claude voice agents are always cascaded. |
| "OpenRouter does realtime voice." | No realtime session API; it proxies audio-input chat models and STT/TTS endpoints, not live sessions. |
| "I can send my mic audio straight to the API." | Resample to the required rate (16/24 kHz), frame to ~20 ms chunks, encode correctly — a rate mismatch fails silently. |
Key takeaways#
- Two architectures: cascaded (STT→LLM→TTS) buys control, observability and any-LLM flexibility; speech-to-speech buys latency, prosody and presence. Choose per use case; hybrids (full-duplex voice + delegated text backend) are the modern middle.
- Provider landscape (Nov 2026): OpenAI Realtime (
gpt-realtime-2.1family, WebRTC/WebSocket/SIP, 60-min sessions) andgpt-live-1(full-duplex, $0.05/min + backend); Gemini Live (gemini-3.8-livefamily, WebSocket, 15-min audio sessions, resumption/compression); Anthropic and OpenRouter have no realtime session API. - Transports: WebRTC for browsers, WebSocket for servers/gateways, SIP for phones, HTTP streaming only for non-conversational audio.
- Wire format: raw PCM16, mono, 16 kHz in / 24 kHz out typical; 20–40 ms frames; base64 in JSON events; μ-law 8 kHz on telephony. Resample deliberately — mismatches fail silently.
- Turn-taking: energy VAD → ML VAD (Silero) → semantic turn detection is the maturity ladder; provider server-VAD exposes
silence_duration_ms/threshold/prefix_padding_msas your latency-vs-accuracy knobs. - Barge-in needs truncation: record
audio_end_msof what the user actually heard and truncate the model's context — on WebSocket you do it yourself. - Sessions are finite: design reconnection and context resumption; persist state to roll sessions.
- Cost: per-token realtime billing re-sends context each turn; per-minute billing (Gemini, gpt-live-1) is more predictable. Model the whole conversation, not the duration.
- Latency: target < ~800 ms end-of-speech → first audio; the levers are VAD wait and model first-audio time.
- Privacy: voice is sensitive biometric-adjacent data; consent, retention, injection-via-speech and DTMF masking are design requirements.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Cascaded pipeline | Voice agent as STT → LLM → TTS stages orchestrated by your app |
| Speech-to-speech / audio-native model | A model taking audio in and producing audio out directly |
| Full-duplex | Both sides can speak at once (vs half-duplex turn-taking) |
| Realtime API / Live API | Provider APIs holding a continuous low-latency audio session |
| WebSocket (WSS) | Persistent bidirectional socket; carries base64 audio in JSON events |
| WebRTC | Browser media protocol with built-in jitter buffer, AEC, codecs |
| SIP / PSTN | Telephony signalling / the phone network itself |
| PCM / PCM16 | Raw uncompressed audio; 16-bit signed little-endian samples |
| μ-law (G.711) | 8-bit companded telephony codec at 8 kHz |
| Base64 | Encoding that turns binary audio into JSON-safe text (+33% size) |
| Jitter | Variable packet arrival delay; absorbed by a jitter buffer |
| Clock drift | Capture and playback clocks running at slightly different rates, slowly desynchronising a stream |
| Echo cancellation (AEC) | Removing speaker output leaking into the mic |
| VAD | Voice activity detection: is someone speaking now |
| Energy VAD / ML VAD | Threshold-on-loudness / neural-net speech detector (Silero) |
| End-of-turn detection | Deciding the speaker actually finished their thought |
| server_vad / semantic_vad | Provider turn detection: silence-based / completeness-model |
| Barge-in | User interrupting the agent mid-reply |
| Truncation | Cutting the model's unheard reply out of its context |
| Backchannel | Listener noise ("mm-hm") during the other's turn |
| Ephemeral token / client secret | Short-lived credential for client-side realtime sessions |
| Session resumption | Resuming a realtime session across reconnects (handle/token) |
| Context window compression | Summarising old audio tokens so sessions can run longer |
| DTMF | Touch-tone phone digits for IVR-style input |
Exercises#
All keyless unless noted.
- μ-law round-trip: extend
linear_to_mu/mu_to_linearto encode a full WAV of the lab signal to μ-law and decode it back; measure the max error vs original PCM16. Where does companding lose most? - Resampling quality: resample the 16 kHz signal to 24 kHz and back; compute per-sample error. Is linear interpolation good enough for speech? Where does it fail?
- VAD tuning: run
energy_vadon the synthetic signal at thresholds 200/500/1000 and hangover 0/5/15. Which setting would clip a slow talker? Which would trigger on the noise floor? - Latency budget: recompute §3.4's budget for a cascaded pipeline (STT finalise 300 ms + LLM first-token 400 ms + TTS first-audio 250 ms + same transport). Compare to speech-to-speech. Which stages dominate each?
- Cost model: use
voice_cost.pyto price a 10-minute call at 70% user / 30% agent talk-time ongpt-realtime-2.1vsgpt-realtime-minivsgpt-live-1(assume $0.10 backend). Which is cheapest? What breaks the ranking? - Event mapping: take the §5.1 table and add a third column for your provider of choice (check its current docs). Which concepts have no equivalent?
- Truncation logic: write a function
truncate_context(played_ms, generated_ms)returning the fraction of the assistant's last reply the user heard; explain why you can't recover the unheard transcript. - Design challenge: spec (no code) a voice agent for a clinic appointment line: architecture choice, transport, VAD settings, what happens on barge-in, what PII must never reach the model, and the consent notice. Defend each choice.
Hints and worked numbers for the exercises
- μ-law's quantisation step grows with amplitude, so the largest absolute error is at the loudest samples (in the check above, 16,000 comes back as 15,996, an error of 4; measure the maximum over a whole signal and where it occurs). Compare relative error, not absolute, to see that companding keeps quiet speech accurate.
- Linear interpolation adds high-frequency loss and aliasing: fine for speech, audible on music or sibilants. A 16 kHz to 24 kHz to 16 kHz round trip will not reproduce the input exactly.
- A higher threshold or hangover of 0 clips slow talkers' pauses and quiet word onsets; none of 200, 500 or 1000 is below the noise floor (its RMS is about 76 on this signal), so none flags silence as speech; try a threshold of 50 and every one of the 100 frames is flagged. For the clipping case, hangover 0 gives 56 speech frames at thresholds 500 and 1000, against 69 with a hangover of 5.
- Cascaded: 10 + 40 + 500 (VAD wait) + 300 (STT finalise) + 400 (LLM first token) + 250 (TTS first audio) + 40 + 60 + 10 = 1,610 ms against 1,010 ms for the speech-to-speech budget. The two model stages and the VAD wait dominate both.
- 7 minutes of user audio is 4,200 tokens in and 3 minutes of agent audio 3,600 tokens out.
gpt-realtime-2.1: 4,200 × $32/M + 3,600 × $64/M = $0.365;gpt-realtime-miniat $10/$20: $0.114;gpt-live-1: 10 × $0.05 + $0.10 = $0.60. The mini is cheapest until context re-billing, a stronger-model requirement or backend cost changes the ranking. - Tool calls, truncation and session resumption are the concepts most likely to lack a one-to-one equivalent.
played_ms / generated_ms, clamped to 0 to 1. You cannot recover the unheard transcript because the API only truncates by audio duration; there is no word-level alignment of the played audio.- A good answer picks WebRTC or a telephony WebSocket, server VAD with a patient
silence_duration_msfor hesitant callers, truncation on barge-in, DTMF for any card or identity digits, and an upfront AI-and-recording notice.
Check yourself#
- What's the difference between a cascaded voice pipeline and a speech-to-speech model?Cascaded runs STT → LLM → TTS as separate orchestrated stages (observable, controllable, any LLM); speech-to-speech is one model taking audio in and producing audio out (lower latency, richer prosody, less control).
- Name two things a speech-to-speech model "hears" that a transcript loses.Tone/prosody/emotion and non-speech sound (noise, music, sound events) — a transcript keeps only the words.
- Which transport should a browser voice app use, and why not plain WebSocket?WebRTC — it provides jitter buffering, echo cancellation, noise suppression and codecs; WebSocket leaves all media handling to you.
- What sample rate and bit depth do Gemini Live and OpenAI Realtime typically want for input audio?Raw 16-bit PCM, mono; Gemini input natively 16 kHz (output 24 kHz), OpenAI examples use PCM at 24 000 Hz.
- Why does sending 48 kHz audio to a 16 kHz API fail silently?The bytes are still valid PCM — just at the wrong rate — so the model hears speed/pitch-shifted audio with no error.
- What's the difference between VAD and end-of-turn detection?VAD detects whether speech is present now; end-of-turn detection decides the speaker finished their thought (via silence duration or a semantic completeness model).
- What does
silence_duration_mscontrol, and what's the latency trade-off?How much silence before a turn is declared over. Lower = faster response but clips mid-sentence pauses; higher = safer but adds dead air. - Why must you truncate the assistant's context on barge-in — what breaks if you don't?Otherwise the model's context contains a reply the user never heard, so it references/repeats content they didn't get — context must reflect what was delivered.
- Name the four transports and one use case for each.HTTP streaming (non-conversational audio), WebSocket (server-side/gateway realtime), WebRTC (browser/mobile), SIP/PSTN (phone calls).
- What's OpenAI Realtime's max session duration, and what does that imply for long calls?60 minutes — long calls must be chains of sessions with context carried over.
- How does Gemini Live handle sessions longer than its 15-minute limit?Session resumption handles across ~10-min connection resets, context-window compression for the token limit, and GoAway warnings — enabling effectively unlimited sessions.
- Why does a realtime call's cost grow faster than its duration suggests?Each turn re-sends the accumulated conversation as input tokens (and audio tokens accrue ~25/sec in context), so later turns cost more.
- What is μ-law, and when do you encounter it?8-bit companded telephony codec at 8 kHz (G.711), used on PSTN/phone calls.
- Give two reasons a voice agent might need consent/notice before it records.Recording-consent laws vary (some need all-party consent); callers should know they're talking to an AI and whether it's recorded.
- Which providers as of Nov 2026 have no realtime session API?Anthropic (text+image only) and OpenRouter (no realtime session API).
Further resources#
- OpenAI Realtime API guide and voice agents overview — transports, session events, VAD, truncation,
gpt-live-1delegation. - OpenAI pricing — realtime audio token rates,
gpt-live-1per-minute, transcription per-minute. - Gemini Live API overview and capabilities guide — models, formats, VAD modes, session limits; session management for resumption/compression; pricing.
- Silero VAD — the standard open ML VAD (MIT, ONNX).
- Stivers et al., "Universals and cultural variation in turn-taking in conversation," PNAS 2009 — the 0–300 ms turn-gap evidence.
- Twilio Conversation Relay and Telnyx Conversation Relay — telephony WebSocket patterns.
- LiveKit Agents and Pipecat — open-source cascaded voice-agent frameworks (09.7 builds on these).
← 09.5 — Text-to-Speech | Module 09 overview | 09.7 — Realtime Voice Agents →