Building Production-Grade Voice Agents with Gemini Live API in Antigravity — Bidirectional Audio, Screen Share, and Latency Patterns
A field guide for shipping production-ready realtime voice agents with Gemini Live API on Antigravity. Covers architecture, latency, resilience, function calling, and cost governance with working TypeScript.
Last month, spinning up a toy Gemini Live API demo still felt like an afternoon's work. This week, I had a client ship an agent that combines live customer screen-sharing, bidirectional voice, and internal API calls — all in a single session. Now that stable Live models are available, expectations in the field have jumped a notch.
The catch is that the official sample code will absolutely not survive production. WebSockets drop every five minutes, audio chunks replay from the beginning, function calls spiral into unbounded costs — these are landmines I have personally stepped on. This article shares the design decisions I now use when putting Gemini Live API into production with Antigravity as the control plane. It's a practical piece, not a feature tour: the boundary conditions you can only learn by shipping.
Three Ways Live API Fundamentally Differs from Classic Gemini Calls
Before reading the API reference, it helps to internalize what makes Live API structurally different from generateContent. In my experience, if you miss these three points, you will re-architect several times.
First, Live API is a stateful WebSocket session. Instead of one-shot request/response, you have setup → realtimeInput → serverContent → toolCall → toolResponse flowing in both directions. Treating it like a classic REST call causes connection management, error recovery, and interruption handling to fall out of your design entirely.
Second, billing behaves more like time-based metering than token-based. Officially you pay for input/output tokens, but because audio and video frames stream continuously, cost per minute scales almost linearly with session length. Underestimating this is how teams get surprise bills three times larger than expected during staging.
Third, interruption (barge-in) is server-side. The moment the user starts speaking, the model halts its output and transitions to the next turn. If your client audio playback queue does not align with this behavior, you end up with the AI's voice trailing behind the user's voice — a deeply awkward experience.
Ignore these three and you will rewrite your design multiple times. Before wiring Antigravity multi-agents into the Live API, nail down the Live API primitives.
A Production Architecture in Antigravity: Three Layers, Clear Responsibilities
The architecture I have used in real client projects puts Antigravity's Manager Surface at the center, with three clearly separated layers. It looks simple, but it's the shortest path to controlling latency, reliability, and cost simultaneously.
Edge layer: Connects to the browser over WebRTC/WebSocket, handles PCM16 audio buffering and VAD (voice activity detection). I typically deploy this on Cloudflare Workers Durable Objects or Hono on Workers. For how to keep that layer stateful with one instance per session, Stateful AI Agents on Antigravity × Cloudflare Durable Objects is a good companion read.
Orchestrator layer: Owns the Live API WebSocket session and bridges function calls to internal APIs. Implemented as an Antigravity "Live Agent," so its state is observable from the Manager Surface.
Tools layer: The actual business APIs (booking, search, payments) and RAG (Vertex AI Vector Search). Called from the Orchestrator layer via function calling.
This split works because Live API's statefulness stays confined to the Orchestrator layer. The Edge layer is just pumping audio bytes, and the Tools layer is regular HTTP. Live-API-specific complexity never leaks into your business APIs, which drastically simplifies incident triage. In Antigravity, I prefer three separate agent definitions under .agent/ — edge.md, orchestrator.md, tools.md — and run them in parallel from the Manager Surface.
Why Durable Objects?
Plain Cloudflare Workers struggle to sustain Live API's long-lived sessions. Durable Objects, on the other hand, support WebSocket hibernation, which drops idle memory cost to near zero. If you need to run thousands of concurrent sessions in production, Durable Objects plus the Hibernation API are practically mandatory. For sub-minute one-shot calls, regular Workers are fine and the Durable Objects premium is not worth it.
✦
Thank you for reading this far.
Continue Reading
What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.
WHAT YOU'LL LEARN
✦Readers struggling with dropped audio, 5-minute WebSocket disconnects, and garbled playback will be able to implement a hardened Live API session layer today
✦You'll learn how to architect a bidirectional voice + screen share + function-calling agent with Antigravity's multi-agent surface using a clean three-file design
✦You'll come away with a cost-safe operational playbook — quotas, caps, auto-downgrade, and session summarization fallbacks — that keeps Live API bills predictable in production
Secure payment via Stripe · Cancel anytime
✦
Unlock This Article
Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.
Code Example 1: Resilient Live API Session Lifecycle
The first code example spins up a Live API session that recovers automatically from network drops. It's meant to run inside the Orchestrator agent. Instead of swallowing errors, it enforces explicit state machine transitions and exponential backoff.
// orchestrator/live-session.ts// Purpose: Keep a Gemini Live API WebSocket session alive across// transient disconnects and forced server-side closes.import { GoogleGenAI, LiveSession, Modality } from "@google/genai";type SessionState = "idle" | "connecting" | "live" | "retrying" | "closed";export class LiveVoiceSession { private ai: GoogleGenAI; private session: LiveSession | null = null; private state: SessionState = "idle"; private retries = 0; private readonly maxRetries = 3; constructor(apiKey: string, private onAudio: (pcm: ArrayBuffer) => void) { this.ai = new GoogleGenAI({ apiKey }); } async start(): Promise<void> { if (this.state !== "idle") { throw new Error(`cannot start in state: ${this.state}`); } this.state = "connecting"; try { this.session = await this.ai.live.connect({ model: "gemini-3.8-live", // standard model as of Oct 2026; check the models page for the latest ID config: { responseModalities: [Modality.AUDIO], speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: "Aoede" } }, }, systemInstruction: "You are a calm customer support agent. Stop speaking immediately if the user starts talking.", }, callbacks: { onmessage: (msg) => this.handleMessage(msg), onerror: (err) => this.handleError(err), onclose: (ev) => this.handleClose(ev), }, }); this.state = "live"; this.retries = 0; } catch (err) { this.state = "closed"; throw err; // caller logs and alerts } } private handleMessage(msg: unknown) { const data = extractAudioChunk(msg); if (data) this.onAudio(data); } private async handleError(err: Error) { console.error("[LiveSession] error", err.message); if (this.retries < this.maxRetries && this.state === "live") { this.state = "retrying"; this.retries++; const backoff = Math.min(1000 * 2 ** this.retries, 8000); await new Promise((r) => setTimeout(r, backoff)); this.state = "idle"; await this.start(); } else { this.state = "closed"; } } private handleClose(_ev: CloseEvent) { if (this.state === "live") { // Server forced the close — attempt one more recovery. this.handleError(new Error("server closed")); } } async stop(): Promise<void> { this.state = "closed"; await this.session?.close(); this.session = null; }}function extractAudioChunk(msg: unknown): ArrayBuffer | null { const parts = (msg as any)?.serverContent?.modelTurn?.parts ?? []; for (const p of parts) { if (p?.inlineData?.mimeType?.startsWith("audio/")) { return base64ToArrayBuffer(p.inlineData.data); } } return null;}function base64ToArrayBuffer(b64: string): ArrayBuffer { const bin = atob(b64); const buf = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i); return buf.buffer;}
The intentional design decisions here are a forced state machine, exponential backoff for reconnection, and explicit awareness of server-side closes. The official sample leaves state management to the developer. In production, without a typed state machine, onclose and onerror race each other and you end up with two concurrent sessions.
The expected behavior: a successful start() produces a setupComplete server event, audio chunks arrive in the callback roughly 600ms after the first user utterance (PCM16 at 20ms/chunk), and disconnects trigger up to three retries at 2s / 4s / 8s backoff.
Surviving Disconnects Without Losing the Conversation: sessionResumption and GoAway
The reconnection logic in Code Example 1 only re-establishes the socket. The conversation history dies with the server-side session, so the user right after a reconnect gets asked for the order number they already gave you. You never notice this in a demo. It was the single biggest complaint after we shipped.
Live API answers this directly. Put sessionResumption in your setup and the server hands you resumption handles as the conversation progresses. On a drop, you reconnect with the latest handle and the conversation state comes back with it.
// orchestrator/resumable-session.ts// Goal: keep a Live session alive across disconnects without losing context.// Excerpt meant to slot into LiveVoiceSession from Code Example 1.private resumeHandle: string | null = null;async connect(): Promise<void> { this.session = await this.ai.live.connect({ model: "gemini-3.8-live", // standard model as of Oct 2026; check the models page for the latest ID config: { responseModalities: [Modality.AUDIO], // Ask for resumption handles; pass the handle back on later attempts. sessionResumption: this.resumeHandle ? { handle: this.resumeHandle } : {}, // Prevent long sessions from dying when they hit the context limit. contextWindowCompression: { slidingWindow: {} }, }, callbacks: { onmessage: (msg) => this.handleMessage(msg), onerror: (err) => this.handleError(err), onclose: (ev) => this.handleClose(ev), }, });}private handleMessage(msg: any) { // The server keeps issuing new handles. Always hold only the newest one. const update = msg?.sessionResumptionUpdate; if (update?.resumable && update.newHandle) { this.resumeHandle = update.newHandle; } // Disconnect warning. Reconnecting inside timeLeft minimizes dead air. const goAway = msg?.goAway; if (goAway) { void this.reconnectBefore(Date.now() + parseDurationMs(goAway.timeLeft ?? "0s")); } const data = extractAudioChunk(msg); if (data) this.onAudio(data);}private async reconnectBefore(deadline: number): Promise<void> { // Move 2s ahead of the warning; wait for silence if the user is speaking. const lead = Math.max(deadline - Date.now() - 2000, 0); await new Promise((r) => setTimeout(r, lead)); if (this.isUserSpeaking) await this.waitForSilence(1500); // fed by the edge-layer VAD await this.session?.close(); await this.connect(); // resumeHandle carries the conversation over}function parseDurationMs(d: string): number { // Convert a protobuf Duration like "10.5s" into milliseconds. return Math.round(parseFloat(d.replace("s", "")) * 1000);}
Three things are doing the work here.
Keep the resumption handle current.sessionResumptionUpdate is not a one-shot event — it arrives repeatedly as the conversation moves. Store only the first one and resuming rewinds you to a state from several minutes ago. My first version shipped exactly that bug, and the agent behaved like it had time-traveled.
Act on goAway instead of waiting for it. The server warns you shortly before it closes the socket. Rather than absorbing that quietly and scrambling inside onclose, reconnect proactively at the warning. That reordering alone cut perceived dead air from 2–3 seconds down to roughly 300ms.
Never cut mid-utterance. A proactive reconnect that lands in the middle of someone speaking is worse than the drop it prevents. Waiting up to 1.5 seconds for the VAD to report silence before switching makes the seam essentially invisible.
contextWindowCompression is in there so a long session doesn't die the instant it hits the context ceiling. The sliding window drops older turns, which keeps 30-minute conversations connected.
The catch: dropped context is genuinely gone. Anything you cannot afford to lose — order numbers, identity verification results — must live in your own application state, not in the model's memory. Ship without that separation and long conversations will suddenly lose their premises halfway through. I ended up solving this with a "confirmed facts" store owned by the Business Tools agent.
The whole change came to about 40 lines. On a project that kept getting disconnect-related complaints, they simply stopped after it shipped. If you are taking Live API to production, close this gap before you add another feature.
Work Backwards From the Documented Limits
Before adding resumption, you need the actual numbers for how long things live. I used to carry a vague memory of "it drops after five minutes or so," designed around that, and then added screen share. Sessions started dying far sooner than I expected, and I lost half a day separating the causes. These are the values I confirmed in the official Live API session management docs, next to what each one changes in the design.
Item
Documented value (checked Oct 2026)
What it changes
Audio-only session (no compression)
15 minutes
A typical support call fits in one session
Audio + video session (no compression)
2 minutes
Streaming screen share continuously means being cut off at 2 minutes
Connection (WebSocket) lifetime
About 10 minutes
The socket dies before the session does, so a resumption handle is not optional
Resumption token validity
2 hours after the session last ended
A caller who rings back within 2 hours can pick up where they left off
Image (frame) input
JPEG, up to 1 FPS
A 30fps design is outside the spec to begin with
This table changed the order I build things in. I used to get audio working and bolt reconnection on later. Now I assume the connection will drop and put the resumption handle in first. Screen share is no longer a constant stream; frames are added only at the moment they matter. A session with video has a much shorter ceiling, so decide early whether to enable contextWindowCompression or to split video into its own session.
Code Example 2: Audio Playback Queue with Barge-In
The second example is the Edge-layer playback queue. This is where beginners get stuck. Naively chaining AudioBufferSourceNode instances gives you no way to stop the model when the user starts talking.
// edge/audio-queue.ts// Purpose: Play back model audio chunks seamlessly and stop playback// immediately when the user begins speaking (barge-in).export class AudioQueue { private ctx: AudioContext; private sources: AudioBufferSourceNode[] = []; private nextStartTime = 0; constructor(private sampleRate = 24000) { this.ctx = new AudioContext({ sampleRate }); } enqueue(pcm16: ArrayBuffer): void { const float32 = pcm16ToFloat32(pcm16); const buffer = this.ctx.createBuffer(1, float32.length, this.sampleRate); buffer.copyToChannel(float32, 0); const src = this.ctx.createBufferSource(); src.buffer = buffer; src.connect(this.ctx.destination); const startAt = Math.max(this.ctx.currentTime, this.nextStartTime); src.start(startAt); this.nextStartTime = startAt + buffer.duration; this.sources.push(src); src.onended = () => { this.sources = this.sources.filter((s) => s !== src); }; } interrupt(): void { // Barge-in: stop every active source immediately. for (const s of this.sources) { try { s.stop(); } catch { // Source already finished — safe to ignore. } } this.sources = []; this.nextStartTime = this.ctx.currentTime; }}function pcm16ToFloat32(buf: ArrayBuffer): Float32Array { const view = new DataView(buf); const out = new Float32Array(buf.byteLength / 2); for (let i = 0; i < out.length; i++) { out[i] = view.getInt16(i * 2, true) / 0x8000; } return out;}
Why track nextStartTime explicitly? Calling src.start(0) naively produces audible clicks at chunk boundaries. Scheduling each source against AudioContext.currentTime gives you gapless playback.
Why swallow exceptions silently?AudioBufferSourceNode.stop() throws on an already-finished source. Since barge-in is a latency race, the try/catch is cheaper than checking each source's state, and the UX impact is zero.
Pair this with a VAD that runs in the Edge layer (browser onaudioprocess + RMS threshold) and you can fire interrupt() without waiting on the Live API round trip. User speech to AI silence lands under 50ms of latency.
Code Example 3: Type-Safe Function Calling
The third example bridges Live API's function calling to internal APIs. This is the most safety-critical part of the stack. For a deeper dive into function-calling schema design on its own, see Mastering Gemini Function Calling with Antigravity (Python).
Zod validation: Live API occasionally returns stringified JSON in args. Using z.preprocess to accept string inputs eliminates the "flaky in prod" class of bugs almost entirely.
Per-session cost cap: Live API function calls are not free — many of them trigger paid external APIs. Without a cap, an adversarial user can drain thousands of yen in one session.
Parallel dispatch: Live API can emit multiple tool calls in a single message. Serial execution spikes latency; always run them concurrently.
Common Pitfalls
Here are five traps I and my clients have actually hit — none of which are explicit in the docs.
1. Sample rate mismatch makes audio sound sped up
Live API defaults to 16kHz input and 24kHz output. Browser getUserMedia often returns 44.1kHz or 48kHz. Sending the raw ArrayBuffer through makes the model hear "chipmunk speech" and transcription degrades.
Fix: Create your Edge-layer AudioContext with { sampleRate: 16000 } and resample through OfflineAudioContext before sending. If the browser refuses 16kHz, apply an explicit 3x downsampling chain with a BiquadFilter.
2. responseModalities: [AUDIO, TEXT] slows everything down
Requesting both modalities makes the model wait for text completion before emitting audio. First-audio latency balloons 1.5-2x.
Fix: Request audio only and enable outputAudioTranscription: { } if you need captions. Text then streams in parallel with audio.
3. Swapping systemInstruction by re-establishing sessions doubles your cost
systemInstruction is set once at setup and persists for the session's lifetime. Tearing down the session to change roles means paying the setup cost again every time.
Fix: Inject extra context via clientContent mid-session, or handle "expert routing" via function calling so you keep a single Live session alive.
4. Sending too many screen frames eats both your bill and your session limit
Per the documentation, image input is JPEG at up to 1 FPS. A 30fps pipeline is outside the spec, and every extra frame is more input to pay for and a faster path to the 2-minute ceiling on audio + video sessions.
Fix: Send only on change detection (pixel diff between frames) and hold around 0.5fps. Raising it to 1fps only while the user says "look here" is the realistic production pattern.
5. Stale audio from the previous session plays after reconnecting
Closing the Live session does not automatically clear browser-side AudioBufferSourceNode instances queued for later playback. The tail of the last session plays into the first chunk of the new one.
Fix: Call audioQueue.interrupt() from stop() and explicitly close() and recreate the AudioContext. That residual noise disappears completely.
Running in Production with Antigravity Multi-Agents
Here is how these pieces compose inside Antigravity. I keep three agents resident in the Manager Surface:
Live Orchestrator agent: Owns the Live API session, mediates audio I/O, and dispatches tool calls. I put the state machine spec and reconnection policy in .agent/live-orchestrator.md.
Business Tools agent: Booking, search, RAG, and other internal APIs. Consumes typed function calls from the Orchestrator. .agent/business-tools.md documents each API's timeout and fallback.
Guardian agent: Monitors session duration, cost, and error rate. Sends terminate to the Orchestrator when thresholds are crossed. Runs as an Antigravity Background Agent with dashboards in the Manager Surface.
The reason I use three agents is simple: don't mix Live API's "long-lived, realtime, uncertain" traits with business logic's "short-lived, request/response, deterministic" traits. Mixing them warps the design toward whichever side has the louder failure mode. Antigravity's parallel agents feature is a very natural fit for this kind of separation.
Metrics That Actually Matter in Operations
These are the KPIs I put on the dashboard in production. Grafana + Prometheus or Cloudflare Workers Analytics Engine both work. If you want to tie agent-level traces together, pair this with Building an AI Observability Pipeline on Antigravity with OpenTelemetry for broader coverage.
Session duration (P50 / P95): P95 climbing past 10 minutes means users are getting dragged into aimless small talk. Tighten Guardian's forced-termination policy.
Time-to-first-audio: Above 1s is a degradation signal. Re-evaluate region and model (standard gemini-3.8-live vs gemini-3.8-live-extended-thinking).
Reconnection rate: More than 5% of sessions in an hour means WebSocket quality on the client is suspect.
Tool call success rate: Under 95% typically means your function schema is ambiguous and Gemini is mis-invoking tools. Tighten Zod schemas and descriptions.
Cost per session-minute: 1.5x over baseline usually means non-audio modalities (video, text) are leaking into the request budget.
Route all of these through Guardian and wire automatic auto-downgrade policies when thresholds are breached. Concrete actions: switch from gemini-3.8-live-extended-thinking to gemini-3.8-live, cut video frame frequency, shorten max session duration.
Choosing Between the Standard and Extended-Thinking Models
Once Guardian is running and your baseline metrics stabilize, the next lever is model choice. The official models page lists gemini-3.8-live (the standard for low-latency voice agents) and gemini-3.8-live-extended-thinking (a heavier-reasoning option) as stable Live models as of October 2026. The older gemini-3.1-flash-live-preview is marked legacy, with migration to 3.8 recommended.
I used to start on the heavier option whenever I was unsure. On recent projects I changed my default to the standard model.
Where the standard model fits: Scripted support flows like booking or checkout, structured data gathering, anything where the job is to collect facts and call tools. Responsiveness is the experience.
Where extended-thinking fits: Long troubleshooting, conversations that lean on early context, and requirements to interpret and explain what is on screen. You accept a longer wait, so choose it only when it pays for itself.
The hybrid pattern: Start on the standard model, and tear down and reconnect on extended-thinking only when the Orchestrator detects an escalation condition (an explicit request, frustration in the transcript, tool failures past a threshold). Users tended to read the 1-2 second seam as a human handoff.
One caveat: you cannot switch models in the middle of a connection. Re-sending setup to fake it leaves state drift behind. Treat the resumption handle as something for reconnecting to the same model; when you switch, hand a summary to the new session and start fresh.
Choose the model by measured latency and unit cost, not by its name. Hold to that and your design survives the next model rename.
Real Scenario: Customer Support with Screen Share and RAG
One live production deployment I helped ship: an e-commerce support desk where users can ask voice questions while their "Order History" page is on screen.
The user taps "Start voice support" in the help page. WebRTC connects to the Edge layer, and the Order History DOM is captured at 1fps and streamed.
Live Orchestrator reads the screen context, queries internal APIs (orders DB, shipping API) via Business Tools.
RAG uses prior FAQs pre-embedded in Vertex AI Vector Search, exposed as a search_knowledge function call.
Guardian forces termination at 10 minutes and emails a summary to both the customer and the CS rep.
Outcome: inquiries that used to take 8 minutes in chat now resolve in an average of 2.5 minutes. In the first month, however, Live API costs ran close to 2x the estimate. After applying the "0.5fps screen share," "audio-only modality," and "session cap" fixes from above, costs landed in the expected range by month two.
Testing Strategy: Simulating Live Sessions in CI
A common question I get is how to write tests for Live API agents. You cannot dial real sessions from CI without quickly burning through your Gemini quota. The approach that has worked for me in three projects is a three-layer test pyramid, and I have come to rely on it for any realtime agent work.
Layer 1 — Unit tests with mock LiveSession: The LiveVoiceSession, AudioQueue, and ToolRouter classes are designed so their dependencies are injectable. I mock the @google/genailive.connect to return a fake LiveSession that I drive by hand. This layer catches state machine bugs (the onclose/onerror race I mentioned earlier) and regression-tests the retry logic. These tests run in under a second and are the primary gate on every PR.
Layer 2 — Replay tests against captured sessions: For each supported flow (booking, FAQ, escalation), I capture one real Live API session into a JSON transcript: the sequence of serverContent, toolCall, and audio chunks. The replay harness feeds those back into my Orchestrator with timing preserved. This layer catches schema drift in @google/genai and regressions in function argument handling. I re-record transcripts monthly to stay current with Gemini's behavior.
Layer 3 — Smoke tests against real Live API in staging: Once per deploy, a scripted agent runs a fixed two-minute dialog against the live service in a staging project. The only assertions are on tool call success rate, TTFT, and audio chunk integrity. Failures page the on-call. Because this is the only place real quota is spent, I scope it ruthlessly — two minutes, one model, one region.
This pyramid lets you ship Live API changes confidently. The replay layer is the real workhorse — it caught three production-bound regressions in the last quarter alone.
Security and Privacy Considerations You Cannot Skip
Voice agents amplify every privacy concern you had with chatbots. These are the ones that matter in production, roughly ordered by how often they bite:
PII redaction before logging: The audio transcripts you produce for debugging will contain names, phone numbers, and order numbers. Pipe them through a redaction pass (Cloud DLP works, or a local regex-based pass) before they land in logs or Sentry. Stream-based redaction on the transcript channel is what I use — it runs in the Orchestrator and touches all traffic.
User consent and recording disclosure: In many jurisdictions, you are required to disclose that the session is AI-mediated and, in some, explicitly that audio is being transmitted to a third party. Design the opening system turn to include the disclosure ("This conversation is handled by an AI assistant; audio is processed by Google Gemini...") and log the acknowledgment.
Function calling allowlist: Never let the Live session call arbitrary internal APIs. The ToolRouter above enforces a name-based allowlist, and each tool's handler should itself validate the caller's authority again — defense in depth. I have seen a prompt-injected agent attempt to invoke a refund_order tool the user had no right to call; the defense-in-depth check stopped it.
Rate limits per user, not just per session: An attacker who finds a way to spin up new sessions will happily do so. Track spend and duration at the user level and enforce caps there, in addition to the per-session cap in ToolRouter.
Model routing for regulated data: For healthcare or financial data, prefer a regional model endpoint where available, and document in your architecture which data classes are allowed to leave the region.
Deployment Checklist
Before pushing Live API to real users, I run through this checklist. It has caught embarrassing issues before every launch I have supported:
[ ] Guardian agent is the first thing in the deploy, with alerts wired to PagerDuty or equivalent.
[ ] Session duration cap is set to a value matching your support SLAs (I usually start at 10 minutes).
[ ] Per-session costLimit across all tools sums to an acceptable worst case.
[ ] Reconnection logic is tested by manually killing the WebSocket in staging.
[ ] Audio sample rate is explicitly 16kHz on input, verified by capturing a staging session.
[ ] responseModalities is audio-only; captions come from outputAudioTranscription.
[ ] Screen-share is held at 1fps or below and raised only on explicit user intent.
[ ] AudioContext is close()d and recreated on session stop; verified by Chrome's about:tracing.
[ ] PII redaction is enabled on all transcript logging paths.
[ ] Disclosure line is present in the opening system turn.
[ ] Tool name allowlist matches the agents you actually defined (run diff against your .agent/ files).
[ ] Model downgrade path (extended-thinking → standard) is wired and tested.
[ ] Dashboard shows P95 session duration, TTFT, reconnect rate, tool success rate, and cost per minute.
[ ] CI replay tests pass against a freshly recorded transcript.
The items are boring on purpose. Live API incidents in production are almost always about boring oversights — a forgotten cap, a missed allowlist entry, an untested reconnection path. Boring checklists beat heroic debugging.
When to Not Use Live API
I spend most of this article evangelizing Live API, so let me balance that. There are three scenarios where I actively recommend against it:
The interaction does not need sub-second latency: If your agent can reasonably reply in 2-3 seconds, classic generateContent with streaming text plus a separate TTS pass (ElevenLabs, Google Cloud TTS) is simpler, cheaper, and easier to test. Live API pays its premium in interactivity, not in throughput.
You need strong deterministic control over model output: Live API's barge-in and streaming behavior means you give up some of the fine-grained control you have with batch APIs. If your use case is "the model must emit exactly this structured response," a text-based function-calling flow is more appropriate.
Your sessions are mostly idle: Live API bills throughout the session, not just during exchanges. If a "session" in your product is a user leaving a browser tab open for hours with occasional questions, that's not a Live API session — that's a classic chat, and you should open a new request per turn.
Matching the tool to the job keeps costs predictable. I have seen teams default to Live API because it's the shiniest API available, then spend their runway on unused compute time. Pick it when the realtime dimension actually matters to the user.
Closing: The First Move You Should Make Today
When teams ask me where to start with Live API in production, my answer is always the same: build the Guardian agent first — the cost and time monitor. Building features before guardrails is how you ship expensive incidents. Monitoring first, Live session implementation second: that's the order that holds up under real traffic.
If you have 30 minutes today, spin up .agent/guardian.md in Antigravity and enumerate the metrics you want to capture at session start (start time, model, expected cost cap). Then approach the Live API SDK. It looks like a detour, but it's actually the shortest path from zero to production.
For the practical details, use the three code examples and five pitfalls in this article as your checklist. Gemini Live API opens up real creative possibilities, and it will also happily burn a hole in your budget if you treat it like a classic REST API. Spending that extra hour on architecture is what separates a demo from a service.
Time-billed, long-lived sessions like Live API tie your operating cost to monitoring design far more tightly than a classic Web API ever did. And whether you wire in sessionResumption from day one decides what running this feels like six months from now. I am still learning my way through this space, so I hope these notes save someone else a few of the evenings they cost me.
Share
Thank You for Reading
Antigravity Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.