09.7 Realtime Voice Agents

Agents & multimodalLesson 7 of 1014,025 wordsOptional14 parts
Module 09 · 0 of 3 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10

A text chatbot replies when you press send. A voice agent lives in a live audio stream: it hears the user through a microphone or a phone line, decides what to say, speaks back, can be interrupted mid-sentence, and can call your tools while the conversation is still going. This lesson is the engineering reference for building one. It covers the two realtime APIs that exist as of November 2026 — OpenAI's Realtime API and Gemini's Live API — plus GPT-Live, OpenAI's newer delegated-backend voice model, why Anthropic and OpenRouter have no realtime voice session of their own, the frameworks and hosted platforms teams actually use (LiveKit Agents, Pipecat, Vapi, Retell, Bland, ElevenLabs Agents, Twilio ConversationRelay), and three complete worked examples: a server-side WebSocket session, a browser client with WebRTC and an ephemeral token, and a cascaded speech-to-text → LLM → text-to-speech pipeline built both with a framework and from scratch. It then covers the parts that make a demo into a product: tools and approvals in a voice loop, conversation design for speech, latency and cost arithmetic, observability and testing, and the privacy and consent rules that come with recording people's voices.

What you'll learn

  • The three voice-agent architectures — a single speech-to-speech realtime model, a full-duplex voice model with a delegated text backend, and a cascaded STT → LLM → TTS pipeline — and when each wins
  • The OpenAI Realtime API completely: transports (WebRTC, WebSocket, SIP), ephemeral client secrets, session configuration, the event model, server and semantic VAD, function and MCP tools, interruption truncation, session limits and token-based pricing
  • GPT-Live: delegation modes, the session.* event model, sideband server control, duration pricing, and when it beats the Realtime API
  • The Gemini Live API completely: WebSocket sessions, BidiGenerateContentSetup, ephemeral tokens, session resumption and context-window compression, function calling and Google Search grounding, voices, limits and pricing
  • What Anthropic and OpenRouter actually offer for voice (and what they don't), verified against their docs
  • How to choose and operate a voice-agent framework or hosted platform: LiveKit Agents, Pipecat, Vapi, Retell, Bland, ElevenLabs Agents, Twilio ConversationRelay
  • Tools, retrieval, human approval and warm handoff inside a voice conversation — including filler phrases, confirmations and readbacks
  • Conversation design for speech: short turns, entity capture, disfluencies, multilingual calls, and a reusable system-prompt blueprint
  • Reliability and operations: session lifecycle, reconnection, rate limits, cost-per-minute modelling, per-turn latency measurement, scripted test callers, fallbacks and abuse prevention
  • Privacy, consent and compliance: recording laws awareness, retention, PCI-style card handling and healthcare caution

What you don't need

  • A microphone, a phone line or API keys to learn the material. Every provider sample is written against the official documentation and labelled illustrative; the pipeline control logic, cost calculator and test harnesses run locally with no network at all.
  • How VAD, barge-in and transport selection work at the signal level — lesson 09.6 owns those fundamentals; this lesson uses them. Likewise, speech-to-text and text-to-speech APIs in depth are 09.4 and 09.5.
  • The tool-calling round trip itself — lesson 03.5 and the agent loop in 08A.2 own those; this lesson shows what changes when the loop runs inside a live audio session.

Setup

The provider samples use the module's provider SDKs plus websockets and fastapi/uvicorn for the server examples. From the llm-apis project folder (see lesson 03.1, Part 4):

bash
uv add "openai[realtime]" anthropic google-genai websockets httpx fastapi uvicorn python-dotenv pydantic
# or: pip install "openai[realtime]" anthropic google-genai websockets httpx fastapi uvicorn python-dotenv pydantic

openai[realtime] is the SDK with the extra that ships client.live.connect() for GPT-Live (4.6). These samples were written and checked against openai 3.42.1, anthropic 2.4.0, google-genai 2.34.0, websockets 17.4 and pydantic 2.14.3 as of November 2026, and a plain install gives you the newest release of each. The examples use additional_headers (the parameter name on the modern asyncio websockets client, 15 and later); on older releases it was called extra_headers, so if you already have an old websockets in the project, upgrade it.

The .env file holds the keys (never commit it):

bash
# .env
OPENAI_API_KEY=...
GEMINI_API_KEY=...   # optional

The framework sample in Part 10 additionally needs pipecat-ai or livekit-agents; install whichever you choose when you reach it — the lesson cites the version the sample was checked against there. The pure-local pieces (the pipeline simulator, the cost calculator, the test harness) need only the standard library, and are marked Try it free.


What you must be able to do after this lesson#

  • Choose a voice-agent architecture for a use case
  • Build a server-side realtime voice session
  • Add tools and human handoff inside a voice conversation
  • Design short, clear turns for voice conversations
  • Handle reconnection, latency and cost in operations

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"Should we use a speech-to-speech model or just chain STT → LLM → TTS?" Part 1 and the decision table
"The agent keeps talking over the caller." 1.5 Interruptions and truncation, 09.6
"How do I get the browser's microphone audio to OpenAI without exposing my key?" Part 9
"What's the difference between the Realtime API and GPT-Live?" Part 4
"Gemini's Live session died after ten minutes." 5.6 Session lifetime, resumption and compression
"Claude can't do voice — what do we do?" Part 6
"Do we build on LiveKit or Pipecat, or pay Vapi/Retell?" Part 7
"The tool call takes three seconds — the caller hears silence." 11.2 Filler phrases and async tools
"What does a voice minute actually cost?" 13.3 Cost per minute
"Can the agent take card numbers over the phone?" 14.3 Payments and sensitive data

Part 1: The three architectures#

1.1 What a voice agent actually is#

Strip away the marketing and a voice agent is three loops running at once:

  1. The audio loop — capture microphone or phone audio, chunk it, stream it to a model, receive audio back, play it with low latency, and handle the user talking over the agent (barge-in).
  2. The conversation loop — decide when the user has finished a turn (endpointing / turn detection), keep the conversation state coherent, and decide what the agent should say next.
  3. The task loop — the same tool-calling loop you know from text agents (03.5, 08A.2), except tool calls happen while audio is streaming and their results must be spoken, not displayed.

Lesson 09.6 covers the audio-loop mechanics in depth: sample rates, PCM formats, VAD algorithms, jitter buffers and the latency budget. This lesson assumes that foundation and focuses on the APIs and the product around them.

1.2 Architecture A: speech-to-speech realtime models#

The newest and simplest shape: one model consumes audio and produces audio directly. You send PCM chunks; you get PCM chunks plus transcripts and events back. The model does transcription, reasoning and speech generation internally.

flowchart LR
    subgraph client ["Client (browser / phone / server)"]
        MIC["Mic / PSTN audio"] --> CAP["Capture + resample<br/>PCM16 24 kHz"]
        PLAY["Speaker / earpiece"] --> OUT["Playback buffer"]
    end
    subgraph api ["Realtime session (one model)"]
        BUF["Input audio buffer"] --> M["Speech-to-speech model<br/>reasoning + tools + voice"]
        M --> AOUT["Output audio deltas<br/>+ transcripts + events"]
    end
    CAP -- "WebRTC media / WebSocket base64" --> BUF
    AOUT -- "audio deltas" --> OUT
    M -. "function_call events" .-> TOOLS["Your tools (server)"]
    TOOLS -. "function_call_output" .-> M

Examples as of November 2026: OpenAI's Realtime API (gpt-realtime-2.1 and siblings) and Google's Gemini Live API (gemini-3.8-live and siblings). Both keep server-side conversation state for the life of the session, both do server-side or client-side turn detection, and both expose function calling.

Strengths: lowest latency of the three architectures (no separate STT/TTS hops), the model hears how things were said (tone, hesitation, accent) rather than just the words, and interruption handling is built in.

Costs: you give up control of the intermediate text — debugging means reading transcripts, not inspecting a clean text pipeline; voices are provider-chosen presets; and the audio token prices are the highest of the three architectures.

1.3 Architecture B: full-duplex voice model + delegated backend (GPT-Live)#

OpenAI's newest offering, GPT-Live (gpt-live-1, live as of November 2026), splits the job differently: a voice model owns the conversation — listening, speaking, turn-taking, interruption — while a separate backend (a Responses-API model like gpt-6.1-terra, or your own agent via client delegation) does the reasoning and tool work. The voice model can keep talking while the backend thinks; results flow back as speech. This is what OpenAI calls delegation.

flowchart LR
    subgraph live ["GPT-Live session (full duplex)"]
        V["Voice model gpt-live-1<br/>listens, speaks, decides when to delegate"]
    end
    subgraph backend ["Delegated backend (your choice)"]
        R["Responses model or your agent<br/>reasoning + tools + business rules"]
    end
    MIC["Caller audio"] --> V
    V --> SPK["Spoken replies"]
    V -- "delegation events<br/>(context + task)" --> R
    R -- "results / updates" --> V
    R --> TOOLS["Your tools & data"]

The pitch is architectural: keep your existing text-agent prompts, tools and evals as the backend, and let the voice model be a specialised conversation layer. The price is a second model to configure and two sets of instructions to keep coherent. Part 4 covers it in depth.

1.4 Architecture C: the cascaded pipeline#

The oldest and still the most controllable shape — the one most voice-agent frameworks orchestrate:

flowchart LR
    A["Mic / phone audio"] --> STT["Streaming STT<br/>(Deepgram, Whisper, Gemini…)"]
    STT -- "partial + final transcripts" --> LLM["LLM text loop<br/>tools, RAG, approvals"]
    LLM -- "text deltas" --> TTS["Streaming TTS<br/>(ElevenLabs, OpenAI, Gemini…)"]
    TTS --> SPK["Speaker / earpiece"]
    STT -. "VAD / endpointing" .-> VAD["Turn detection<br/>(Silero, provider, framework)"]
    VAD -. "barge-in signal" .-> PLAY["Playback cancel +<br/>truncation bookkeeping"]

Every stage is a separate vendor call you can swap, log, cache and test. STT and TTS are covered in 09.4 and 09.5; the LLM stage is the agent loop you already know. The engineering cost is latency stacking: each hop adds time, and naïve implementations feel sluggish; and error compounding: an STT mistake becomes a wrong prompt, a TTS mispronunciation becomes a wrong answer delivered confidently.

1.5 Interruptions and truncation#

Whatever the architecture, the user will talk over the agent — it's normal human behaviour, not an edge case. Two things must happen:

  1. Stop playback immediately when user speech is detected (barge-in). On WebRTC the browser gives you this; on server pipelines you wire your VAD to the audio player.
  2. Fix the model's memory. The model generated audio the user never heard; if the transcript of that unheard audio stays in context, the model believes it said things it didn't. Realtime APIs handle this with truncation: OpenAI's conversation.item.truncate event marks how many milliseconds of the interrupted audio the user actually heard and drops the rest from the conversation (Part 3). In a cascaded pipeline, you own this bookkeeping — Part 10 shows how.

1.6 The decision table#

If you need… Choose Because
Lowest possible latency, rich conversational feel, one vendor Speech-to-speech realtime API (OpenAI Realtime, Gemini Live) One model, one hop; native barge-in and turn detection
Keep an existing text-agent brain (prompts, tools, evals) and add voice GPT-Live delegation or cascaded pipeline Backend stays a normal text agent; voice is a front end
Maximum control: swap every STT/LLM/TTS vendor, inspect every transcript Cascaded pipeline (framework or from scratch) Every stage is yours to log, test and replace
Telephony at scale with per-minute pricing clarity Hosted platform (Vapi, Retell, Bland) or framework + SIP (LiveKit, Pipecat) They absorb carrier, turn-taking and scaling complexity
Claude/Gemini text models as the brain Cascaded pipeline Anthropic has no realtime speech API; Gemini Live exists but is Google-stack
Regulated data that can't leave your infra Self-hosted framework (LiveKit Agents, Pipecat) + self-hosted or on-prem models You control the media path and the models
Rapid prototype this week Hosted platform or Pipecat/LiveKit starter Fastest path to a working call

Part 2: Choosing the realtime API#

2.1 The provider landscape as of November 2026#

Voice is the most volatile corner of the API world: endpoints, model names, event schemas and prices have all changed within the last year. Everything in this section was checked against official documentation on 2026-11-05; re-verify before you ship.

Provider Realtime speech-to-speech Delegated voice model Notes
OpenAI ✅ Realtime API (gpt-realtime-2.1, gpt-realtime-2, gpt-realtime-1.5, gpt-realtime, plus the -mini models) ✅ GPT-Live (gpt-live-1) WebRTC, WebSocket, SIP. Ephemeral client secrets. Function + MCP tools. 60-minute session cap
Anthropic ❌ No realtime or audio API ❌ Messages API accepts text and images, returns text. Voice means a cascaded pipeline with Claude as the text brain
Google Gemini ✅ Live API (gemini-3.8-live, gemini-3.8-live-extended-thinking, gemini-3.1-flash-live-preview) — WebSocket only. Session resumption + context-window compression for long calls. Function calling, Google Search grounding, affective dialog, proactive audio
OpenRouter ❌ No realtime WebSocket session API ❌ Audio files go in via input_audio content parts; audio files come out via /audio/speech and /audio/transcriptions. For live voice, route through a provider's own realtime API or a framework

The rest of this lesson covers the providers that have realtime APIs first — OpenAI (Parts 3–4) and Gemini (Part 5) — then the two that don't (Part 6), where the cascade architecture takes over.

2.2 How to choose, in one table#

Your situation Best fit
Fastest path to a polished browser voice demo OpenAI Realtime API over WebRTC with an ephemeral token (Part 9)
Phone calls (PSTN/SIP) with minimal glue OpenAI Realtime SIP or GPT-Live SIP; or a platform (Vapi/Retell/Bland) that sells telephony as a feature
Long calls (30–120 min) with lots of back-and-forth Gemini Live with session resumption and context compression — its 15-minute audio-only cap is the binding constraint elsewhere
Keep an existing text agent (prompts, tools, evals) and add voice GPT-Live client/Responses delegation, or a cascade where the LLM stage is unchanged
Multi-vendor flexibility, self-hosting, regulated data Cascaded pipeline on LiveKit Agents or Pipecat
Claude or a self-hosted text model as the brain Cascaded pipeline, always
Prototype this week, no infra team Hosted platform (Vapi, Retell, Bland, ElevenLabs Agents)

2.3 Verify-before-you-ship checklist#

Voice APIs change monthly. Before hard-coding anything:

  1. Model IDs: check the provider's models page (/api/docs/models/... for OpenAI, /docs/models/... for Gemini). Never reuse IDs from a blog post older than a few weeks.
  2. Event names: realtime protocols are versioned by event type strings. Diff your handler against the current server-events reference after any SDK upgrade.
  3. Prices: realtime is billed per audio token or per minute — the two units are not interchangeable, and cached-input discounts apply to text tokens on OpenAI but the audio-token caching rules differ. See 13.3.
  4. Limits: session duration caps, chunk size caps, concurrency quotas and WebSocket connection lifetimes are all documented per API and all change. Gemini's ~10-minute WebSocket lifetime and 15-minute audio-only session cap are the classic surprises.
  5. Beta flags: as of November 2026 the OpenAI Realtime API is GA (no OpenAI-Beta: realtime=v1 header) while parts of Gemini Live and OpenAI GPT-Live features still carry preview labels. Check the docs' status banners.

Part 3: The OpenAI Realtime API in depth#

The Realtime API is OpenAI's speech-to-speech service: one model (gpt-realtime-2.1 is the current flagship as of November 2026) that takes audio in and produces audio out, with text transcripts, function calling, MCP tools and server-side turn detection. It is GA — the old OpenAI-Beta: realtime=v1 header is gone.

3.1 Models and what they cost#

Model Context Max output Reasoning Best for
gpt-realtime-2.1 128,000 tokens 32,000 Configurable effort Flagship: strongest reasoning, tools, instruction following
gpt-realtime-2 128,000 32,000 Configurable effort Previous generation, same price tier
gpt-realtime-2.1-mini 128,000 32,000 Supports reasoning Distilled, faster and cheaper (audio $10 in / $20 out per 1M tokens; text $0.60 in / $2.40 out); the model OpenAI names as the migration target for its deprecated text-to-speech models (09.5, 4.1)
gpt-realtime-1.5 — — Non-reasoning Fast, cheap-feeling speech-to-speech
gpt-realtime-mini — — — Earlier small model, same prices as gpt-realtime-2.1-mini; its December 2025 snapshot shuts down 20 January 2027 with gpt-realtime-2.1-mini as the replacement
gpt-realtime 32,000 4,096 — First GA realtime model; smaller context. Deprecated: shuts down 20 January 2027 (OpenAI's deprecations page names gpt-realtime-2.1 as the replacement, as of November 2026)

Pricing for gpt-realtime-2.1 (per 1M tokens, as of November 2026 — audio is billed in audio tokens, see below):

Modality Input Cached input Output
Text $4.00 $0.40 $24.00
Audio $32.00 $0.40 $64.00
Image $5.00 $0.50 —

gpt-realtime-1.5 and gpt-realtime charge $16/M for text output (the same text input, $4/M); the two mini models are far cheaper per token, so price your own call mix before choosing. Audio dominates the bill: a minute of user speech is roughly 600 input audio tokens (1 token per 100 ms), and a minute of agent speech is roughly 1,200 output audio tokens (1 token per 50 ms), as OpenAI's Realtime cost guide states — so one minute of two-way audio is on the order of $0.10 before text and tool tokens. 13.3 turns this into a calculator.

3.2 Three ways to connect#

Transport Endpoint Auth Use when
WebRTC (browser/mobile) POST /v1/realtime/calls (unified interface) or client-side WebRTC with an ephemeral key Server API key for /calls; ephemeral client_secret for direct browser connect Real apps: browsers get mic/speaker, echo cancellation and jitter handling free
WebSocket (server-to-server) wss://api.openai.com/v1/realtime?model=gpt-realtime-2.1 Authorization: Bearer <key> header Your backend owns the audio pipeline: telephony bridges, recorded-audio testing, server-side agents
SIP (telephony) sip:$PROJECT_ID@sip.api.openai.com;transport=tls Project webhook + SIP trunk Inbound phone calls routed straight to the model

Ephemeral client secrets. Never ship your API key to a browser. Your server calls POST /v1/realtime/client_secrets with the session configuration and gets back {"value": "ek_…", "expires_at": …, "session": {...}} — the secret is the top-level value field, not nested under a client_secret key. The browser then either (a) uses it in the WebRTC handshake via the unified /v1/realtime/calls flow, or (b) opens the WebSocket with subprotocols ["realtime", "openai-insecure-api-key." + secret]. Two details that matter: the TTL is configurable via expires_after ({"anchor": "created_at", "seconds": N}, default 600 s, allowed range 10–7200 s), and a secret is not single-use — it can mint multiple sessions until it expires, so treat it as a bearer credential for its whole lifetime and keep seconds short. Set OpenAI-Safety-Identifier: <hashed-user-id> on the server request that mints the secret — OpenAI binds it to the resulting token/session for abuse tracking; it does not carry over to later connections, so set it on every mint.

Audio formats. Input and output are raw PCM16 mono at 24 kHz by default ({"type": "audio/pcm", "rate": 24000}). Output can also be audio/pcmu (G.711 µ-law) for telephony. Over WebSocket you base64-encode PCM chunks into input_audio_buffer.append events (each ≤ 15 MB). Over WebRTC the browser's getUserMedia and <audio> element handle all of this — you only exchange SDP and JSON events on the data channel.

3.3 The session object and the event model#

A Realtime session is stateful: the server keeps the conversation, you send client events and receive server events, all JSON. The lifecycle:

sequenceDiagram
    participant C as Client
    participant S as Realtime API
    C->>S: connect (WebRTC SDP / WebSocket / SIP)
    S-->>C: session.created
    C->>S: session.update (model, voice, VAD, tools, instructions)
    S-->>C: session.updated
    loop each user turn
        S-->>C: input_audio_buffer.speech_started
        S-->>C: input_audio_buffer.speech_stopped (+ transcript deltas)
        S-->>C: response.created → output_audio.delta … → response.done
    end
    C->>S: conversation.item.truncate (on interruption, WebSocket only)
    C->>S: session.close / connection ends

The core session.update (this is the GA shape — note type: "realtime" and output_modalities):

json
{
  "type": "session.update",
  "session": {
    "type": "realtime",
    "model": "gpt-realtime-2.1",
    "output_modalities": ["audio"],
    "audio": {
      "input": {
        "format": { "type": "audio/pcm", "rate": 24000 },
        "turn_detection": { "type": "semantic_vad", "eagerness": "auto" },
        "noise_reduction": { "type": "near_field", "strength": 0.8 },
        "transcription": { "model": "gpt-realtime-whisper" }
      },
      "output": {
        "format": { "type": "audio/pcm", "rate": 24000 },
        "voice": "marin"
      }
    },
    "instructions": "You are the phone assistant for Northwind Garden Supplies...",
    "tools": [ /* function + mcp tools */ ],
    "tool_choice": "auto"
  }
}

Rules that bite people:

  • output_modalities is ["audio"] or ["text"], never both in one response; pick per response.create if you need both at different times.
  • voice is one of alloy, ash, ballad, coral, echo, sage, shimmer, verse, marin, cedar (OpenAI recommends marin or cedar for best quality as of November 2026). It cannot be changed after the model has produced audio once in the session.
  • Most session fields can be updated mid-session via session.update; the conversation, tools and instructions are all live-editable — a genuinely useful property for long calls.
  • instructions can also reference a server-stored prompt (prompt: {id: "pmpt_...", version, variables}) so prompt management lives in OpenAI's prompt library rather than your deploy.
  • audio.input.noise_reduction filters the audio before VAD and the model: type is near_field (headsets) or far_field (laptop/conference mics) and strength is 0–1 (default 1). It improves VAD accuracy and model perception in noisy environments; set it to null to disable.
  • audio.input.transcription turns on input audio transcription — off by default. It is not native to the model (the model hears audio directly); a separate transcription model (whisper-1, gpt-realtime-whisper, gpt-4o-transcribe, gpt-4o-mini-transcribe, gpt-transcribe, gpt-live-transcribe, gpt-4o-transcribe-diarize as of November 2026) transcribes asynchronously and emits conversation.item.input_audio_transcription.completed events for your captions/logs. It accepts language/languages, keywords, prompt and (for gpt-realtime-whisper) delay; it is billed separately per audio duration. Treat the transcript as guidance, not gospel — it can differ from what the model actually heard.
  • audio.input.turn_detection also takes idle_timeout_ms on server_vad: if the caller goes quiet mid-thought, the model nudges the conversation forward and an input_audio_buffer.timeout_triggered event fires — the "are you still there?" primitive for phone calls.
  • Maximum session duration: 60 minutes. Plan handoffs or session rotation for longer interactions.

3.4 Turn detection (VAD)#

Turn detection decides when the user has finished speaking. Two modes plus manual:

Mode How it decides Tuning
server_vad (default for speech-to-speech) Silence-based: speech start/stop from audio energy threshold (0–1, higher = louder needed, better in noise), prefix_padding_ms, silence_duration_ms (lower = faster turns, more false cuts), idle_timeout_ms (auto-nudge after a long caller silence)
semantic_vad A semantic classifier scores "is the user done?" from the words eagerness: low/medium/high/auto (default auto, equivalent to medium; the named levels cap the max wait at 8s/4s/2s respectively — high responds fastest, low is most patient)
null You control turns manually Push-to-talk: you send input_audio_buffer.commit + response.create yourself

create_response and interrupt_response flags let VAD chunk turns without auto-responding or auto-interrupting — useful when you want a moderation or validation step between hearing and replying. 09.6 goes deeper on VAD algorithm choice; the provider's built-in modes cover most cases.

Two VAD footnotes that bite: in transcription-only sessions on gpt-realtime-whisper or gpt-live-transcribe, turn detection must be omitted or null — those models don't support VAD; you commit each turn yourself with input_audio_buffer.commit. And in push-to-talk on WebRTC/SIP, send input_audio_buffer.clear on key-down and output_audio_buffer.clear to drop unplayed model audio (see 3.6).

3.5 Function calling and MCP tools#

Tools work like text tool-calling but over the event stream. Declare them in session.tools (or per response.create):

json
{ "type": "function", "name": "lookup_order",
  "description": "Look up an order by order number.",
  "parameters": { "type": "object",
    "properties": { "order_id": { "type": "string" } },
    "required": ["order_id"] } }

When the model decides to call it, response.done contains an output item of type: "function_call" with name, arguments (a JSON string) and call_id. Your code executes the function, then returns the result as a conversation.item.create event with type: "function_call_output", the same call_id, and output as a JSON string — then sends response.create to let the model speak the result. The full loop is in Part 8.

MCP tools are newer: { "type": "mcp", "server_label": "orders", "server_url": "https://...", "allowed_tools": [...], "require_approval": "never" } — the Realtime API itself connects to the MCP server and executes the calls, surfacing approval requests as conversation items you can accept or reject. Use MCP when the tool already lives behind an MCP server; use function tools when the logic is yours.

3.6 Interruptions, truncation and conversation control#

  • Barge-in is automatic with VAD on: user speech cancels the in-flight response (response.done arrives with status: "cancelled" — don't wait for it before stopping playback; the docs' order is: stop playback on speech_started, send truncation, then observe response.done).
  • WebRTC and SIP: the server tracks how much audio was played and truncates unplayed audio itself.
  • WebSocket: you must truncate. On input_audio_buffer.speech_started, stop playback, measure how many ms of the interrupted item the user heard, then send conversation.item.truncate with item_id, content_index and audio_end_ms. Skip this and the model believes it said things the user never heard (1.5). Note the docs' caveat: truncation cuts the audio and drops the transcript for the unplayed portion — the model can't align them precisely, so you get a clean cut, not a verbatim partial transcript.
  • output_audio_buffer.clear is the WebRTC/SIP-side "clear unplayed audio" event: it drops the server's output buffer and truncates the conversation in one step. It's the event the push-to-talk flow uses instead of conversation.item.truncate (which is WebSocket-only); send it when you need to hard-reset what the model is saying — e.g. a guardrail fired mid-sentence.
  • Out-of-band responses: response.create with response.conversation: "none" generates a response that doesn't enter the main conversation — for background classification or scoring. Tag it with metadata to match its response.done.
  • Custom context: response.input accepts item_reference entries to reuse earlier items, or [] for a context-free response.

3.7 Cost and limit gotchas#

  • Billing is per Response (each response.create or VAD-triggered turn), in input + output tokens across text/audio/image modalities. Empty audio filtered by VAD doesn't bill as input.
  • Prompt caching applies automatically — the growing conversation prefix is cached, which is why cached_tokens shows up in usage on response.done. Keep instructions and tool definitions stable at the front to maximise hits.
  • token_limits.post_instructions caps input tokens per response (truncating oldest items first) — your cost ceiling per turn.
  • session.truncation + retention_ratio control how aggressively that truncation drops context: the server default 1.0 removes only what it must; a lower ratio (e.g. 0.8) drops extra history each truncation, which keeps more headroom before the next truncation and protects prompt-cache hits — OpenAI's cost guide recommends pairing token_limits with retention_ratio < 1 for long sessions. Trade-off: less model memory per turn.
  • Transcription-only sessions (gpt-realtime-whisper, gpt-live-transcribe, gpt-transcribe) and translation (gpt-realtime-translate) are billed by audio duration, not tokens — different budget maths.
  • Errors arrive as error events correlated by event_id; rate_limits.updated events stream your remaining quota live.

Part 4: GPT-Live — a voice model with a delegated backend#

Deep-dive

GPT-Live (gpt-live-1) is OpenAI's newest voice architecture, live as of November 2026. It inverts the Realtime API's "one model does everything" design: the voice model owns the conversation; a separate backend owns the thinking.

4.1 The delegation model#

  • The voice layer (gpt-live-1) listens and speaks full-duplex — it can talk while still listening, handle interruptions naturally, and decides when a request needs backend work.
  • The backend does reasoning and tools. Two modes:
    • Responses delegation: OpenAI runs a Responses-API model (e.g. gpt-6.1-terra) as the backend, passing conversation context and tool results between it and the voice model. Your app still executes custom functions.
    • Client delegation: your application is the backend — any model, agent harness or service. GPT-Live sends delegation events; you run the work and return results.

You choose the mode at session creation. The voice model gets a short prompt (conversation style, when to delegate); the backend keeps your full business instructions, tool workflows and permissions. This maps cleanly onto an existing text agent: the backend is your agent.

4.2 Connecting#

Same transports as Realtime: WebRTC (recommended), WebSocket, SIP. The WebSocket endpoint is wss://api.openai.com/v1/live/sessions — note /v1/live/, a different API surface with its own event names:

  • Client → server: session.start (first message, carries the whole session config), session.input_audio.append (base64 PCM), session.update, the three context-append events (session.instructions.append, session.thinking.append, session.commentary.append — see 4.5), session.input_audio.mute/unmute, response.create, session.close.
  • Server → client: session.started (resolved config + session id — wait for it), session.output_audio.delta, session.input_transcript.delta, session.output_transcript.delta, response.event (nested backend events), session.updated, session.usage.updated (live cost meter), session.closed (final usage — keep receiving until it arrives).

Audio formats: PCM16 mono at 24 kHz or 16 kHz, or G.711 audio/pcmu/audio/pcma at 8 kHz for telephony — one format per session, no mid-session changes. One session field matters for later: store (default false) controls whether the finished call is retained as a downloadable recording you can fork or replay — see 4.5 and Part 14.

For WebRTC, your server POSTs {session: {...}, transport: {type: "webrtc", sdp: <offer>}} to POST /v1/live/sessions and returns the SDP answer. Creating a WebRTC session bills 15 seconds of voice duration at init, credited against the running session — not extra.

4.3 Pricing and limits#

  • Voice: $0.05 per minute, billed per second — duration-based, not token-based. Backend model and tool usage bills separately at normal API rates.
  • A 90-second call with $0.02 of backend tokens costs ~$0.095 total. Silence is expensive: close the session during long backend tasks rather than leave the voice line open (voice-latency-cost guide).
  • Sideband: a second server-side WebSocket can attach to a live session to observe events or send commands (guardrails, redirects, playback control) while audio continues on the primary connection — your monitoring/steering hook.
  • Custom voices: you can create voices from a text description or from recordings (with responsible-use constraints); select at session creation.
  • Partner integrations exist for LiveKit, Twilio, Telnyx, Bandwidth and Daily/Pipecat, so existing telephony stacks can front GPT-Live.

4.4 Realtime API vs GPT-Live — when each#

Realtime API GPT-Live
Architecture One model: hears, thinks, speaks Voice model + delegated backend
Billing Audio/text/image tokens per response $0.05/min voice + backend tokens
Best when You want one vendor, one prompt, tightest integration You already have a text agent brain to reuse
Tool execution Your client executes function tools; MCP tools run API-side Backend (Responses or yours) executes; voice layer delegates
Long tasks Tool call pauses the voice turn Backend work continues while the voice model keeps talking
Maturity GA, longer track record Newer (2026), faster-moving docs

4.5 Session lifecycle extras#

GPT-Live's session model has several features the event list only hints at — all verified against the managing-sessions guide as of November 2026:

  • Three ways to add context mid-call. session.instructions.append adds trusted instructions that steer behaviour; session.thinking.append adds factual context the model shouldn't necessarily say aloud ("the account lookup is still running", "the user already accepted the terms"); session.commentary.append adds information the model may speak, paraphrasing as needed. Each takes content (≤500 tokens), a delegation_id (null for session-wide) and a unique event_id; the matching *.appended acknowledgement tells you when the timeline reaches it — it does not confirm the words were spoken.
  • session.usage.updated is your live cost meter. It reports cumulative voice duration in seconds ({"usage": {"seconds": 12}, "context_window": {"usage_ratio": 0.42}}) — read the latest value as the running total; do not sum the events. context_window.usage_ratio tells you how full the voice context is; past ~90% the service spins up a replacement voice engine carrying your instructions plus a compressed history.
  • Greeting seeding. For reliable openers, put a developer-role message in session.input at creation and send the same greeting once via session.commentary.append after session.started, keeping input audio running. Startup instructions improve greetings but don't guarantee speech — for exact wording, play a recorded clip yourself.
  • Session forking — the answer to "calls longer than a session" and callbacks. store: true makes a finished session retain a stored recording (available 30 days; with Zero Data Retention, store is forced false and forking is unavailable). Fork it on a new connection — WebSocket: connect to wss://api.openai.com/v1/live/sessions/{source_session_id}/fork; WebRTC: POST /v1/live/sessions/{source_session_id}/fork with a new SDP offer — and the child inherits the model, voice, instructions and conversation, with a new session ID. The child gets its own store setting (omitted = inherit). Use cases: a caller hangs up and phones back, an eval suite replaying one reference conversation into many trials, or continuing after a dropped connection.
  • Stored recordings. GET /v1/live/sessions/{session_id}/content returns the finished call as stereo WAV — caller on the left channel, agent on the right — after the session finalises (session.closed; saving the recording can add finalisation time). This is the API-native answer to "record the call": gate store behind consent (14.1), and remember forking requires a completed stored recording.
  • SIP call controls. On SIP sessions, POST /v1/live/sessions/{session_id}/refer with {"target_uri": "sip:agent@example.com"} (or tel:+1…) transfers the call — it becomes the SIP Refer-To header, a native warm-transfer primitive — and POST /v1/live/sessions/{session_id}/hangup ends it. DTMF arrives as transport.dtmf.received on the sideband; transport.dtmf.send plays tones back. (The Realtime API's SIP surface has the same shape at /v1/realtime/calls/{call_id}/refer and /hangup.)

4.6 A minimal GPT-Live session#

Part 8 shows raw-WebSocket sessions for Realtime and Gemini; GPT-Live is different enough to show here, in its SDK form. The OpenAI Python SDK (openai[realtime]) ships client.live.connect() — the same session.start / session.input_audio.append / session.closed flow as the wire protocol:

python
# gpt_live_ws.py — a minimal GPT-Live session (server-side, SDK form).
# Requires the realtime extra: pip install "openai[realtime]"
import asyncio
import base64
import os

from dotenv import load_dotenv
from openai import AsyncOpenAI

load_dotenv()


async def main():
    session_config = {
        "model": "gpt-live-1",
        "instructions": (
            "You are a concise voice assistant for an electronics store. "
            "Keep answers under two sentences; delegate lookups to the backend."
        ),
        "audio": {
            "format": {"type": "audio/pcm", "rate": 24000},   # PCM16 mono 24 kHz
            "output": {"voice": "marin"},
        },
        # Responses delegation: OpenAI runs the backend model (web_search here);
        # your own tools still execute in your app — see live-delegation guide.
        "delegation": {
            "type": "responses",
            "responses": {
                "model": "gpt-6-luna",
                "tools": [{"type": "web_search"}],
                "tool_choice": "auto",
            },
        },
    }

    async with AsyncOpenAI() as client:
        async with client.live.connect() as connection:
            # First message on the wire: session.start with the whole config.
            await connection.session.start(session=session_config)

            # Feed mic audio as raw PCM16 24 kHz mono, base64-encoded:
            #   await connection.session.input_audio.append(audio=b64_chunk)
            # Keep feeding silence before the caller speaks if you seed a greeting.

            async for event in connection:
                if event.type == "session.started":
                    print("[session ready]", event.session.id)
                elif event.type == "session.output_audio.delta":
                    pass  # base64 PCM16 — decode and play (docs stream it to stdout)
                elif event.type == "session.output_transcript.delta":
                    print(event.delta, end="", flush=True)   # live captions
                elif event.type == "session.usage.updated":
                    pass  # cumulative seconds — your live cost meter, don't sum
                elif event.type == "session.closed":
                    print("\n[closed]", event.usage)  # final usage; keep the loop
                    break                                # open until this arrives


if __name__ == "__main__":
    asyncio.run(main())
Example output · illustrative3 lines
[session ready] live_sess_abc123
Your order A-1042 shipped and should arrive Friday.
[closed] {'seconds': 47.2, ...}

Two habits this example encodes: wait for session.started before treating the session as live (it carries the resolved config and session id you'll need for /fork, /content, sideband and SIP controls), and don't exit on the first transcript delta — session.closed carries the final usage snapshot and arrives only after you send session.close (or the transport ends); a socket that closes first leaves final usage unconfirmed.


Part 5: The Gemini Live API in depth#

Deep-dive

Gemini Live is Google's bidirectional audio API: WebSocket-only, native audio in and out, and the most feature-dense realtime API of the three — function calling, Google Search grounding, affective dialog, proactive audio, session resumption and context compression.

5.1 Models, specs and endpoint#

Model Status (Nov 2026) Notes
gemini-3.8-live Stable, default Low-latency voice agent model
gemini-3.8-live-extended-thinking Stable Adds configurable background reasoning (thinkingLevel low/medium/high)
gemini-3.1-flash-live-preview Preview Previous generation; Google's deprecations page lists 17 November 2026 as the earliest shutdown date, with gemini-3.8-live as the replacement
gemini-2.5-flash-native-audio-preview-12-2025 Preview Legacy native-audio model, same 17 November 2026 earliest shutdown date and replacement — the docs' display name "Gemini 2.5 Flash Live Preview" is not the API ID

Technical specs (from Google's docs): input is raw 16-bit PCM audio at 16 kHz little-endian, JPEG or PNG images at ≤1 FPS, and text; output is raw 16-bit PCM at 24 kHz. Protocol is a stateful WebSocket (wss).

Endpoint (API key in the query string — fine server-side, use ephemeral tokens client-side):

text
wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent?key=YOUR_API_KEY

The first message must be a BidiGenerateContentSetup carrying the full config (model, system instruction, voice, tools, transcription, compression); the server replies setupComplete. Then audio flows as realtimeInput messages and responses arrive as serverContent messages with modelTurn parts (inlineData = audio bytes, outputTranscription = text). The Python SDK wraps this as client.aio.live.connect(model=..., config=types.LiveConnectConfig(...)), session.send_realtime_input(audio=types.Blob(data=..., mime_type="audio/pcm;rate=16000")), and async for response in session.receive().

5.2 Session configuration#

Key LiveConnectConfig fields (verify names against the current SDK — google-genai 2.34.x):

  • response_modalities=["AUDIO"] (or ["TEXT"])
  • system_instruction — the voice-agent prompt
  • speech_config.voice_config.prebuilt_voice_config.voice_name — any TTS voice (e.g. Kore, Puck, Charon…; the set matches the TTS voice list — check the speech-generation docs for the current roster)
  • input_audio_transcription / output_audio_transcription — get text of both sides for your logs and UI captions
  • tools — function_declarations (your functions) and/or google_search grounding
  • proactivity / proactive audio — whether the model may respond proactively or stay silent; support is per-model (permanently on for gemini-3.8-live, configurable on gemini-2.5-flash-native-audio-preview-12-2025, unsupported on gemini-3.1-flash-live-preview — check the capabilities table)
  • enable_affective_dialog — tone adaptation to the user's expression; supported only on gemini-2.5-flash-native-audio-preview-12-2025 and removed from the Gemini 3.x Live models (omit the field there — setting it is wrong, not just ignored)
  • context_window_compression, session_resumption — see 5.6
  • realtime_input_config — automatic activity detection parameters (the Gemini analogue of VAD)

5.3 Tools and grounding#

  • Function calling: declare function_declarations in setup; the model emits toolCall messages with function calls; you execute and return toolResponse messages. Asynchronous (NON_BLOCKING) function calling is per-model, not generational — gemini-3.8-live supports it by default (plus BLOCKING and function scheduling SILENT/WHEN_IDLE/INTERRUPTED), gemini-3.8-live-extended-thinking is async-only, gemini-2.5-flash-native-audio-preview-12-2025 supports both modes, and gemini-3.1-flash-live-preview is synchronous-only (the model waits for your toolResponse). Check the capabilities table for your model before relying on the model talking while your tool runs.
  • Google Search grounding: add the google_search tool and the live model can ground spoken answers in current web results — unique among the realtime APIs here (OpenAI Realtime has MCP/web tools but not built-in search grounding in the same way; verify per-model).
  • Multimodal input: the session accepts images (JPEG ≤1 FPS) and text mid-conversation — "what's wrong with this photo?" works in a voice call.

5.4 Transcription, languages and extras#

  • 99 languages supported for conversation (per Google's capabilities doc, as of November 2026 — check the supported-languages table); audio transcription can use custom vocabulary biasing (up to ~1,000 terms — names, product SKUs, jargon) to fix recognition of domain words.
  • Proactive audio lets the model decide when to respond (or stay silent) rather than always replying — useful for ambient/assistant scenarios; permanently enabled on the 3.8 Live models.
  • Affective dialog adapts tone to the user's expression — but only on gemini-2.5-flash-native-audio-preview-12-2025; it was removed from the Gemini 3.x Live models.
  • Dedicated sibling APIs exist for Live Transcribe (gemini-3.5-transcribe-live, ~$0.009/min blended) and Live Translate (gemini-3.5-live-translate-preview — note the -preview suffix) if you need transcription-only or translation streams rather than a full agent.

5.5 Ephemeral tokens for browsers#

Same pattern as OpenAI: your server mints a short-lived token via client.auth_tokens.create(config={"uses": 1, "expire_time": ..., "new_session_expire_time": ...}) — defaults are ~1 minute to start a session and ~30 minutes of connection life. The browser connects to the BidiGenerateContentConstrained endpoint with ?access_token=<token> instead of ?key=. Ephemeral tokens are Live-API-only as of November 2026.

5.6 Session lifetime, resumption and compression#

The classic Gemini Live gotcha, and it hasn't gone away:

  • Audio-only sessions cap at ~15 minutes; audio+video at ~2 minutes without compression — the context window fills with audio tokens.
  • The WebSocket connection itself lives ~10 minutes; when it drops, the session drops with it.

The two engineered escapes:

  • Context window compression (context_window_compression with a sliding_window and trigger_tokens): the server compresses older context as the window fills, extending sessions "to an unlimited amount of time" per Google's docs.
  • Session resumption (session_resumption in setup): the server emits sessionResumptionUpdate messages carrying resumable handles; on reconnect you pass the last handle in sessionResumption.handle and the session continues. Resumption tokens are valid ~2 hours after termination, and the same ephemeral token can reconnect even with uses: 1.
  • A GoAway message arrives before the server closes a connection, carrying timeLeft — your cue to reconnect cleanly.

Design rule: always implement resumption + GoAway handling for production Gemini Live, and prefer compression for long calls. For calls longer than ~an hour, reconsider architecture — a cascade or GPT-Live may fit better.

5.7 Pricing (as of November 2026)#

gemini-3.8-live (and siblings at standard tier) Per 1M tokens Per minute equivalent
Audio input $3.00 ~$0.005/min
Audio output $12.00 ~$0.018/min
Text input $0.75 —
Text output (incl. thinking) $4.50 —
Image/video input $1.00 ~$0.002/min

A free tier exists (free of charge, data used to improve products). Google Search grounding in live sessions: 5,000 free requests/month shared across Gemini 3+ models, then $14 per 1,000 requests — and the paid tier is also capped at 1,500 requests/day, a real constraint for high-volume callers. Billing is per-token like everything else on Gemini — but note that every turn resends context, so long sessions accumulate input tokens fast; compression and resumption manage context size, not just connection life.


Part 6: Providers without a realtime API#

Reference

6.1 Anthropic: Claude as the brain, not the voice#

Anthropic's Messages API accepts text and images and returns text — there is no audio modality, no realtime endpoint, no transcription or speech API as of November 2026. This is a positioning fact, not a gap you can route around: if Claude must be the reasoning engine, the voice layer has to be somebody else's.

The standard pattern: STT → Claude (Messages API, with tools) → TTS. Claude's strengths — instruction following, tool use, long-context reasoning — are unaffected; you just own the audio plumbing. See Part 10 for the pipeline, and 09.4/09.5 for picking STT/TTS vendors.

6.2 OpenRouter: audio files, not audio sessions#

OpenRouter can transcribe (audio in via chat input_audio parts) and speak (/api/v1/audio/speech, /api/v1/audio/transcriptions endpoints as of November 2026), and its catalogue marks which models accept audio modalities. But there is no realtime WebSocket session API — a voice agent on OpenRouter means either a cascade (OpenRouter for the text LLM stage, a separate STT/TTS provider) or a framework that integrates OpenRouter as its LLM plugin (LiveKit Agents does exactly this). Check supported_parameters/modalities per model before assuming audio support — it varies by endpoint.

6.3 Third-party speech specialists still matter#

Even with realtime APIs, specialists win specific stages of a cascade: Deepgram/AssemblyAI/Speechmatics for streaming STT with diarization, ElevenLabs/Cartesia/Deepgram Aura for TTS quality and voice cloning, and platforms like Vapi/Retell that bundle all three. 09.4 and 09.5 own those comparisons; the realtime lesson's point is that mixing happens at the stage level, not inside a speech-to-speech session — Gemini Live always speaks with its own voices, so you cannot put an ElevenLabs voice on its audio output, whereas a cascade can pair any STT with Claude and any TTS.


Part 7: Frameworks and hosted platforms#

Deep-dive

When you don't want to own the audio plumbing — echo cancellation edge cases, telephony carriers, scaling WebSocket fleets, turn-taking heuristics — two escape hatches exist: open-source frameworks you run yourself, and hosted platforms that sell the whole stack.

7.1 The landscape as of November 2026#

Option Type License / cost Transport What you own
LiveKit Agents Framework (Python + Node) Apache-2.0; self-host free, LiveKit Cloud ~$0.01/min agent minutes WebRTC SFU + native SIP Agent logic, deployment; they own media transport
Pipecat Framework (Python) BSD-2; self-host free; Pipecat Cloud hosting from $0.01 per active agent-minute (agent-1x), transport and model vendors billed separately Transport-agnostic: WebRTC, WebSocket, telephony (via Daily) Pipeline composition; they own transport plumbing
Vapi Hosted platform ~$0.05/min platform fee + provider costs at cost or your keys Web, phone (Vapi numbers or BYO SIP) Configuration, prompts, workflows
Retell AI Hosted platform ~$0.055/min voice infra + LLM/voice/telephony Phone-first, web Same
Bland AI Hosted platform ~$0.14/min all-in (LLM+STT+TTS) on entry tier Phone-first, high-volume campaigns Same
ElevenLabs Agents Hosted platform Per-minute voice-agent pricing on top of ElevenLabs Web/phone Prompt + voice; most turnkey
Twilio ConversationRelay Telephony bridge (not a framework) Twilio per-minute + your STT/LLM/TTS costs PSTN/SIP only The whole cascade; Twilio owns the phone plumbing
OpenAI Agents SDK realtime / Gemini Live Provider-native Provider pricing Provider transports Everything except what the API gives you

(Prices are list-price approximations from vendor pages and third-party trackers as of November 2026 — verify current rates; they're the most volatile numbers in this lesson.)

One row deserves expansion: the provider-native Agents SDK path. OpenAI's Agents SDK — the same framework family as the text agent loop in 08A.2 — now ships realtime primitives: RealtimeAgent (instructions, tools, guardrails, handoffs for one voice specialist) + RealtimeRunner/RealtimeSession in Python (agents.realtime, default transport a server-side WebSocket via OpenAIRealtimeWebSocketModel), and RealtimeAgent/RealtimeSession from @openai/agents/realtime in JS/TS — the official Realtime quickstart leads with it. The Python SDK deliberately has no browser WebRTC transport — pair it with your own WebRTC frontend or a framework for browser calls. It gives you the agent-loop ergonomics (tools, handoffs, guardrails) without hand-rolling the event dispatch in Part 8 — at the cost of less visibility into the wire protocol, so learn the raw events first.

7.2 How to choose#

  • Framework (LiveKit/Pipecat) when: you have engineers, need custom pipelines (e.g., Claude brain + specific STT/TTS), data can't leave your infra, or unit economics matter at scale. LiveKit gives you a full WebRTC SFU + SIP; Pipecat gives you a composable frame pipeline that's transport-agnostic and famously swappable (change one service line to swap STT/LLM/TTS vendors).
  • Hosted platform (Vapi/Retell/Bland/ElevenLabs) when: speed-to-phone-line matters, you want visual workflow builders, per-minute pricing is acceptable, and you don't want to run media infrastructure. You trade control and margin for weeks of integration saved.
  • Twilio ConversationRelay when: your entire surface is the phone network and you want Twilio to handle media while you run STT→LLM→TTS over webhooks — it streams transcript tokens to your app and plays TTS back, handling interruptions. It's a bridge, not an agent framework; pair it with a cascade.
  • Provider-native (Realtime/Live/GPT-Live) when: lowest latency and simplest ops win, and you're comfortable with that vendor's model, voice and event model.

7.3 The hybrid pattern that wins in production#

The most common real architecture: framework for transport + turn-taking, best-of-breed model per stage. LiveKit Agents or Pipecat handles WebRTC/SIP/VAD/barge-in; you plug in Gemini Live or a Realtime-API session as the "LLM" stage where supported, or a cascade of Deepgram STT + Claude + ElevenLabs TTS. This keeps the audio plumbing commodity while the intelligence stays best-of-breed — at the cost of integrating two event models (the framework's and the realtime API's), which is exactly what Part 10 and the running example in the module projects are for.


Part 8: Full example 1 — a server-side WebSocket voice session#

This part builds the smallest real thing: a Python server that holds a Realtime API WebSocket session, feeds it audio, and prints what comes back. Two variants — OpenAI Realtime and Gemini Live — because their event models differ enough that you should see both.

8.1 OpenAI Realtime over WebSocket#

The flow: connect to wss://api.openai.com/v1/realtime?model=gpt-realtime-2.1 with your API key, wait for session.created, send session.update, then stream PCM16/24 kHz mono audio as base64 input_audio_buffer.append events. Server events arrive as JSON; response.output_audio.delta carries base64 audio, response.output_audio_transcript.delta carries the words being spoken, and response.done ends the turn.

python
# realtime_ws.py — a minimal OpenAI Realtime WebSocket session (server-side).
# Feed it PCM16 24 kHz mono chunks; it prints transcripts and saves audio.
import asyncio, base64, json, os

import websockets
from dotenv import load_dotenv

load_dotenv()
MODEL = "gpt-realtime-2.1"
URL = f"wss://api.openai.com/v1/realtime?model={MODEL}"
HEADERS = {
    "Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
    # Stable, privacy-preserving per-user id for abuse tracking (hashed, never raw PII)
    "OpenAI-Safety-Identifier": "hashed-user-id-example",
}

SESSION_UPDATE = {
    "type": "session.update",
    "session": {
        "type": "realtime",
        "model": MODEL,
        "output_modalities": ["audio"],
        "audio": {
            "input": {
                "format": {"type": "audio/pcm", "rate": 24000},
                "turn_detection": {"type": "semantic_vad", "eagerness": "auto"},
                # Input transcription is OFF by default — without this the
                # conversation.item.input_audio_transcription.completed
                # events below never fire. Billed separately per audio minute.
                "transcription": {"model": "gpt-realtime-whisper"},
                "noise_reduction": {"type": "near_field"},
            },
            "output": {
                "format": {"type": "audio/pcm", "rate": 24000},
                "voice": "marin",
            },
        },
        "instructions": (
            "You are a concise voice assistant for an electronics store. "
            "Confirm order numbers digit by digit. Keep answers under two sentences."
        ),
        "tools": [
            {
                "type": "function",
                "name": "lookup_order",
                "description": "Look up an order's status by order number.",
                "parameters": {
                    "type": "object",
                    "properties": {"order_id": {"type": "string"}},
                    "required": ["order_id"],
                },
            }
        ],
        "tool_choice": "auto",
    },
}


async def send_audio(ws, pcm16_24k_mono: bytes):
    """Append one chunk of raw PCM16 audio (24 kHz mono) to the input buffer."""
    await ws.send(json.dumps({
        "type": "input_audio_buffer.append",
        "audio": base64.b64encode(pcm16_24k_mono).decode("ascii"),
    }))


async def run_tool_and_reply(ws, call_id: str, name: str, arguments: str):
    """Execute a function_call and return its result to the model."""
    args = json.loads(arguments)
    # In production this hits your orders service; here a stub keeps it honest.
    result = {"order_id": args.get("order_id"), "status": "shipped", "eta": "Friday"}
    await ws.send(json.dumps({
        "type": "conversation.item.create",
        "item": {
            "type": "function_call_output",
            "call_id": call_id,
            "output": json.dumps(result),
        },
    }))
    await ws.send(json.dumps({"type": "response.create"}))


async def handle_events(ws):
    """Dispatch server events: audio out, transcripts, function calls, errors."""
    audio_parts = []
    async for raw in ws:
        event = json.loads(raw)
        t = event["type"]
        if t == "session.created":
            await ws.send(json.dumps(SESSION_UPDATE))
        elif t == "session.updated":
            print("[session ready]")
        elif t == "input_audio_buffer.speech_started":
            print("[user started speaking]")  # stop playback here on a real client
        elif t == "conversation.item.input_audio_transcription.completed":
            print(f"[user said] {event.get('transcript', '')}")
        elif t == "response.output_audio_transcript.delta":
            print(event["delta"], end="", flush=True)  # stream the words being spoken
        elif t == "response.output_audio.delta":
            audio_parts.append(base64.b64decode(event["delta"]))
        elif t == "response.done":
            print()  # end of turn
            for item in event["response"].get("output", []):
                if item.get("type") == "function_call":
                    await run_tool_and_reply(
                        ws, item["call_id"], item["name"], item["arguments"]
                    )
        elif t == "error":
            print(f"[error] {event['error']}")
        elif t == "rate_limits.updated":
            pass  # monitor quota live if you want


async def main():
    async with websockets.connect(URL, additional_headers=HEADERS) as ws:
        # In a real app, feed mic audio from send_audio(); here we just listen.
        await handle_events(ws)


if __name__ == "__main__":
    asyncio.run(main())
Example output · illustrative4 lines
[session ready]
[user started speaking]
[user said] where is my order A-1042?
Your order A-1042 shipped and should arrive Friday.

What this leaves out, and what production adds: resampling your mic to 24 kHz mono PCM16 (09.6's lab), jitter buffering on output, conversation.item.truncate on interruption for WebSocket clients (3.6), reconnection logic, and per-turn latency logging. Each is covered later in this lesson.

8.2 Gemini Live over WebSocket#

Same skeleton, different protocol. Gemini's Live API speaks BidiGenerateContent messages: you send one BidiGenerateContentSetup first, then realtimeInput audio blobs; the server streams serverContent with modelTurn parts. The Python SDK (google-genai 2.34.x) wraps it as client.aio.live.connect(...) — shown here because it's the supported path:

python
# gemini_live_ws.py — a minimal Gemini Live session (server-side, SDK form).
import asyncio
import os

from dotenv import load_dotenv
from google import genai
from google.genai import types

load_dotenv()


async def main():
    client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
    config = types.LiveConnectConfig(
        response_modalities=["AUDIO"],
        system_instruction=(
            "You are a concise voice assistant for an electronics store. "
            "Confirm order numbers digit by digit. Keep answers under two sentences."
        ),
        speech_config=types.SpeechConfig(
            voice_config=types.VoiceConfig(
                prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name="Kore")
            )
        ),
        input_audio_transcription=types.AudioTranscriptionConfig(),
        output_audio_transcription=types.AudioTranscriptionConfig(),
        # Long calls: let the server compress context and resume across reconnects
        context_window_compression=types.ContextWindowCompressionConfig(
            sliding_window=types.SlidingWindow()
        ),
        session_resumption=types.SessionResumptionConfig(),
    )

    async with client.aio.live.connect(model="gemini-3.8-live", config=config) as session:
        # Feed mic audio: session.send_realtime_input(
        #     audio=types.Blob(data=pcm16_16k_mono, mime_type="audio/pcm;rate=16000"))
        async for response in session.receive():
            server = response.server_content
            if server is None:
                continue
            if server.input_transcription and server.input_transcription.text:
                print(f"[user] {server.input_transcription.text}")
            if server.output_transcription and server.output_transcription.text:
                print(server.output_transcription.text, end="", flush=True)
            if server.model_turn:
                for part in server.model_turn.parts:
                    if part.inline_data is not None:
                        # part.inline_data.data is base64 PCM16 24 kHz — play it
                        pass
            # session_resumption_update / go_away arrive on the same stream:
            # store the latest resumable handle and reconnect on GoAway.


if __name__ == "__main__":
    asyncio.run(main())
Example output · illustrative2 lines
[user] where is my order A-1042?
Your order A-1042 shipped and should arrive Friday.

The raw-WebSocket equivalent exists (BidiGenerateContentSetup as the first JSON message on wss://generativelanguage.googleapis.com/ws/...BidiGenerateContent?key=...), and the SDK is the better choice unless you need the wire format for a non-Python client. Note the two Gemini-specific production requirements this example gestures at: resumption (store the sessionResumptionUpdate handle, reconnect with it on GoAway) and compression (without it, audio-only sessions die at ~15 minutes and the WebSocket itself at ~10).

8.3 What the two have in common — and don't#

Concern OpenAI Realtime Gemini Live
Connect WS URL + Authorization header WS URL + ?key= or ?access_token= (ephemeral)
First message session.created arrives automatically; you send session.update You send BidiGenerateContentSetup; server replies setupComplete
Audio out response.output_audio.delta (base64) per response serverContent.modelTurn.parts[].inlineData (base64)
Transcripts input_audio_transcription.completed, output_audio_transcript.delta input_transcription, output_transcription on serverContent
Tools function_call items + function_call_output + response.create toolCall / toolResponse messages (NON_BLOCKING on newer models)
Interruption Automatic + conversation.item.truncate (WS) Automatic barge-in; interruption events on the stream
Session cap 60 minutes ~15 min audio-only / ~10 min connection without resumption+compression
Long-session strategy token_limits, context is conversation items context_window_compression + session_resumption

Part 9: Full example 2 — browser client with WebRTC and an ephemeral token#

Deep-dive

Browsers should never hold your API key. The standard pattern: your server mints a short-lived credential, the browser connects to the realtime API directly over WebRTC (which handles echo cancellation, jitter and NAT traversal for free), and JSON events flow on a data channel.

9.1 The token-minting endpoint (FastAPI)#

python
# voice_server.py — mints an OpenAI Realtime client secret for the browser.
# Run: uvicorn voice_server:app --port 8000   (needs httpx + fastapi)
import hashlib
import os

import httpx
from dotenv import load_dotenv
from fastapi import Depends, FastAPI, Header, HTTPException
from fastapi.responses import FileResponse

load_dotenv()
app = FastAPI()


@app.get("/")
async def index():
    """Serve the browser page from 9.2 (save it as index.html next to this file)."""
    return FileResponse("index.html")


async def verified_user_id(authorization: str = Header(...)) -> str:
    """STUB for your auth layer: verify the bearer token (JWT/session) and
    return the authenticated user id. In production this is where auth
    happens — the client never supplies its own identity."""
    if not authorization.startswith("Bearer "):
        raise HTTPException(401, "missing auth")
    return "user-demo"  # illustrative: replace with your real lookup


@app.post("/api/realtime/session")
async def create_session(user_id: str = Depends(verified_user_id)):
    # Stable, privacy-preserving per-user id for abuse tracking.
    # hashlib, NOT hash(): hash() is salted per process and changes on restart.
    safety_id = "user-" + hashlib.sha256(user_id.encode()).hexdigest()[:24]

    # Ask OpenAI for an ephemeral client secret bound to this session config.
    async with httpx.AsyncClient(timeout=15) as client:
        r = await client.post(
            "https://api.openai.com/v1/realtime/client_secrets",
            headers={
                "Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
                "OpenAI-Safety-Identifier": safety_id,
                "Content-Type": "application/json",
            },
            json={
                # Optional: "expires_after": {"anchor": "created_at", "seconds": 300}
                # (default 600 s, range 10-7200; the secret can mint multiple
                # sessions until it expires — keep TTL short).
                "session": {
                    "type": "realtime",
                    "model": "gpt-realtime-2.1",
                    "output_modalities": ["audio"],
                    "audio": {
                        "output": {"voice": "marin"},
                        "input": {"turn_detection": {"type": "semantic_vad"}},
                    },
                    "instructions": "You are a concise voice assistant.",
                }
            },
        )
    if r.status_code != 200:
        raise HTTPException(502, f"realtime session failed: {r.status_code}")
    data = r.json()
    # The API returns the secret TOP-LEVEL: {"value": "ek_…", "expires_at": …,
    # "session": {...}} — there is no "client_secret" object in the response.
    # Return ONLY the ephemeral secret — never your real API key.
    return {"client_secret": data["value"], "expires_at": data["expires_at"]}

The response's value is a short-lived token (ek_…, default 10-minute TTL, reusable for multiple sessions until it expires — treat it as a bearer credential, not single-use). Your real key never leaves the server.

9.2 The browser page (the one non-Python listing, as in 03.3)#

Save this as index.html next to voice_server.py and open http://localhost:8000/. It is the ephemeral-token flow: the page asks your server for a client secret, creates an SDP offer, and posts it straight to OpenAI's /v1/realtime/calls with the secret as its bearer token; events then flow on a WebRTC data channel labelled oai-events. About 60 lines of HTML/JS — the one exception to "Python only", matching the convention in 03.3 Part 11:

html
<!doctype html><meta charset="utf-8"><title>Voice agent</title>
<button id="start">Start call</button> <button id="stop">End</button>
<pre id="log"></pre>
<script>
const log = m => document.getElementById("log").textContent += m + "\n";
let pc, dc, audioEl;

start.onclick = async () => {
  // 1. Mic permission + local audio track
  const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
  pc = new RTCPeerConnection();
  audioEl = document.createElement("audio");
  audioEl.autoplay = true;
  pc.ontrack = e => audioEl.srcObject = e.streams[0];   // model's voice plays here
  pc.addTrack(stream.getTracks()[0]);

  // 2. Data channel for JSON events — create BEFORE the offer
  dc = pc.createDataChannel("oai-events");
  dc.onopen = () => log("session ready");
  dc.onmessage = ev => {
    const e = JSON.parse(ev.data);
    if (e.type === "input_audio_buffer.speech_started") log("…user speaking");
    if (e.type === "response.output_audio_transcript.delta")
      document.getElementById("log").textContent += e.delta;  // live captions
    if (e.type === "response.done") log("\n— turn done —");
    if (e.type === "error") log("ERROR: " + e.error.message);
  };

  // 3. Ask YOUR server for an ephemeral client secret (it holds the real API key)
  const tokenRes = await fetch("/api/realtime/session", {
    method: "POST",
    headers: { Authorization: "Bearer demo-token" },   // demo only: send your real session/JWT here
  });
  const { client_secret } = await tokenRes.json();

  // 4. SDP offer → OpenAI /v1/realtime/calls (authenticated with the secret) → SDP answer
  await pc.setLocalDescription(await pc.createOffer());
  // wait for ICE gathering (simplified: real code waits for iceGatheringState === "complete")
  await new Promise(r => setTimeout(r, 500));
  const res = await fetch("https://api.openai.com/v1/realtime/calls", {
    method: "POST",
    headers: { Authorization: "Bearer " + client_secret, "Content-Type": "application/sdp" },
    body: pc.localDescription.sdp,
  });
  await pc.setRemoteDescription({ type: "answer", sdp: await res.text() });  // the SDP answer is plain text
};

stop.onclick = () => { dc?.close(); pc?.close(); audioEl && (audioEl.srcObject = null); };
</script>

Why WebRTC and not WebSocket in the browser: WebRTC gives you the microphone capture, echo cancellation, jitter buffers, NAT traversal and hardware codecs that a hand-rolled WebSocket audio pipeline would have to rebuild — and it degrades gracefully on bad networks. Reserve WebSocket for server-to-server (telephony bridges, bots, test harnesses) where you control both ends.


Part 10: Full example 3 — the cascaded pipeline agent#

Deep-dive

When the brain isn't a realtime model — Claude, a self-hosted LLM, or any text model — you build the cascade: streaming STT → LLM tool loop → streaming TTS. This part shows it twice: once with Pipecat (the framework path), once from scratch with asyncio queues and scripted fakes so the control logic runs with zero API calls.

10.1 The shape of the problem#

flowchart LR
    MIC["Mic audio"] --> STT["Streaming STT"]
    STT -- "partial → final transcript" --> BRIDGE["Turn manager:<br/>endpointing, barge-in,<br/>played-vs-generated tracking"]
    BRIDGE --> LLM["LLM agent loop<br/>(tools, RAG, approvals)"]
    LLM -- "text deltas" --> TTS["Streaming TTS"]
    TTS --> PLAY["Speaker"]
    BRIDGE -. "user barges in:<br/>cancel TTS, truncate context" .-> LLM

The hard parts aren't the vendor calls — they're the glue: knowing when the user finished a turn, cancelling speech mid-word, and keeping the LLM's context honest about what the user actually heard.

10.2 With Pipecat (framework path)#

Pipecat (BSD-2, Python, by Daily) models the pipeline as a chain of processors passing frames (audio, text, control). You swap vendors by changing one service. The sample below targets pipecat-ai 1.15.0 (released 29 October 2026, Python 3.11 or newer) and follows the structure of the project's own examples/getting-started/06-voice-agent.py at that tag. It is illustrative, because it needs three vendor keys, but its import paths, constructors, Settings objects and install extras match the v1.15.0 tag on GitHub (re-checked on 12 November 2026; 1.15.0 is still the latest release). Pipecat is a young, fast-moving framework, so a plain install may give you a newer release than 1.15.0: if an import path or constructor has changed, compare against the release notes for the version you installed:

bash
# the extras pull in only the vendors and tooling you use
uv add "pipecat-ai[openai,deepgram,elevenlabs,silero,webrtc,runner]" python-dotenv
python
# pipecat_agent.py — cascaded voice agent (Pipecat 1.15.0), illustrative.
# Needs OPENAI_API_KEY, DEEPGRAM_API_KEY, ELEVENLABS_API_KEY in .env, then:
#   uv run python pipecat_agent.py -t webrtc   # local WebRTC test client on http://localhost:7860
import os

from dotenv import load_dotenv

from pipecat.audio.vad.silero import SileroVADAnalyzer
from pipecat.frames.frames import LLMRunFrame
from pipecat.pipeline.pipeline import Pipeline
from pipecat.pipeline.worker import PipelineParams, PipelineWorker
from pipecat.processors.aggregators.llm_context import LLMContext
from pipecat.processors.aggregators.llm_response_universal import (
    LLMContextAggregatorPair,
    LLMUserAggregatorParams,
)
from pipecat.runner.types import RunnerArguments
from pipecat.runner.utils import create_transport
from pipecat.services.deepgram.stt import DeepgramSTTService
from pipecat.services.elevenlabs.tts import ElevenLabsTTSService
from pipecat.services.openai.llm import OpenAILLMService
from pipecat.transports.base_transport import BaseTransport, TransportParams
from pipecat.workers.runner import WorkerRunner

load_dotenv(override=True)

# One params factory per transport the runner can select (webrtc is the local default).
transport_params = {
    "webrtc": lambda: TransportParams(audio_in_enabled=True, audio_out_enabled=True),
}


async def run_bot(transport: BaseTransport, runner_args: RunnerArguments) -> None:
    stt = DeepgramSTTService(api_key=os.environ["DEEPGRAM_API_KEY"])      # streaming STT
    llm = OpenAILLMService(                                              # your text brain (+ tools)
        api_key=os.environ["OPENAI_API_KEY"],
        settings=OpenAILLMService.Settings(
            model="gpt-6-luna",
            system_instruction="You are a concise voice assistant. Keep answers under two sentences.",
        ),
    )
    tts = ElevenLabsTTSService(                                          # streaming TTS
        api_key=os.environ["ELEVENLABS_API_KEY"],
        settings=ElevenLabsTTSService.Settings(voice="<your-voice-id>"),
    )
    # llm.register_function("lookup_order", lookup_order)  # your tools here

    context = LLMContext()
    user_aggregator, assistant_aggregator = LLMContextAggregatorPair(
        context,
        user_params=LLMUserAggregatorParams(vad_analyzer=SileroVADAnalyzer()),  # turn-taking input
    )

    pipeline = Pipeline([
        transport.input(),    # mic audio in
        stt,                  # -> transcript frames
        user_aggregator,      # -> user turn added to the context (VAD decides when it ends)
        llm,                  # -> text deltas (with tool loop)
        tts,                  # -> audio frames
        transport.output(),   # -> speaker / client
        assistant_aggregator, # -> what the bot actually said goes back into the context
    ])
    worker = PipelineWorker(
        pipeline,
        params=PipelineParams(enable_metrics=True, enable_usage_metrics=True),  # per-turn latency
    )
    runner = WorkerRunner(handle_sigint=runner_args.handle_sigint)
    await runner.add_workers(worker)

    @transport.event_handler("on_client_connected")
    async def on_client_connected(transport, client):
        context.add_message({"role": "developer", "content": "Greet the user briefly."})
        await worker.queue_frames([LLMRunFrame()])      # kick off the first reply

    @transport.event_handler("on_client_disconnected")
    async def on_client_disconnected(transport, client):
        await runner.cancel()

    await runner.run()


async def bot(runner_args: RunnerArguments) -> None:
    """Entry point the Pipecat runner (and Pipecat Cloud) calls."""
    transport = await create_transport(runner_args, transport_params)
    await run_bot(transport, runner_args)


if __name__ == "__main__":
    from pipecat.runner.run import main

    main()

What changed since older tutorials (the traps when you copy a 2025 snippet): PipelineTask and PipelineRunner are deprecated aliases since 1.3.0 (scheduled for removal in 2.0.0) in favour of PipelineWorker and WorkerRunner; the pipecat.pipeline.task and pipecat.pipeline.runner modules only re-export them. Vendor services now take a settings=Service.Settings(...) object (model, voice and system instruction live there; the older voice_id argument is marked deprecated). The conversation history lives in an LLMContext that you wire in through the LLMContextAggregatorPair (a user aggregator before the LLM and an assistant aggregator after the transport output), not by passing a context to the task. And the transport is normally created by the runner (create_transport), not constructed by hand.

Pipecat gives you VAD/turn-taking (SileroVADAnalyzer plus the VADController and the smart-turn models under pipecat.audio), interruption handling, metrics and telephony transports as library pieces — the same job LiveKit Agents does with a different architecture (LiveKit: rooms + WebRTC SFU + AgentSession; Pipecat: frame pipelines). Both are covered comparatively in Part 7.

10.3 From scratch: the control logic that actually matters#

Frameworks hide the interesting part. This pure-local version — asyncio queues, scripted fake STT/LLM/TTS — runs with no API keys and no audio hardware, and teaches you the state machine every cascade needs:

python
# cascade_sim.py — a cascaded voice pipeline with scripted fakes (stdlib only).
# Simulates: user speech → STT transcript → LLM reply → TTS audio, with barge-in.
# Run: python cascade_sim.py
import asyncio


class FakeSTT:
    """Yields 'final' transcripts like a streaming STT would."""
    def __init__(self, lines):
        self.lines = lines

    async def listen(self):
        for line in self.lines:
            await asyncio.sleep(0.05)          # pretend network latency
            yield {"type": "final", "text": line}


class FakeLLM:
    """Streams text deltas like an LLM; 'looks up' an order on a keyword.

    `generated` records EVERY delta the model produced for the current
    respond() call — generation runs to completion even when playback is
    interrupted, exactly like a real LLM stream you can't un-generate."""

    MS_PER_DELTA = 30   # each word-delta ≈ 30 ms of fake TTS audio

    def __init__(self):
        self.generated = []

    async def respond(self, user_text: str):
        self.generated = []
        if "order" in user_text:
            reply = "Your order A-1042 shipped and arrives Friday."
        else:
            reply = "I can help with orders, returns, or store hours."
        for word in reply.split():
            delta = word + " "
            self.generated.append(delta)     # record BEFORE yielding
            await asyncio.sleep(0.03)        # pretend model latency
            yield delta


class FakeTTS:
    """'Speaks' text deltas as timed audio the player can interrupt.

    speak() returns the list of deltas actually played — the 'heard' text.
    Whatever is still queued when `cancel` fires is dropped, like a real
    audio player flushing its buffer on barge-in."""

    async def speak(self, delta_queue: asyncio.Queue, cancel: asyncio.Event):
        played = []
        while True:
            delta = await delta_queue.get()
            if delta is None:                # end-of-generation sentinel
                break
            if cancel.is_set():
                break                        # barge-in: drop unplayed audio
            await asyncio.sleep(0.03)        # pretend audio playback time
            played.append(delta)
        return played


async def voice_session():
    stt, llm, tts = (
        FakeSTT(["where is my order A-1042?", "actually cancel that"]),
        FakeLLM(),
        FakeTTS(),
    )

    async for transcript in stt.listen():
        # --- Generation is its OWN task: it runs to completion even if the
        #     user interrupts playback. This mirrors reality — you cannot
        #     un-generate tokens; you can only stop playing them. ---
        deltas = asyncio.Queue()

        async def produce():
            async for delta in llm.respond(transcript["text"]):
                deltas.put_nowait(delta)
            deltas.put_nowait(None)          # signal end of generation

        producer = asyncio.create_task(produce())

        # User barges in mid-reply -> cancel playback only.
        tts_cancel = asyncio.Event()

        async def maybe_barge_in():
            await asyncio.sleep(0.12)         # user starts talking 120ms in
            tts_cancel.set()
        barge = asyncio.create_task(maybe_barge_in())

        played_deltas = await tts.speak(deltas, tts_cancel)
        barge.cancel()
        await producer                       # let generation finish anyway

        # --- Bookkeeping: generated vs heard ---
        full_reply = "".join(llm.generated)
        heard = "".join(played_deltas)
        played_ms = len(played_deltas) * FakeLLM.MS_PER_DELTA
        print(f"[turn] user: {transcript['text']!r}")
        print(f"       model generated: {full_reply!r}")
        print(f"       user actually heard (~{played_ms}ms): {heard!r}")


asyncio.run(voice_session())

Run it (python cascade_sim.py — stdlib only). The fakes are scripted, so this output is real on an idle machine (the timings themselves are simulated). The 120 ms barge-in and the 30 ms playback steps land close together, so under heavy load you may see one word more or less:

Output6 lines
[turn] user: 'where is my order A-1042?'
       model generated: 'Your order A-1042 shipped and arrives Friday. '
       user actually heard (~90ms): 'Your order A-1042 '
[turn] user: 'actually cancel that'
       model generated: 'I can help with orders, returns, or store hours. '
       user actually heard (~90ms): 'I can help '

The lesson the simulation teaches: the LLM's context must record heard, not full_reply. In a real cascade you append the truncated assistant turn to the message history — exactly what OpenAI's conversation.item.truncate does automatically on the realtime API. Get this wrong and the model insists it already said the part the user never heard — the single most common voice-agent context bug.

10.4 Production notes the fakes omit#

  • Streaming STT emits partial transcripts long before finals; your turn manager waits for a final + endpointing silence before calling the LLM (semantic endpointing beats fixed silence — 09.6).
  • Streaming TTS starts speaking the first sentence while the LLM is still generating the second — sentence-level chunking cuts time-to-first-audio dramatically (09.5 covers the sentence streamer).
  • Barge-in must cancel TTS and the in-flight LLM response, then truncate context — three coordinated cancellations, not one.
  • Latency budget: aim for <800ms turn latency end-to-end; each stage's contribution is measurable (13.2).

Part 11: Tools, retrieval and humans inside a voice loop#

11.1 Why voice tools are different#

A text agent can take 8 seconds to call a tool and the user watches a spinner. A voice caller experiences every millisecond as dead air. Three rules follow:

  1. Filler phrases buy time honestly. "Let me check that for you" is fine if the tool actually takes noticeable time — and it resets the caller's patience clock. Don't filler on fast tools; it sounds robotic.
  2. Async tools keep the conversation alive. GPT-Live's delegated backend can run tools while the voice model keeps talking. On Realtime/Gemini Live, a slow function call blocks the turn unless you design around it: return a "pending" result quickly and follow up, or use out-of-band responses.
  3. Irreversible actions need spoken confirmation. "Should I go ahead and cancel order A-1042?" — wait for an explicit yes. Voice confirmations are weaker than typed ones (no record of what was shown), so read back the exact action and key details.

11.2 Tools in a voice loop: filler, async and approval#

The pattern that works across providers:

python
# voice_tool_policy.py — the policy layer between model and your tools.
# Provider-agnostic: works with Realtime function calls, Gemini toolCall,
# or a cascade's LLM tool loop.
import asyncio, time

SLOW_TOOL_THRESHOLD_S = 1.5   # above this, the caller hears a filler first


async def run_voice_tool(name, args, execute, speak_filler):
    """Run a tool; if it's slow, speak a filler first. Returns the result.

    NOTE: `execute` may raise — callers must catch tool exceptions and
    convert them into a spoken error ("sorry, the order lookup failed,
    want me to try again?") rather than letting them kill the session."""
    start = time.monotonic()
    task = asyncio.create_task(execute(name, args))

    done, _ = await asyncio.wait({task}, timeout=SLOW_TOOL_THRESHOLD_S)
    if not done:
        await speak_filler(name)          # "One moment, checking your order…"
        return await task                 # still running: keep the turn alive
    return task.result()


async def confirm_before_execute(name, args, needs_confirm, speak_confirm, execute):
    """Two-phase tool: confirm in speech, then execute.

    `speak_confirm` should return False if the caller hangs up or the
    confirmation times out — treat anything but an explicit yes as a no."""
    if needs_confirm(name, args):
        ok = await speak_confirm(name, args)   # "…cancel order A-1042? Say yes to confirm."
        if not ok:
            return {"status": "cancelled_by_user", "reason": "no confirmation"}
    return await execute(name, args)

On the Realtime API specifically: when a function_call arrives, you can choose to (a) execute and return function_call_output then response.create (the model speaks the result), or (b) for long work, return a quick "I'm checking" result, keep the session alive, and inject the real result later via conversation.item.create + response.create. Option (b) is how you fake async on a synchronous tool API — but it complicates context, so prefer genuinely async architectures (GPT-Live delegation, cascade with background tasks) for real long-running work.

11.3 Retrieval (RAG) in voice agents#

Voice RAG has a brutal latency budget: the caller is waiting silently. Rules:

  • Pre-fetch on intent, not on question. When the user says "order" or "return", kick off the retrieval in parallel with the LLM turn — don't wait for the full query.
  • Cache aggressively. FAQ answers, store hours, policies — precompute and cache; a cache hit is ~0ms vs ~800ms for retrieval + generation.
  • Speak the answer, not the sources. "Your order ships Friday" not "According to document chunk 7…". Keep citations for the text channel or a follow-up "want me to text you the link?".
  • Bound the context. RAG results are long; in a voice session they flood the audio-token-priced context. Retrieve top-3, summarise to one spoken sentence, keep the full text for a follow-up channel.
  • Link: retrieval strategy itself is Module 07; this lesson only covers the voice-specific latency constraints.

11.4 Human handoff and IVR replacement#

Two patterns:

  • Warm transfer: the agent summarises the call so far (it has the transcript) and transfers to a human agent with context — "I've got Sarah on the line, she's asking about order A-1042 which shipped Friday; she also wants to change the delivery address." This is where voice agents beat IVR: the human doesn't start from zero. On telephony this is a first-class API call, not a metaphor: GPT-Live SIP exposes POST /v1/live/sessions/{id}/refer (the destination becomes the SIP Refer-To header) and /hangup, and the Realtime API's SIP surface has the same /v1/realtime/calls/{id}/refer + /hangup pair (4.5). Your app decides when to refer — the model shouldn't be able to transfer calls on its own say-so; gate it behind the same confirmation policy as any irreversible tool.
  • Callback booking: when no human is available, the agent books a callback slot — a tool call (book_callback(time, topic, phone)) with spoken confirmation. This is the highest-value IVR replacement: capture intent + contact + context, guarantee a human follow-up.

IVR replacement works when the agent handles the structured part (auth, lookup, routing, FAQ) and hands off the judgement part (complaints, edge cases, sales) — with context intact. Trying to make the agent handle everything is where voice agents fail in production.


Part 12: Conversation design for voice#

Deep-dive

Voice is a different medium from text. The prompt blueprint below is distilled from OpenAI's voice-prompting guide and production practice; adapt per provider.

12.1 The voice-agent system prompt blueprint#

text
# Role and Objective
You are the phone assistant for <business>. Your job: <one sentence>.

# Personality and Tone
Warm, concise, professional. Speak in short sentences. No markdown, no lists
read aloud, no URLs spoken character-by-character.

# Language
Respond in the caller's language. If unsure, ask once, then default to English.

# Reasoning
Answer simple questions directly. For multi-step requests, say what you're
about to do, then do it. If audio is unclear, ask for clarification — never guess.

# Message Channels
Voice only. Keep replies under 25 words unless the caller asks for detail.

# Preambles
Use a short filler ("One moment…") ONLY before a tool call that takes >1s.
Never filler on instant answers — it sounds robotic.

# Tools
<tool list with when-to-use notes>
For irreversible actions (cancel, refund, delete), ALWAYS read back the exact
action and key details and wait for an explicit "yes".

# Entity Capture
Read back order numbers, phone numbers, emails, and names — digit by digit or
letter by letter — and confirm before acting.

# Unclear Audio
If you can't understand: "Sorry, I didn't catch that — could you say it again?"
After two failures, offer to take a message or transfer.

# Long Context Behavior
If the call exceeds ~10 minutes, briefly recap where you are.

# Escalation
Offer a human when: caller asks twice, is frustrated, the request is outside
your tools, or it's a complaint/edge case. Book a callback with topic + number.
Situation Prompt line that works
Numbers "Read back numbers digit by digit: 'A-1042' is 'A, one, zero, four, two.'"
Confirmation "Before cancelling, say: 'I'll cancel order A-1042 — say yes to confirm or no to keep it.'"
Barge-in friendly "If the caller interrupts, stop immediately and address their new point — don't finish your sentence."
Silence "If the caller is silent for 5 seconds, ask 'Are you still there?' once, then offer help."
Emotion "If the caller sounds frustrated, acknowledge it first: 'I understand this is frustrating.'"
Handoff "When transferring, summarise: the issue, what you've tried, and what the caller needs."
Multilingual "Mirror the caller's language and accent level; switch only if they switch first."

12.3 Disfluencies, interruptions and recovery#

Real callers say "um", restart sentences, change their mind mid-request ("actually, cancel that — no wait, just change the address"). Your prompt must handle this: the realtime models are good at it natively; cascades need the LLM to see the full transcript including abandoned starts (don't pre-filter disfluencies — they're signal). The failure mode is the agent answering the first interpretation after the caller corrected to the second.

12.4 Multilingual and accents#

  • Gemini Live: 99 languages, code-switching mid-call works.
  • OpenAI Realtime: strong multilingual; test your specific language pairs — quality varies more than English.
  • Cascades: STT language detection + TTS multilingual voices; the weak link is usually STT on accented speech — bias vocabulary, keep sentences short.

Part 13: Reliability and operations#

Deep-dive

13.1 Session lifecycle and limits#

Provider Max session Connection lifetime Reconnection story
OpenAI Realtime 60 minutes WS: until closed; WebRTC: ICE-managed No session resume — reconnect = new session, replay context from your logs
OpenAI GPT-Live Per-minute billing, no hard cap documented WS/WebRTC managed Sideband can observe; session forking continues a stored session on a new connection; reconnect per transport rules
Gemini Live ~15 min audio-only / ~2 min audio+video without compression ~10 min WebSocket sessionResumption + GoAway — designed for reconnect

Design rule: treat every voice session as disposable. Log enough (transcripts, tool calls, session ids) to reconstruct or hand off, and implement reconnect/resume per provider — Gemini's is the only first-class one.

13.2 Latency budget and observability#

The metric that matters is time-to-first-audio (caller stops talking → hears a response) and per-turn latency. Budget roughly:

Stage Typical
Endpointing/silence detection 300–800ms (semantic VAD faster than silence-based)
STT final transcript (cascade) 200–600ms
LLM first token 300–1500ms (reasoning models slower)
TTS first audio 200–500ms
Network + jitter buffer 50–200ms
Total cascade ~1–3s typical; realtime models ~500–900ms

(Orders of magnitude — measure your own; they depend on provider, region, model and load.)

Log per turn: session id, turn id, endpointing delay, STT confidence, LLM time-to-first-token, TTS time-to-first-audio, tool calls + latencies, interruption events, truncation events, final outcome. On GPT-Live, session.usage.updated gives you cumulative voice seconds live and session.closed the final figure — your cost dashboard without extra instrumentation. Store audio only with consent (Part 14); on GPT-Live the recording itself is a session field (store: true) retrievable afterwards via GET /v1/live/sessions/{id}/content as stereo WAV (4.5) — decide deliberately whether you want the provider to hold call audio at all.

13.3 Cost per minute modelling#

python
# voice_cost.py — per-minute cost model (stdlib only). Prices as of Nov 2026.
# Run: python voice_cost.py

def openai_realtime_cost_per_min(
    user_speech_s=30, agent_speech_s=30, text_in_tok=2000, text_out_tok=1000,
    tool_calls=2, tool_tok_per_call=800, text_in_cached_frac=0.8,
    price_audio_in=32.0, price_audio_out=64.0,
    price_text_in=4.0, price_text_out=24.0, price_cached_in=0.4,
):
    """OpenAI Realtime (gpt-realtime-2.1 list prices).

    Audio bills in tokens: 1 per 100 ms of input, 1 per 50 ms of output
    (from the Realtime cost guide). The growing conversation prefix is
    prompt-cached, so most text input bills at the cached rate — model
    that with text_in_cached_frac rather than assuming all-or-nothing.
    Each tool call adds a function_call + function_call_output ≈ a few
    hundred text tokens, billed at the text-input price (tool_tok_per_call
    is an estimate, tune it)."""
    audio_in_tok = user_speech_s * 10      # 10 tokens per second of input audio
    audio_out_tok = agent_speech_s * 20    # 20 tokens per second of output audio
    text_in_rate = (text_in_cached_frac * price_cached_in
                    + (1 - text_in_cached_frac) * price_text_in)
    usd = (audio_in_tok * price_audio_in + audio_out_tok * price_audio_out
           + text_in_tok * text_in_rate + text_out_tok * price_text_out
           + tool_calls * tool_tok_per_call * price_text_in) / 1e6
    return usd

def gemini_live_cost_per_min(
    user_speech_s=30, agent_speech_s=30,
    in_per_min=0.005, out_per_min=0.018,
):
    """Gemini Live: billed per token ($3/$12 per 1M audio tokens); Google's
    per-minute figures are the standard-tier equivalents (~$0.005/min in,
    ~$0.018/min out). Text and context re-billing are left out here."""
    return user_speech_s/60*in_per_min + agent_speech_s/60*out_per_min

def gpt_live_cost_per_min(voice_s=60, backend_usd=0.02):
    """GPT-Live: $0.05/min voice (billed per second) + backend tokens."""
    return voice_s/60*0.05 + backend_usd

def cascade_cost_per_min(
    stt_per_min=0.006, tts_per_1m_chars=30.0, llm_usd_per_min=0.01,
    chars_spoken_per_min=600,
):
    """Cascade: STT $/min + TTS $/1M chars + LLM $/min.

    tts_per_1m_chars: neural TTS list prices are typically in the
    $10-40 per million characters range — check your provider's page."""
    return stt_per_min + chars_spoken_per_min/1e6*tts_per_1m_chars + llm_usd_per_min

print(f"OpenAI Realtime  (1min two-way): ${openai_realtime_cost_per_min():.3f}")
print(f"Gemini Live     (1min two-way): ${gemini_live_cost_per_min():.3f}")
print(f"GPT-Live        (1min + $0.02 backend): ${gpt_live_cost_per_min():.3f}")
print(f"Cascade         (1min, typical): ${cascade_cost_per_min():.3f}")
Output4 lines
OpenAI Realtime  (1min two-way): $0.081
Gemini Live     (1min two-way): $0.011
GPT-Live        (1min + $0.02 backend): $0.070
Cascade         (1min, typical): $0.034

The honest takeaway: per-minute sticker prices mislead. OpenAI Realtime's token model charges for context resent every turn (though caching discounts it); Gemini's per-minute audio rate looks cheapest but long sessions accumulate input tokens; GPT-Live's $0.05/min is simple but adds backend costs; cascades can be cheapest if you pick efficient STT/TTS and a cheap text model — or most expensive if you pick premium voices. Build the calculator with your prices and your call profile before choosing.

13.4 Testing voice agents#

  • Scripted audio fixtures: record real calls (with consent), replay through your pipeline, assert on transcripts/tool calls/outcomes — regression suites for voice.
  • Simulated callers: an LLM plays the user (text in → TTS → your agent), giving you automated multi-turn tests; frameworks and OpenAI's eval cookbook cover this.
  • Metrics: task success rate, time-to-first-audio p50/p95, interruption handling rate, ASR confidence, tool-call accuracy, caller satisfaction (post-call survey).
  • Crawl/Walk/Run (from OpenAI's voice-agent guide): synthetic single-turn → recorded single-turn → simulated multi-turn caller, increasing realism in stages.

13.5 Fallbacks and abuse prevention#

  • Fallbacks: provider outage → degrade to text chat or cascade; STT failure → offer keypad/DTMF fallback on phone; model failure → transfer to human. Design the degraded path, don't just retry.
  • Abuse: authenticate callers before exposing tools (never let an unauthenticated caller hit order-lookup or refund tools); rate-limit sessions per user; watch for prompt injection through speech (a caller saying "ignore your instructions" — same defences as text, Module 12); fraud patterns (voice deepfakes authorising transactions — require step-up auth for sensitive actions).

Deep-dive

Voice is the most sensitive modality you can ship: it captures biometric data (voiceprints), happens in private spaces, and records what people say — often including things they didn't intend to say to a machine.

  • Recording consent laws vary by jurisdiction — some require all-party consent, some one-party. You're responsible for compliance; this is awareness, not legal advice. When in doubt, announce "this call may be recorded for quality" and get explicit consent before recording.
  • Provider retention: OpenAI and Google retain API data per their terms (check current retention/ZDR policies — 02.9 covers data privacy generally); self-hosted frameworks change what leaves your infra. On GPT-Live specifically, call audio is not stored by default — the store session field (default false) is what enables the downloadable stereo-WAV recording and session forking (4.5); set it only when consent and your retention policy allow, and note Zero Data Retention organisations can't use it at all.
  • Store less: keep transcripts for debugging, delete audio quickly, redact PII in logs, give users a deletion path.

14.2 Payments and sensitive data#

14.3 Healthcare and high-stakes caution#

Voice agents in health, legal or financial contexts raise the stakes: misheard medication names, wrong dosages read aloud, financial advice from a hallucinating model. Add human-in-the-loop for anything irreversible, disclaimers where appropriate, and extra evaluation before production.


Failure Symptom Cause Fix
Agent talks over user Constant interruptions VAD too sensitive / interrupt_response on Tune silence_duration_ms, eagerness: low, or disable auto-interrupt
Agent answers wrong interpretation Replies to abandoned request Context kept the full untruncated turn Truncate to what user heard (WS) / framework handles it
Dead air on tool call 3s silence mid-call Synchronous tool blocks the turn Filler phrase, async tool, or delegated backend
"I already told you" Model repeats itself Context includes unheard audio Truncation bookkeeping
Session dies at 10 min Gemini Live disconnects WS lifetime / no resumption Implement sessionResumption + GoAway
Audio sounds chipmunked Wrong sample rate 16k vs 24k mismatch, or wrong PCM width Match audio.format.rate; resample before send
Tool called with wrong args "order_id" gets "my order" Entity capture failure Read-back confirmation, constrained schemas, entity-capture prompt section
Costs explode Bill 10× estimate Context resent every turn + no caching awareness token_limits, stable prefix, monitor rate_limits.updated/usage
Caller hears themselves Echo Speakerphone + no AEC WebRTC (has AEC) or headset; never raw WS audio to speakers
Agent can't hear soft speech Missed turns VAD threshold too high Lower threshold, check mic gain, prefix_padding_ms

Common misconceptions#

Misconception Reality
"Realtime API and GPT-Live are the same thing." Different architectures: one model does everything vs voice model + delegated backend. Different endpoints (/v1/realtime vs /v1/live), event names, and pricing models.
"You need WebRTC for everything." WebRTC is best for browsers; WebSocket is right for server-to-server (telephony, bots, tests). SIP for phone calls.
"Put your API key in the browser with a realtime API." Never. Mint an ephemeral client secret server-side; the real key never leaves your backend.
"VAD handles interruptions perfectly." It handles detection; you still must stop playback and truncate context on WebSocket clients. On WebRTC/SIP the server truncates audio automatically.
"Claude can't do voice at all." Claude can't do realtime audio — but it's excellent as the text brain in a cascade. "No realtime API" ≠ "no voice".
"OpenRouter gives you realtime voice." It brokers audio file I/O and text LLMs, not stateful realtime audio sessions. Use it for the LLM stage of a cascade.
"A voice agent is just a chatbot with audio." The medium changes everything: turn-taking, interruptions, entity capture, latency budgets, consent. Text-agent assumptions break.
"Per-minute pricing is simpler so it's cheaper." Token-priced realtime can be cheaper or pricier depending on call length and context size; model it with your real call profile.
"Gemini Live sessions just work forever." ~15min audio-only / ~10min connection caps without compression + resumption. Design for reconnect.

Key takeaways#

  • Three architectures: speech-to-speech realtime model (OpenAI Realtime, Gemini Live), full-duplex voice + delegated backend (GPT-Live), cascaded STT→LLM→TTS (everything else, incl. Claude). Choose by latency needs, existing brain, and control requirements.
  • OpenAI Realtime is GA: gpt-realtime-2.1, WebRTC/WebSocket/SIP, ephemeral client secrets, session.update with output_modalities, semantic/server VAD, function + MCP tools, conversation.item.truncate for interruptions, 60-min cap, token pricing.
  • GPT-Live (gpt-live-1) splits voice (conversation) from backend (reasoning/tools) via delegation; $0.05/min voice + backend costs; sideband for server control; store enables forkable stored recordings; SIP refer/hangup for programmatic warm transfer.
  • Gemini Live is WebSocket-only with the richest feature set (99 languages, grounding, per-model affective dialog and async tools) but needs resumption + compression for calls past ~10-15 minutes.
  • Anthropic and OpenRouter have no realtime audio session — Claude and OpenRouter models work in cascades.
  • Frameworks (LiveKit Agents, Pipecat) give you transport + turn-taking; platforms (Vapi, Retell, Bland, ElevenLabs) sell the whole stack; pick by control vs speed vs compliance.
  • Voice changes the engineering: filler phrases for slow tools, spoken confirmations for irreversible actions, truncation bookkeeping, entity read-backs, per-turn latency metrics, consent-first recording.

Terms introduced in this lesson#

Term One-line definition
Voice agent A program that conducts a spoken conversation: hears audio, decides, speaks back, uses tools
Speech-to-speech model A model that takes audio input and produces audio output directly, without separate STT/TTS stages
Realtime API OpenAI's speech-to-speech API (/v1/realtime), GA as of Nov 2026
GPT-Live OpenAI's delegated voice architecture: voice model + separate reasoning backend (/v1/live)
Delegation GPT-Live's mechanism for handing reasoning/tool work from the voice model to a backend
Gemini Live API Google's bidirectional audio WebSocket API
Ephemeral client secret / token A short-lived credential minted server-side so browsers/clients can connect without your real API key
Session A stateful realtime connection with its own conversation, config and lifetime
Client event / server event JSON messages you send to / receive from a realtime API
session.update OpenAI Realtime client event that (re)configures the session live
output_modalities Realtime session field choosing audio-only or text-only output per response
VAD (voice activity detection) Detecting when the user starts/stops speaking; server_vad (silence) vs semantic_vad (meaning) on OpenAI
Endpointing Deciding a spoken turn has ended
Barge-in The user interrupting the agent mid-speech
Truncation Removing unheard assistant audio from the conversation so the model knows what was actually played
conversation.item.truncate OpenAI event marking how much of an interrupted audio item the user heard
Function calling (realtime) Model emits a function_call item; your code runs it and returns function_call_output
MCP tool A tool executed by the realtime API itself against a remote MCP server
input_audio_buffer.append WebSocket event streaming base64 PCM audio chunks to the model
response.create / response.done Client event to trigger a model turn / server event marking its completion
output_audio_buffer.clear Realtime event dropping unplayed output audio (and truncating context) on WebRTC/SIP
Noise reduction (near_field/far_field) Realtime input filter that cleans audio before VAD and the model
Input audio transcription Optional per-session transcription of what the user said, for captions/logs (off by default)
retention_ratio Realtime truncation setting controlling how much extra history is dropped per truncation
Sideband A second server-side WebSocket observing/controlling a GPT-Live session
Session fork GPT-Live feature continuing a stored session's conversation on a new connection
session.usage.updated GPT-Live event reporting cumulative voice duration (don't sum)
Context append events GPT-Live session.instructions/thinking/commentary.append for mid-call context
Session resumption Gemini Live's reconnect mechanism carrying conversation state across WebSocket drops
Context window compression Gemini Live's sliding-window summarisation extending session life
GoAway Gemini message warning a connection will close, with time left
Cascade / chained pipeline STT → LLM → TTS architecture where each stage is separate
Turn manager The glue logic in a cascade deciding when turns start/end and handling interruptions
Filler phrase A short spoken acknowledgement ("one moment") during slow tool calls
Warm transfer Handing a call to a human with AI-generated context summary
Twilio ConversationRelay Twilio's telephony bridge streaming transcripts to your app for STT→LLM→TTS
LiveKit Agents / Pipecat Open-source frameworks for building realtime voice agents
Vapi / Retell / Bland / ElevenLabs Agents Hosted voice-agent platforms

All terms are also collected in the glossary.


Exercises#

  1. Cost model: run voice_cost.py with your own call profile (short support calls vs long sales calls). Which architecture wins at 2-min vs 20-min average call length?
  2. Barge-in simulation: modify cascade_sim.py so the user barges in at 500ms instead of 120ms. How does the "heard" transcript change, and what does that teach you about truncation thresholds?
  3. Session config: write the session.update JSON for an OpenAI Realtime session with server_vad (threshold 0.7, silence 400ms), voice cedar, and two function tools. Identify which fields you could NOT change mid-session.
  4. Gemini resumption: sketch (in pseudocode or Python) the reconnect loop for Gemini Live: store the latest sessionResumptionUpdate handle, on GoAway reconnect with sessionResumption.handle, on WS drop resume within the 2-hour token window.
  5. Tool policy: extend voice_tool_policy.py so a refund tool always requires spoken confirmation but lookup_order never does. Write the needs_confirm function.
  6. Framework choice: for a clinic appointment-booking voice agent with HIPAA constraints, argue framework-vs-platform in 200 words citing the decision table.
  7. Prompt design: take the blueprint in 12.1 and rewrite the "Entity Capture" section for a pharmacy refilling prescriptions (drug names, dosages, DOB) — what read-back rules matter most?
  8. Latency budget: instrument cascade_sim.py to print simulated per-stage latencies and compute p50/p95 turn latency over 100 simulated turns.
Hints for the exercises
  1. With the prices in 13.3, the per-minute sticker prices rank as Gemini Live, cascade, GPT-Live, OpenAI Realtime for a short call. Re-run with higher text_in_tok (a long history) to see the token-priced realtime option grow with call length while GPT-Live and the cascade stay nearly linear.
  2. With the barge-in at 500 ms the whole reply is already played: both turns show heard equal to generated (about 210 ms and 270 ms), because the replies are shorter than the delay. Truncation matters only when the user interrupts before playback finishes; the bookkeeping must still record the played length either way.
  3. Set turn_detection to {"type": "server_vad", "threshold": 0.7, "silence_duration_ms": 400}, voice to cedar, and put the two tools in tools. The voice cannot be changed after the model has produced audio once; most other fields can be updated.
  4. Keep handle = None; on every session_resumption_update with resumable true, store new_handle; on go_away or a dropped socket, reconnect with SessionResumptionConfig(handle=handle); if more than two hours have passed since the last termination, start a fresh session and seed it from your own transcript.
  5. needs_confirm = lambda name, args: name == "refund"; test that lookup_order never calls speak_confirm and that a False answer returns the cancelled_by_user record.
  6. A strong answer weighs a hosted platform's signed BAA and speed against a self-hosted framework's control of the media path; cite the "Regulated data that can't leave your infra" row of the 1.6 table.
  7. For prescriptions, read back drug name letter by letter for look-alike names, dosage as digits and units, and date of birth as day, month, year; refuse to proceed on any mismatch.
  8. Record time.monotonic() around each fake stage, store the per-turn sum, and use statistics.quantiles for p50 and p95; add small random jitter to the fake sleeps or every percentile will be identical.

Check yourself#

  1. What are the three voice-agent architectures, and which providers exemplify each as of November 2026?
  2. Why does a browser need an ephemeral client secret rather than your API key for a realtime session?
  3. What's the difference between server_vad and semantic_vad on the OpenAI Realtime API?
  4. After the model emits a function_call item on Realtime, what two events must your client send to return the result and get a spoken reply?
  5. Why is conversation.item.truncate needed on WebSocket but not WebRTC/SIP?
  6. What's the maximum OpenAI Realtime session duration, and what happens to voice after the first audio response?
  7. How does GPT-Live's delegation differ from Realtime's function calling?
  8. What are the two mechanisms Gemini Live provides for sessions longer than ~15 minutes?
  9. Which providers have NO realtime audio API as of November 2026, and what's the workaround?
  10. When would you choose a hosted platform (Vapi/Retell) over a framework (LiveKit/Pipecat)?
  11. Why do you truncate the assistant's context to what the user heard, not what the model generated?
  12. What's the PCI-style rule for taking card numbers in a voice agent?
  13. Name two observability metrics specific to voice agents that don't exist for text chat.
  14. A caller hangs up mid-conversation on GPT-Live and phones back an hour later. How do you continue where you left off — and what session setting made it possible?
  15. Why does conversation.item.input_audio_transcription.completed never fire in a default OpenAI Realtime session, and what do you set to fix it?

Further resources#

  • OpenAI Realtime API docs — developers.openai.com/api/docs/guides/realtime and the voice-* guides (WebRTC, WebSockets, VAD, MCP, prompting, SIP, cost). The ?api=realtime / ?api=live variants separate the two APIs.
  • OpenAI GPT-Live docs — developers.openai.com/api/docs/guides/live, live-delegation, live-conversations, voice-server-controls.
  • Gemini Live API docs — aistudio.google.com/docs/live-api (overview, capabilities, session-management, ephemeral-tokens, get-started-websocket).
  • OpenAI voice-agent architecture comparison — developers.openai.com/api/docs/guides/voice-agents (the three-architecture table this lesson adapts).
  • LiveKit Agents — docs.livekit.io / github.com/livekit/agents (Apache-2.0).
  • Pipecat — docs.pipecat.ai / github.com/pipecat-ai/pipecat (BSD-2).
  • Vapi, Retell, Bland, ElevenLabs Agents, Twilio ConversationRelay — vendor docs for platform capabilities and pricing.
  • OpenAI voice-agent evaluation cookbook — developers.openai.com/cookbook/examples/audio/voice_agent_evaluation.

← 09.6 — Audio-Native Models and Realtime Foundations | Module 09 overview | 09.8 — Video Understanding →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close