Building conversational AI applications that feel genuinely human requires discarding the traditional HTTP request-response mental model. If your user speaks into a microphone, your application sends an HTTP POST, waits for audio transcription, passes text to an LLM, calls text-to-speech, and finally streams an audio buffer back, the interaction suffers from noticeable latency—frequently exceeding 1.5 to 2.5 seconds. More critically, traditional HTTP pipelines break down the moment a user interrupts the assistant mid-sentence.
The Gemini Multimodal Live API solves this fundamental bottleneck by offering a stateful, full-duplex WebSocket connection. It processes continuous streams of raw audio, visual frames, and text simultaneously, delivering native 24kHz audio responses with sub-second turnaround times.
This guide provides a comprehensive technical walkthrough for software engineers integrating the Gemini Multimodal Live API via WebSockets, covering connection setup, handshake payloads, audio/video streaming formats, interruption management, and production-grade authentication with ephemeral tokens.
Architectural Decision: Direct Client-to-Server vs. Server Proxy
When designing real-time voice and video applications with Gemini, developers face an immediate architectural fork: proxying media streams through an existing backend or connecting the client application directly to Gemini's WebSocket endpoint.
At 365Finds, our recommendation is explicit: Use the direct Client-to-Server architecture powered by Ephemeral Tokens for all interactive frontend interfaces.
Direct Architecture (Recommended):
[Browser / Mobile App] ──(Direct WSS)──> [Gemini Live API]
│
└── 1. Fetch Ephemeral Token ──> [Your Auth Server] (Validates user & mints token)
Proxy Architecture (Avoid for real-time media):
[Browser / Mobile App] ──(WSS)──> [Your Proxy Server] ──(WSS)──> [Gemini Live API]
Why 365Finds Recommends the Direct Client Path
- Latency Minimization: Passing raw 16kHz audio chunks (sent every 100–200ms) and camera frames through a backend proxy introduces double-hop serialization, network transit delays, and operating system context switches. In conversational interfaces, an extra 200ms delay transforms a natural conversation into an awkward waiting game.
- Infrastructure Cost & Scalability: Relaying uncompressed PCM audio and base64 video frames across thousands of concurrent sessions turns your backend cluster into an expensive, bandwidth-heavy bottleneck. Direct client streaming offloads ingress/egress load directly to Google's edge infrastructure.
- Turn-Taking Precision: Local microphone capture and audio playback hardware can react to server-side interruption signals immediately, without waiting for an intermediate server proxy to drain or cancel its buffers.
The historical barrier to direct client connections was credential exposure: you could never put a master API key in client-side code. Gemini eliminates this risk through Ephemeral Tokens.
Production Security: Minting Constrained Ephemeral Tokens
In a client-to-server deployment, your backend acts solely as an authentication and provisioning authority. The client requests a short-lived token from your server, which calls the Gemini provisioning API using your master API key.
By default, an ephemeral token grants 1 minute to establish the WebSocket session (newSessionExpireTime) and supports a continuous connection of up to 30 minutes (expireTime).
Backend Token Minting Implementation (Node.js & Python)
To prevent users from modifying system prompts or switching models from the browser console, 365Finds strongly advises locking down session parameters using liveConnectConstraints directly during token generation on the server.
// Server-Side: Node.js (Token Minting Endpoint)
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
export async function requestLiveSessionToken(userId) {
// Validate user authentication and session quota first
const expireTime = new Date(Date.now() + 30 * 60 * 1000).toISOString(); // 30 minutes
const newSessionExpireTime = new Date(Date.now() + 1 * 60 * 1000).toISOString(); // 1 minute
const token = await client.authTokens.create({
config: {
uses: 1, // Single-use token for a single connection session
expireTime: expireTime,
newSessionExpireTime: newSessionExpireTime,
liveConnectConstraints: {
model: "gemini-3.8-live",
config: {
responseModalities: ["AUDIO"],
sessionResumption: {}
}
}
}
});
// Return the token identifier (token.name) to the frontend
return token.name;
}
Equivalent Python backend implementation:
# Server-Side: Python (FastAPI / Flask)
import datetime
from google import genai
client = genai.Client()
def create_ephemeral_token():
now = datetime.datetime.now(tz=datetime.timezone.utc)
token = client.auth_tokens.create(
config={
"uses": 1,
"expire_time": now + datetime.timedelta(minutes=30),
"new_session_expire_time": now + datetime.timedelta(minutes=1),
"live_connect_constraints": {
"model": "gemini-3.8-live",
"config": {
"response_modalities": ["AUDIO"],
"session_resumption": {}
}
}
}
)
return token.name
Establishing the WebSocket Connection & The Initial Handshake
The Gemini Multimodal Live API enforces strict connection protocol requirements:
- Constrained Endpoint for Ephemeral Tokens:
wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContentConstrained?access_token={EPHEMERAL_TOKEN} - Direct Server Endpoint (Backend Only with Master API Key):
wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent?key={API_KEY} - Mandatory Setup Message:
The very first message sent immediately after the WebSocket handshake completes must be a
setupframe (BidiGenerateContentSetup). If any media chunks or text inputs are transmitted prior to setup, the server closes the connection with an error.
The Initial Handshake Payload
{
"setup": {
"model": "models/gemini-3.8-live",
"generationConfig": {
"responseModalities": ["AUDIO"],
"speechConfig": {
"voiceConfig": {
"prebuiltVoiceConfig": {
"voiceName": "Puck"
}
}
}
},
"systemInstruction": {
"parts": [
{
"text": "You are an expert technical collaborator. Keep answers concise, direct, and conversational. Do not output formatted markdown in your speech."
}
]
},
"tools": [
{
"functionDeclarations": [
{
"name": "lookupHardwareTelemetry",
"description": "Fetch real-time hardware status metrics.",
"parameters": {
"type": "OBJECT",
"properties": {
"deviceId": { "type": "STRING" }
},
"required": ["deviceId"]
}
}
]
}
]
}
}
Prebuilt voices available for Gemini Live include Puck, Charon, Aoede, Fenrir, and Kore.
Streaming Audio and Video to Gemini (Client Ingress)
Once the setup payload is acknowledged, the client can stream real-time sensor data over the same connection using structured JSON frames adhering to BidiGenerateContentClientMessage.
1. Ingesting Real-Time Audio (Microphone)
The Multimodal Live API requires uncompressed, raw 16-bit linear PCM audio sampled at 16,000 Hz in little-endian format, Base64-encoded.
- Audio Input Spec:
audio/pcm;rate=16000, 16-bit, single-channel (mono). - Chunk Size Recommendation: Send audio frames in 100ms to 200ms slices (3,200 to 6,400 raw bytes per chunk). Sending chunks smaller than 50ms produces needless JSON framing overhead, while buffers longer than 500ms degrade perceived response latency.
// Client-Side: Streaming Audio Frame
function sendAudioChunk(webSocket, rawPcm16Buffer) {
if (webSocket.readyState !== WebSocket.OPEN) return;
const base64Data = btoa(
String.fromCharCode(...new Uint8Array(rawPcm16Buffer))
);
const payload = {
realtimeInput: {
mediaChunks: [
{
mimeType: "audio/pcm;rate=16000",
data: base64Data
}
]
}
};
webSocket.send(JSON.stringify(payload));
}
2. Ingesting Real-Time Video (Webcam / Screen Share)
Video input does not use WebRTC video tracks or H.264 streams; instead, it consumes discrete JPEG or PNG image frames embedded in realtimeInput.
- Visual Frame Spec: JPEG or PNG, recommended resolution 720p or 1080p.
- Frame Rate Rule: Throttle camera capture strictly to 1 frame per second (1 FPS).
365Finds Engineering Note: Do not stream 15 or 30 FPS video to Gemini Live API. Gemini evaluates video as continuous visual context rather than temporal motion estimation. Pumping high-frequency frames exhausts prompt token windows in seconds, increases latency, and quickly hits rate limits without adding reasoning accuracy.
// Client-Side: Streaming Video Frame (JPEG)
function sendVideoFrame(webSocket, canvasElement) {
if (webSocket.readyState !== WebSocket.OPEN) return;
// Capture frame as JPEG data URL at quality 0.7
const dataUrl = canvasElement.toDataURL("image/jpeg", 0.7);
const base64Data = dataUrl.split(",")[1];
const payload = {
realtimeInput: {
mediaChunks: [
{
mimeType: "image/jpeg",
data: base64Data
}
]
}
};
webSocket.send(JSON.stringify(payload));
}
Receiving Responses, Managing Interruption, and Playback
Gemini responds via BidiGenerateContentServerMessage frames. Unlike standard text completions, the response arrives as interleaved audio chunks and text transcriptions.
- Audio Output Spec: Raw 16-bit linear PCM at 24,000 Hz (24kHz), little-endian.
- Transcriptions: When enabled, the server streams real-time speech-to-text transcriptions for both user speech (
inputTranscription) and model output (outputTranscription).
// Client-Side: Handling Server Messages
webSocket.onmessage = async (event) => {
const response = JSON.parse(event.data);
// 1. Process Model Audio Output
if (response.serverContent?.modelTurn?.parts) {
for (const part of response.serverContent.modelTurn.parts) {
if (part.inlineData?.mimeType?.startsWith("audio/pcm")) {
const audioBytes = base64ToArrayBuffer(part.inlineData.data);
audioQueue.enqueue(audioBytes); // Push to 24kHz Web Audio buffer queue
}
}
}
// 2. Real-time Transcriptions
if (response.serverContent?.inputTranscription) {
console.log("User Transcript:", response.serverContent.inputTranscription.text);
}
if (response.serverContent?.outputTranscription) {
console.log("Gemini Transcript:", response.serverContent.outputTranscription.text);
}
// 3. User Interruption Handling (Barge-In)
if (response.serverContent?.interrupted) {
console.log("User interrupted the model! Purging playback buffer.");
audioQueue.clearAndStopPlayback();
}
// 4. Turn Completion
if (response.serverContent?.turnComplete) {
console.log("Turn completed by model.");
}
// 5. Tool Calls
if (response.toolCall) {
handleToolCall(webSocket, response.toolCall);
}
};
The Anatomy of Barge-In (Interruption)
Gemini features server-side Voice Activity Detection (VAD). When the user starts speaking while Gemini is still streaming audio responses:
- The model detects user voice activity from incoming PCM chunks.
- The server halts model speech generation immediately.
- The server transmits an
interrupted: trueflag insideserverContent. - Client Responsibility: The frontend must immediately stop its Web Audio playback node and purge any queued PCM chunks. If you fail to flush the local audio buffer on the client, the user will experience the assistant continuing to speak over them, defeating the real-time experience.
Handling Tool Calls and Function Execution Mid-Stream
The Multimodal Live API supports tool execution without severing the full-duplex session. When Gemini decides to invoke a tool defined during the setup phase, it sends a toolCall object containing one or more function invocations.
// Incoming toolCall from Gemini
{
"toolCall": {
"functionCalls": [
{
"name": "lookupHardwareTelemetry",
"id": "call_abc123",
"args": {
"deviceId": "sensor-west-04"
}
}
]
}
}
The client or backend executes the requested function and returns a toolResponse frame over the same active WebSocket:
async function handleToolCall(webSocket, toolCall) {
const functionResponses = [];
for (const fc of toolCall.functionCalls) {
let result;
try {
if (fc.name === "lookupHardwareTelemetry") {
result = await fetchTelemetryData(fc.args.deviceId);
}
} catch (err) {
result = { error: err.message };
}
functionResponses.push({
name: fc.name,
id: fc.id,
response: { result: result }
});
}
// Send function response back through the WebSocket
const toolResponsePayload = {
toolResponse: {
functionResponses: functionResponses
}
};
webSocket.send(JSON.stringify(toolResponsePayload));
}
Upon receiving the toolResponse, Gemini seamlessly resumes verbal dialogue, incorporating the returned data into its spoken output.
Technical Specifications & Parameter Comparison
| Parameter | Input Specification | Output Specification |
|---|---|---|
| Audio Format | Raw 16-bit Linear PCM, little-endian | Raw 16-bit Linear PCM, little-endian |
| Audio Sample Rate | 16,000 Hz (16kHz) | 24,000 Hz (24kHz) |
| Video Format | JPEG / PNG base64 encoded | Not applicable (Text/Audio output only) |
| Video Cadence | Recommended $\le$ 1 FPS | Not applicable |
| Protocol | WSS (Stateful Bi-directional WebSocket) | WSS (Stateful Bi-directional WebSocket) |
| Authentication | Ephemeral Token (access_token) or API Key | Authenticated session context |
| Turn Detection | Native Server-side VAD (Voice Activity Detection) | turnComplete: true / interrupted: true |
365Finds Implementation Checklist for Production
- Enforce Ephemeral Tokens: Never include your master
GEMINI_API_KEYin frontend bundles, native iOS/Android builds, or client-side web code. - Lock Constraints on Server: Include
liveConnectConstraintsin your backend token creation call to prevent prompt hijacking or model tampering. - Clamp Video Ingestion: Throttle client camera capture to strictly 1 FPS. Do not exceed 1080p resolution.
- Sample Rate Resampling: Ensure client microphone audio is converted to 16kHz before base64 encoding; feeding standard 44.1kHz or 48kHz audio without resampling will garble pitch and break speech recognition.
- Active Buffer Flushing on Barge-in: Implement an immediate cancelation hook in your Web Audio API queue whenever
serverContent.interruptedis received. - Session Resumption: Implement session resumption handling if conversations are expected to span across token renewal windows.