360 Secure SkillHub
360 安全技能中心

gemini-live-api-dev

提供 Gemini Live API 的模型选择、SDK 用法、音视频与文本流式传输、实时翻译与转录、VAD、工具调用、会话管理、临时令牌及旧模型迁移说明和代码示例。

分类:开发
google-gemini
热度 67.93
最近更新 2026-12-04 05:08:19

安装

发给 Agent
帮我安装这个技能:npx secure-skills-cli add google-gemini/gemini-skills/gemini-live-api-dev
兼容性
通用兼容
联网要求
不联网
数据出网
数据不出本机
Metadata
name
gemini-live-api-dev
description
Use this skill when building real-time, bidirectional streaming applications with the Gemini Live API, or migrating legacy Live models (2.0/2.5/3.1/3.8) to Gemini 4 Live and Gemini 4 Live Translate. Covers WebSocket-based audio/video/text streaming, Proactive Video, mid-session context updates, 2,000+ preset voices, voice activity detection (VAD), background reasoning, asynchronous function calling, session management, ephemeral tokens, live transcription, and live translation. SDKs covered - google-genai (Python), @google/genai (JavaScript/TypeScript).

Gemini Live API Development Skill

Overview

The Live API enables low-latency, real-time voice and video interactions with Gemini over WebSockets. It processes continuous streams of audio, video, or text to deliver immediate, human-like spoken responses and background reasoning.

Key capabilities:

  • Bidirectional audio streaming — real-time mic-to-speaker conversations, including upgraded 8kHz telephony VAD
  • Unified fast & background reasoning — lowest-latency default (MINIMAL) or multi-step background reasoning (LOW/MEDIUM/HIGH) with spoken updates on gemini-4-live
  • Extended voices — 2,000+ preset voices and Paid Tier 3 custom voice replication
  • Video streaming & Proactive Video — send camera/screen frames alongside audio, with optional proactive visual responses
  • Mid-session context updates — dynamically update system_instruction and tools without reconnecting
  • Live translation — real-time speech-to-speech translation across 70+ languages (4,900+ language pairs)
  • Live streaming transcription — real-time speech-to-text with interim and finalized streams
  • Text input/output — send and receive text within a live session
  • Audio transcriptions — get text transcripts of both input and output audio
  • Voice Activity Detection (VAD) — automatic server VAD, client-side Hybrid VAD, and manual Push-to-Talk
  • Asynchronous function calling — non-blocking tool execution while audio continues streaming
  • Full-session client content — inject and update conversation turns mid-stream
  • Session management — context compression, session resumption, GoAway signals, and implicit session prefix caching
  • Ephemeral tokens — secure client-side authentication

[!NOTE] The Live API connects directly via WebSockets. For WebRTC support or simplified integration, use a partner integration.

Models

Current Models (Use These)

  • gemini-4-live — Unified model replacing both gemini-3.8-live and gemini-3.8-live-extended-thinking on a single endpoint (128K input / 64K output context window).
    • Fast default mode (omit thinking_level or set "minimal" / MINIMAL): Lowest latency (>3x faster Time to First Audio than gemini-3.8-live), standard turn_complete lifecycle, supports both NON_BLOCKING (default) and explicit BLOCKING function declarations plus function response scheduling (SILENT, WHEN_IDLE, INTERRUPT).
    • Deeper background reasoning mode (thinking_level set to "low", "medium", or "high" / LOW, MEDIUM, HIGH): Runs background reasoning while speaking conversational updates. Requires behavior: "NON_BLOCKING" on all function declarations (BLOCKING and scheduling return errors), and clients must track server_content.interaction_status (IN_PROGRESS vs IDLE).
    • thinking_budget and XHIGH are not supported.
  • gemini-4-live-translate — Real-time speech-to-speech streaming translation across 70+ languages (4,900+ language pairs), starting in under 2 seconds (~2x faster than gemini-3.5-live-translate-preview), with improved speaker echo handling (16K input / 32K output context window). Supports translation_config, optional setup-time system_instruction, and optional preset voice selection via speech_config; does not support tools, thinking, or text input.
  • gemini-3.5-transcribe-live — Real-time streaming speech-to-text with interim hypotheses, finalized transcripts, smart formatting, and Hybrid VAD.

[!WARNING] Legacy Models (gemini-3.8-live, gemini-3.8-live-extended-thinking, gemini-3.5-live-translate-preview, gemini-3.1-flash-live-preview, gemini-2.5-flash-native-audio-*, gemini-live-2.5-flash-preview, gemini-2.0-flash-live-001): Read references/migration.md for model replacements and protocol details (thinking_level, behavior: "NON_BLOCKING", server_content.interaction_status, v1beta routing, send_client_content).

SDKs

  • Python: google-genai >= 3.2.0 — pip install -U google-genai
  • JavaScript/TypeScript: @google/genai >= 3.2.0 — npm install @google/genai

[!IMPORTANT] v1beta is required for the Live API. SDKs >= 3.0.0 default to v1, while the Live API (BidiGenerateContent), Ephemeral Tokens (POST /v1beta/auth_tokens), and Voices API (GET /v1beta/voices) require v1beta. Always initialize clients with http_options={"api_version": "v1beta"} (Python) or { httpOptions: { apiVersion: "v1beta" } } (JS/TS).

[!WARNING] Legacy SDKs google-generativeai (Python) and @google/generative-ai (JS) are deprecated. Never use them.

Partner Integrations

To streamline real-time audio/video app development, use a third-party integration supporting the Gemini Live API over WebRTC or WebSockets:

  • LiveKit — Use the Gemini Live API with LiveKit Agents.
  • Pipecat by Daily — Create a real-time AI chatbot using Gemini Live and Pipecat.
  • Fishjam by Software Mansion — Create live video and audio streaming applications with Fishjam.
  • Vision Agents by Stream — Build real-time voice and video AI applications with Vision Agents.
  • Voximplant — Connect inbound and outbound calls to Live API with Voximplant.
  • Firebase AI SDK — Get started with the Gemini Live API using Firebase AI Logic.

Audio Formats

  • Input: Raw PCM, little-endian, 16-bit, mono. 16kHz native (audio/pcm;rate=16000; other rates are resampled). Also supports audio/pcm;rate=8000 with upgraded 8kHz telephony VAD for noisy phone lines, short utterances, and barge-in.
  • Output: Raw PCM, little-endian, 16-bit, mono. 24kHz sample rate.

[!IMPORTANT] Use send_realtime_input / sendRealtimeInput for all real-time streaming user input (audio, video, and text). On Gemini 4 Live (and Gemini 3.8 Live), send_client_content / sendClientContent is supported across the full session lifecycle with explicit roles (user or model) to inject conversation context (turn_complete=true unconditionally interrupts active generation).

[!WARNING] Do not use media in sendRealtimeInput. Use the specific keys: audio for audio data, video for images/video frames, and text for text input.


Quick Start

Authentication

Python

from google import genai

# Reads GEMINI_API_KEY from the environment (or pass api_key="YOUR_API_KEY")
client = genai.Client(http_options={"api_version": "v1beta"})

JavaScript

import { GoogleGenAI } from '@google/genai';

// Reads GEMINI_API_KEY from the environment (or pass apiKey: 'YOUR_API_KEY')
const ai = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });

Connecting to the Live API

Python

from google.genai import types

config = types.LiveConnectConfig(
    response_modalities=[types.Modality.AUDIO],
    system_instruction=types.Content(
        parts=[types.Part(text="You are a helpful assistant.")]
    )
)

async with client.aio.live.connect(model="gemini-4-live", config=config) as session:
    pass  # Session is active

JavaScript

const session = await ai.live.connect({
  model: 'gemini-4-live',
  config: {
    responseModalities: ['audio'],
    systemInstruction: { parts: [{ text: 'You are a helpful assistant.' }] }
  },
  callbacks: {
    onopen: () => console.log('Connected'),
    onmessage: (response) => console.log('Message:', response),
    onerror: (error) => console.error('Error:', error),
    onclose: () => console.log('Closed')
  }
});

Sending Text

Python

await session.send_realtime_input(text="Hello, how are you?")

JavaScript

session.sendRealtimeInput({ text: 'Hello, how are you?' });

Sending Audio

Python

await session.send_realtime_input(
    audio=types.Blob(data=chunk, mime_type="audio/pcm;rate=16000")
)

JavaScript

session.sendRealtimeInput({
  audio: { data: chunk.toString('base64'), mimeType: 'audio/pcm;rate=16000' }
});

Sending Video

Python

# frame: raw JPEG-encoded bytes
await session.send_realtime_input(
    video=types.Blob(data=frame, mime_type="image/jpeg")
)

JavaScript

session.sendRealtimeInput({
  video: { data: frame.toString('base64'), mimeType: 'image/jpeg' }
});

Receiving Audio and Text

[!IMPORTANT] A single server event can contain multiple content parts simultaneously (e.g., audio chunks and transcript). Always process all parts in each event to avoid missing content.

Python

async for response in session.receive():
    content = response.server_content
    if content:
        # Audio — process ALL parts in each event
        if content.model_turn:
            for part in content.model_turn.parts:
                if part.inline_data:
                    audio_data = part.inline_data.data
        # Transcription
        if content.input_transcription:
            print(f"User: {content.input_transcription.text}")
        if content.output_transcription:
            print(f"Gemini: {content.output_transcription.text}")
        # Interruption
        if content.interrupted is True:
            pass  # Stop playback, clear audio queue

JavaScript

// Inside the onmessage callback
const content = response.serverContent;
if (content?.modelTurn?.parts) {
  for (const part of content.modelTurn.parts) {
    if (part.inlineData) {
      const audioData = part.inlineData.data; // Base64 encoded
    }
  }
}
if (content?.inputTranscription) console.log('User:', content.inputTranscription.text);
if (content?.outputTranscription) console.log('Gemini:', content.outputTranscription.text);
if (content?.interrupted) { /* Stop playback, clear audio queue */ }

Background Reasoning

gemini-4-live supports two operating modes on a single endpoint controlled by thinking_level:

  • Fast default mode (omit thinking_level or set thinking_level="minimal" / MINIMAL): Lowest latency (>3x faster Time to First Audio than gemini-3.8-live), standard turn_complete lifecycle, and support for both NON_BLOCKING (default) and explicit BLOCKING function declarations plus function response scheduling (SILENT, WHEN_IDLE, INTERRUPT).
  • Deeper background reasoning mode (thinking_level set to "low", "medium", or "high" / LOW, MEDIUM, HIGH): Use when your voice agent must evaluate complex data, plan multiple steps, or handle long-running tools. The model speaks natural conversational updates (e.g. "Checking flight options now...") while running background reasoning and asynchronous tools.

Key requirements for LOW / MEDIUM / HIGH mode:

  • Thinking config: Set thinking_config=types.ThinkingConfig(thinking_level="low") ("low" | "medium" | "high"). thinking_budget and XHIGH are not supported on gemini-4-live.
  • Non-blocking tools required: All function declarations must set behavior="NON_BLOCKING". BLOCKING tools and function response scheduling (SILENT, WHEN_IDLE, INTERRUPT) return errors in this mode.
  • Lifecycle tracking (interaction_status): Do not rely on turn_complete=True alone to detect turn completion. Monitor message.server_content.interaction_status (Python) / message.serverContent?.interactionStatus (JS/TS):
    • "IN_PROGRESS": Server is reasoning, speaking conversational updates, or waiting for async tool responses.
    • "IDLE": Server has completed all background reasoning and tool calls; session is ready for user input.

See references/migration.md and the Thinking in Live API Guide for complete Python and JavaScript implementation examples.


Gemini 4 Live Capabilities

Voices (gemini-4-live)

  • Extended voice library (2,000+ preset voices): Pass a prebuilt voice name in speech_config.voice_config.prebuilt_voice_config.voice_name (or speech_config.voice_config.voice). Always filter when listing preset voices (v1beta client required):
    • Python: client.voices.list(type_=["prebuilt"])
    • JS/TS: ai.voices.list({ type: ["prebuilt"] })
    • REST: GET /v1beta/voices?type=prebuilt
  • Custom Voice replication (Paid Tier 3 only): Supports replicated voices (voice_... IDs or stateless voicekey_... keys created via POST /v1beta/voices) passed in speech_config.voice_config.voice.
  • Designed voices are NOT supported: Voice Design and Voice Remixing are TTS-only; passing a prompted/designed voice to gemini-4-live fails.
  • Language / accent: Optionally set speech_config.language_code alongside a voice to choose a language or regional accent.

Proactive Video

Enable proactive visual responses so the model can speak when relevant visual changes occur:

  • Python: proactivity=types.ProactivityConfig(proactive_video=True)
  • JS/TS: proactivity: { proactiveVideo: true }
  • Turn coverage requirement: Requires realtime_input_config.turn_coverage to be TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO (default) or TURN_INCLUDES_ALL_INPUT (incompatible with TURN_INCLUDES_ONLY_ACTIVITY).
  • Proactive audio remains permanently enabled (proactive_audio: false returns an error).

Mid-Session Instruction & Tool Updates

Update system_instruction and/or tools dynamically without reconnecting (wire message: BidiGenerateContentContextUpdate):

  • Python: await session.send_context_update(system_instruction=..., tools=...) (pass tools=[] to clear tools)
  • JS/TS: session.sendContextUpdate({ systemInstruction: ..., tools: ... })
  • Prefix cache caveat: Updating system_instruction or tools invalidates the session prefix cache.

Implicit Session Prefix Caching

Responses report implicit session prefix cache hits via usage_metadata.cached_content_token_count and cache_tokens_details (explicit context caching is not supported).


Live Translation (Gemini 4 Live Translate)

The Live API supports real-time, low-latency speech-to-speech translation across 70+ languages (4,900+ language pairs), starting in under 2 seconds (~2x faster than gemini-3.5-live-translate-preview), with improved speaker echo handling. Context window: 16K input (16,384) / 32K output (32,768). Does not support tools, thinking, or text input. For full details, see the Live Translate Guide.

Model

  • gemini-4-live-translate — The recommended translation model for all Live Translate use cases.

Voices & Instructions

  • Default voice (instant voice replication): Omit speech_config to automatically mirror each speaker's tone, pacing, and pitch.
  • Optional extended voice library (2,000+ preset voices): Set speech_config.voice_config.prebuilt_voice_config.voice_name (as a sibling of translation_config inside generationConfig in raw WebSockets—not nested inside translationConfig) for a fixed voice across the session. Always filter preset voices via client.voices.list(type_=["prebuilt"]) / ai.voices.list({ type: ["prebuilt"] }) / GET /v1beta/voices?type=prebuilt.
  • Voices created via the Voices API (POST /v1beta/voices, voice_... / voicekey_...) are NOT supported and fail at setup with 400 INVALID_ARGUMENT.
  • Setup-time system_instruction (optional): Provide custom glossaries, domain terminology, and formality/register guidance at setup time (setup-only; no mid-session updates).

Configuration (TranslationConfig)

To enable translation, specify a TranslationConfig (target_language_code, optional echo_target_language defaulting to false) inside your live session setup (requires a v1beta client):

  • Python SDK: Configure the connection using translation_config (and optional system_instruction / speech_config) on LiveConnectConfig:
    config = types.LiveConnectConfig(
        response_modalities=[types.Modality.AUDIO],
        translation_config=types.TranslationConfig(
            target_language_code="es",  # Target language code (e.g. es, fr, pl)
            echo_target_language=False,
        ),
        # Optional setup-time glossary / register guidance (setup-only)
        system_instruction="Use formal Spanish (usted) and keep product names in English.",
        # Optional fixed preset voice; omit speech_config for default instant voice replication
        # 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(),
    )
    
    async with client.aio.live.connect(model="gemini-4-live-translate", config=config) as session:
        pass
    
  • Raw WebSockets: Place translationConfig (and optional speechConfig as a sibling—not nested inside translationConfig) inside generationConfig:
    {
      "setup": {
        "model": "models/gemini-4-live-translate",
        "generationConfig": {
          "responseModalities": ["AUDIO"],
          "translationConfig": {
            "targetLanguageCode": "es",
            "echoTargetLanguage": false
          },
          "speechConfig": {
            "voiceConfig": {
              "prebuiltVoiceConfig": {
                "voiceName": "Kore"
              }
            }
          }
        }
      }
    }
    

Live Streaming Transcription (Gemini Live Transcribe)

The Live API supports real-time streaming speech-to-text over WebSockets with low-latency interim hypotheses, finalized transcripts, and Hybrid VAD. For full details, see the Live Transcription Guide and Colab Cookbook.

Model

  • gemini-3.5-transcribe-live

Modes

  • smart: cleans up filler words, resolves inline self-corrections, and structures formatting.
  • verbatim (default): exact word-for-word transcript.

Python

config = types.LiveConnectConfig(
    response_modalities=["TEXT"],
    input_audio_transcription=types.AudioTranscriptionConfig(),
)

async with client.aio.live.connect(model="gemini-3.5-transcribe-live", config=config) as session:
    # Stream audio
    await session.send_realtime_input(audio=types.Blob(data=chunk, mime_type="audio/pcm;rate=16000"))
    # Hybrid VAD: notify turn end on client-detected silence for zero latency
    await session.send_realtime_input(audio_stream_end=True)

JavaScript

const session = await ai.live.connect({
  model: 'gemini-3.5-transcribe-live',
  config: {
    responseModalities: ['text'],
    inputAudioTranscription: { mode: 'smart' }
  },
  callbacks: {
    onmessage: (msg) => {
      if (msg.serverContent?.interimInputTranscription) {
        console.log('Interim:', msg.serverContent.interimInputTranscription.text);
      }
      if (msg.serverContent?.inputTranscription) {
        console.log('Final:', msg.serverContent.inputTranscription.text);
      }
    }
  }
});

session.sendRealtimeInput({ audio: { data: chunkBase64, mimeType: 'audio/pcm;rate=16000' } });
session.sendRealtimeInput({ audioStreamEnd: true }); // Hybrid VAD

Raw WebSockets

{
  "setup": {
    "model": "models/gemini-3.5-transcribe-live",
    "generationConfig": {
      "responseModalities": ["TEXT"],
      "speechConfig": {
        "voiceConfig": {}
      }
    },
    "inputAudioTranscription": {
      "mode": "smart"
    }
  }
}

Limitations

  • Response modality — Only TEXT or AUDIO per session, not both. Native audio models output audio (response_modalities=["AUDIO"]); enable output_audio_transcription if you need text transcripts.
  • Audio-only session — 15 min without compression
  • Audio+video session — 2 min without compression
  • Connection lifetime — ~10 min (use session resumption)
  • Context window — gemini-4-live: 128K input (131,072) / 64K output (65,536) tokens; gemini-4-live-translate: 16K input (16,384) / 32K output (32,768) tokens
  • Unsupported tools & features — gemini-4-live does not support Google Maps, Code Execution, URL Context, thinking_budget, XHIGH, designed voices, or explicit context caching (google_search and custom function_declarations are supported). gemini-4-live-translate does not support tools, thinking, text input, or Voices API custom voices.

Upgrading & Migration

For step-by-step migration checklists and protocol deltas when upgrading from gemini-3.8-live, gemini-3.8-live-extended-thinking, gemini-3.5-live-translate-preview, gemini-3.1-flash-live-preview, gemini-2.5-flash-native-audio-*, or gemini-2.0-flash-live-001 to Gemini 4 Live (gemini-4-live) and Gemini 4 Live Translate (gemini-4-live-translate), read references/migration.md.

Best Practices

  1. Always initialize Live API clients with v1beta (http_options={"api_version": "v1beta"} in Python; { httpOptions: { apiVersion: "v1beta" } } in JS/TS) because SDKs >= 3.0.0 default to v1
  2. Use headphones when testing mic audio to prevent echo/self-interruption
  3. Enable context window compression for sessions longer than 15 minutes
  4. Implement session resumption to handle connection resets gracefully
  5. Use ephemeral tokens for client-side deployments — never expose API keys in browsers
  6. Use send_realtime_input for real-time user input (audio, video, text). Use send_client_content with explicit user/model roles to inject context turns mid-stream
  7. Send audioStreamEnd / audio_stream_end (Hybrid VAD) when the mic is paused or user finishes speaking
  8. Clear audio playback queues on interruption signals (interrupted: true)
  9. Process all parts in each server event — events can contain multiple content parts
  10. Monitor server_content.interaction_status (serverContent?.interactionStatus in JS/TS; IN_PROGRESS vs IDLE) when using gemini-4-live with thinking_level set to LOW/MEDIUM/HIGH rather than relying on turn_complete alone

Documentation Lookup

When MCP is Installed (Preferred)

If the search_docs tool (from the Google MCP server) is available, use it as your only documentation source:

  1. Call search_docs with your query
  2. Read the returned documentation
  3. Trust MCP results as source of truth for API details — they are always up-to-date.

[!IMPORTANT] When MCP tools are present, never fetch URLs manually. MCP provides up-to-date, indexed documentation that is more accurate and token-efficient than URL fetching.

When MCP is NOT Installed (Fallback Only)

If no MCP documentation tools are available, fetch from the official docs index:

llms.txt URL: https://aistudio.google.com/llms.txt

This index contains links to all documentation pages in .md format. Use web fetch tools to:

  1. Fetch llms.txt to discover available documentation pages
  2. Fetch specific pages (e.g., https://aistudio.google.com/docs/live-api/session-management.md)

Key Documentation Pages

[!IMPORTANT] Those are not all the documentation pages. Use the llms.txt index to discover available documentation pages

Supported Languages

The Live API supports 70 languages including: English, Spanish, French, German, Italian, Portuguese, Chinese, Japanese, Korean, Hindi, Arabic, Russian, and many more. Native audio models automatically detect and switch languages.