Get started with Gemini Live API using the Google GenAI SDK

Gemini Live API 支持与 Gemini 模型进行实时双向互动,并支持音频、视频和文本输入以及原生音频输出。本指南介绍了如何在服务器上使用 Google GenAI SDK 与 API 集成。

概览

Gemini Live API 使用 WebSocket 进行实时通信。google-genai SDK 提供了一个高级异步接口,用于管理这些连接。

主要概念:

  • 会话:与模型的持久连接。
  • 配置:设置模态(音频/文本)、语音和系统指令。
  • 实时输入:以 blob 形式发送音频和视频帧。

连接到 Live API

使用 API 密钥启动 Live API 会话:

Python

import asyncio
from google import genai

client = genai.Client(api_key="YOUR_API_KEY")

model = "gemini-2.5-flash-native-audio-preview-12-2025"
config = {"response_modalities": ["AUDIO"]}

async def main():
    async with client.aio.live.connect(model=model, config=config) as session:
        print("Session started")
        # Send content...

if __name__ == "__main__":
    asyncio.run(main())

JavaScript

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

const ai = new GoogleGenAI({ apiKey: "YOUR_API_KEY"});
const model = 'gemini-2.5-flash-native-audio-preview-12-2025';
const config = { responseModalities: [Modality.AUDIO] };

async function main() {

  const session = await ai.live.connect({
    model: model,
    callbacks: {
      onopen: function () {
        console.debug('Opened');
      },
      onmessage: function (message) {
        console.debug(message);
      },
      onerror: function (e) {
        console.debug('Error:', e.message);
      },
      onclose: function (e) {
        console.debug('Close:', e.reason);
      },
    },
    config: config,
  });

  console.debug("Session started");
  // Send content...

  session.close();
}

main();

正在发送短信

可以使用 send_realtime_input (Python) 或 sendRealtimeInput (JavaScript) 发送文本。

Python

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

JavaScript

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

发送音频

音频需要以原始 PCM 数据(原始 16 位 PCM 音频,16kHz,小端序)的形式发送。

Python

# Assuming 'chunk' is your raw PCM audio bytes
await session.send_realtime_input(
    audio=types.Blob(
        data=chunk,
        mime_type="audio/pcm;rate=16000"
    )
)

JavaScript

// Assuming 'chunk' is a Buffer of raw PCM audio
session.sendRealtimeInput({
  audio: {
    data: chunk.toString('base64'),
    mimeType: 'audio/pcm;rate=16000'
  }
});

如需查看如何从客户端设备(例如浏览器)获取音频的示例,请参阅 GitHub 上的端到端示例。

正在发送视频

视频帧以单独图片的形式发送(例如,JPEG 或 PNG)的帧速率(最高为每秒 1 帧)。

Python

# Assuming 'frame' is your JPEG-encoded image bytes
await session.send_realtime_input(
    video=types.Blob(
        data=frame,
        mime_type="image/jpeg"
    )
)

JavaScript

// Assuming 'frame' is a Buffer of JPEG-encoded image data
session.sendRealtimeInput({
  video: {
    data: frame.toString('base64'),
    mimeType: 'image/jpeg'
  }
});

如需查看如何从客户端设备(例如浏览器)获取视频的示例,请参阅 GitHub 上的端到端示例。

接收音频

模型以数据块的形式返回音频回答。

Python

async for response in session.receive():
    if response.server_content and response.server_content.model_turn:
        for part in response.server_content.model_turn.parts:
            if part.inline_data:
                audio_data = part.inline_data.data
                # Process or play the audio data

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;
      // Process or play audioData (base64 encoded string)
    }
  }
}

如需了解如何在服务器上接收音频以及如何在浏览器中播放音频,请参阅 GitHub 上的示例应用。

正在接收短信

服务器内容中包含用户输入和模型输出的转写内容。

Python

async for response in session.receive():
    content = response.server_content
    if content:
        if content.input_transcription:
            print(f"User: {content.input_transcription.text}")
        if content.output_transcription:
            print(f"Gemini: {content.output_transcription.text}")

JavaScript

// Inside the onmessage callback
const content = response.serverContent;
if (content?.inputTranscription) {
  console.log('User:', content.inputTranscription.text);
}
if (content?.outputTranscription) {
  console.log('Gemini:', content.outputTranscription.text);
}

处理工具调用

该 API 支持工具调用(函数调用)。当模型请求进行工具调用时,您必须执行相应函数并将响应发送回去。

Python

async for response in session.receive():
    if response.tool_call:
        function_responses = []
        for fc in response.tool_call.function_calls:
            # 1. Execute the function locally
            result = my_tool_function(**fc.args)

            # 2. Prepare the response
            function_responses.append(types.FunctionResponse(
                name=fc.name,
                id=fc.id,
                response={"result": result}
            ))

        # 3. Send the tool response back to the session
        await session.send_tool_response(function_responses=function_responses)

JavaScript

// Inside the onmessage callback
if (response.toolCall) {
  const functionResponses = [];
  for (const fc of response.toolCall.functionCalls) {
    const result = myToolFunction(fc.args);
    functionResponses.push({
      name: fc.name,
      id: fc.id,
      response: { result }
    });
  }
  session.sendToolResponse({ functionResponses });
}

后续步骤

  • 如需了解主要功能和配置(包括语音活动检测和原生音频功能),请参阅完整的 Live API 功能指南。
  • 请参阅工具使用指南,了解如何将 Live API 与工具和函数调用集成。
  • 如需管理长时间运行的对话,请参阅会话管理指南。
  • 请参阅临时令牌指南,了解如何在客户端到服务器应用中进行安全身份验证。
  • 如需详细了解底层 WebSockets API,请参阅 WebSockets API 参考文档