Gemini 中文指南
获取 API 密钥 ↗

使用 Google GenAI SDK 快速入门 Gemini Live API

↓ 下载 MarkdownInteractions API

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

尝试 Google AI Studio 中的 Live API

从 GitHub 克隆示例应用程序

使用编码智能体技巧

概览 #

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", http_options={"api_version": "v1beta"})

model = "gemini-3.8-live"
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())

发送文本 #

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

python
await session.send_realtime_input(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"
    )
)

有关如何从客户端设备(例如浏览器)获取音频的示例,请参阅上的端到端示例 GitHub.

发送视频 #

视频帧以特定帧速率(每秒最大 1 帧)作为单独图像(例如 JPEG 或 PNG)发送。

python
# Assuming 'frame' is your JPEG-encoded image bytes
await session.send_realtime_input(
    video=types.Blob(
        data=frame,
        mime_type="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

请参阅 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}")

处理工具调用 #

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)

后续步骤 #

搜索标题、API 名称或正文内容