Live API

Live API 支持与 Gemini 建立低延迟的双向语音和视频互动。借助 Live API,您可以为最终用户提供自然的、类似人类的语音对话体验,并能够使用语音指令中断模型的回答。该模型可以处理文本、音频和视频输入,并提供文本和音频输出。

您可以在 Google AI Studio 中试用 Live API。

使用 Live API

本部分介绍了如何将 Live API 与我们的某个 SDK 搭配使用。如需详细了解底层 WebSockets API,请参阅下文中的 WebSockets API 参考文档

发送和接收短信

import asyncio
from google import genai

client = genai.Client(api_key="GEMINI_API_KEY", http_options={'api_version': 'v1alpha'})
model = "gemini-2.0-flash-exp"

config = {"response_modalities": ["TEXT"]}

async def main():
    async with client.aio.live.connect(model=model, config=config) as session:
        while True:
            message = input("User> ")
            if message.lower() == "exit":
                break
            await session.send(input=message, end_of_turn=True)

            async for response in session.receive():
                if response.text is not None:
                    print(response.text, end="")

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

接收音频

以下示例展示了如何接收音频数据并将其写入 .wav 文件。

import asyncio
import wave
from google import genai

client = genai.Client(api_key="GEMINI_API_KEY", http_options={'api_version': 'v1alpha'})
model = "gemini-2.0-flash-exp"

config = {"response_modalities": ["AUDIO"]}

async def main():
    async with client.aio.live.connect(model=model, config=config) as session:
        wf = wave.open("audio.wav", "wb")
        wf.setnchannels(1)
        wf.setsampwidth(2)
        wf.setframerate(24000)

        message = "Hello? Gemini are you there?"
        await session.send(input=message, end_of_turn=True)

        async for idx,response in async_enumerate(session.receive()):
            if response.data is not None:
                wf.writeframes(response.data)

            # Comment this out to print audio data info
            # if response.server_content.model_turn is not None:
            #      print(response.server_content.model_turn.parts[0].inline_data.mime_type)

        wf.close()

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

音频格式

Live API 支持以下音频格式:

  • 输入音频格式:16kHz 小端字节序的原始 16 位 PCM 音频
  • 输出音频格式:24kHz 小端字节序的原始 16 位 PCM 音频

流式传输音频和视频

系统指令

借助系统说明,您可以根据自己的特定需求和使用情形来控制模型的行为。系统说明可以在设置配置中设置,并将在整个会话期间保持有效。

from google.genai import types

config = {
    "system_instruction": types.Content(
        parts=[
            types.Part(
                text="You are a helpful assistant and answer in a friendly tone."
            )
        ]
    ),
    "response_modalities": ["TEXT"],
}

增量内容更新

使用增量更新发送文本输入、建立会话上下文或恢复会话上下文。对于简短的情境,您可以发送精细互动来表示确切的事件顺序:

PythonJSON
from google.genai import types

turns = [
    types.Content(parts=[types.Part(text="What is the capital of France?")], role="user"),
    types.Content(parts=[types.Part(text="Paris")], role="model")
]
await session.send(input=types.LiveClientContent(turns=turns))

turns = [types.Content(parts=[types.Part(text="What is the capital of Germany?")], role="user")]
await session.send(input=types.LiveClientContent(turns=turns, turn_complete=True))
{
  "clientContent": {
    "turns": [
      {
        "parts":[
          {
            "text": ""
          }
        ],
        "role":"user"
      },
      {
        "parts":[
          {
            "text": ""
          }
        ],
        "role":"model"
      }
    ],
    "turnComplete": true
  }
}

对于较长的上下文,建议提供单个消息摘要,以便释放上下文窗口以供后续互动。

更改语音

Live API 支持以下语音:Aoede、Charon、Fenrir、Kore 和 Puck。

如需指定语音,请在会话配置中在 speechConfig 对象中设置语音名称:

PythonJSON
from google.genai import types

config = types.LiveConnectConfig(
    response_modalities=["AUDIO"],
    speech_config=types.SpeechConfig(
        voice_config=types.VoiceConfig(
            prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name="Kore")
        )
    )
)
{
  "voiceConfig": {
    "prebuiltVoiceConfig": {
      "voiceName": "Kore"
    }
  }
}

使用函数调用

您可以使用 Live API 定义工具。如需详细了解函数调用,请参阅函数调用教程

必须在会话配置中定义工具:

config = types.LiveConnectConfig(
    response_modalities=["TEXT"],
    tools=[set_light_values]
)

async with client.aio.live.connect(model=model, config=config) as session:
    await session.send(input="Turn the lights down to a romantic level", end_of_turn=True)

    async for response in session.receive():
        print(response.tool_call)

从单个提示中,模型可以生成多个函数调用以及串联其输出所需的代码。此代码在沙盒环境中执行,会生成后续的 BidiGenerateContentToolCall 消息。执行会暂停,直到每个函数调用的结果都可用,以确保顺序处理。

客户端应响应 BidiGenerateContentToolResponse

音频输入和音频输出会对模型使用函数调用功能的能力产生负面影响。

处理中断

用户可以随时中断模型的输出。当语音活动检测 (VAD) 检测到中断时,系统会取消并舍弃正在生成的音频。只有已发送到客户端的信息会保留在会话历史记录中。然后,服务器会发送 BidiGenerateContentServerContent 消息来报告中断。

此外,Gemini 服务器会舍弃所有待处理的函数调用,并发送包含已取消调用的 ID 的 BidiGenerateContentServerContent 消息。

async for response in session.receive():
    if response.server_content.interrupted is not None:
        # The generation was interrupted

限制

在规划项目时,请考虑 Live API 和 Gemini 2.0 的以下限制。

客户端身份验证

Live API 仅提供服务器到服务器身份验证,不建议直接供客户端使用。客户端输入应通过中间应用服务器路由,以便通过 Live API 进行安全身份验证。

对话记录

虽然该模型会跟踪会话内的互动,但不会存储对话记录。会话结束后,系统会清除相应上下文。

为了恢复之前的会话或向模型提供用户互动的历史背景信息,应用应维护自己的对话日志,并在新的会话开始时使用 BidiGenerateContentClientContent 消息发送此信息。

会话时长上限

会话时长:音频不超过 15 分钟,音频和视频不超过 2 分钟。当会话时长超出限制时,连接会终止。

模型还受上下文大小的限制。在视频和音频流中发送大量内容可能会导致会话提前终止。

语音活动检测 (VAD)

该模型会自动对连续的音频输入流执行语音活动检测 (VAD)。VAD 始终处于启用状态,其参数不可配置。

token 计数

不支持 token 计数。

速率限制

以下速率限制适用:

  • 每个 API 密钥 3 个并发会话
  • 每分钟 400 万个 token

WebSockets API 参考文档

Live API 是一种使用 WebSockets 的有状态 API。在本部分中,您将详细了解 WebSockets API。

会话

WebSocket 连接会在客户端和 Gemini 服务器之间建立会话。客户端发起新连接后,会话可以与服务器交换消息,以执行以下操作:

  • 向 Gemini 服务器发送文本、音频或视频。
  • 接收来自 Gemini 服务器的音频、文本或函数调用请求。

连接后的初始消息会设置会话配置,其中包括模型、生成参数、系统说明和工具。

请参阅以下示例配置。请注意,SDK 中的名称大小写可能有所不同。您可以点击此处查看 Python SDK 配置选项


{
 
"model": string,
 
"generationConfig": {
   
"candidateCount": integer,
   
"maxOutputTokens": integer,
   
"temperature": number,
   
"topP": number,
   
"topK": integer,
   
"presencePenalty": number,
   
"frequencyPenalty": number,
   
"responseModalities": [string],
   
"speechConfig": object
 
},
 
"systemInstruction": string,
 
"tools": [object]
}

发送消息

如需通过 WebSocket 连接交换消息,客户端必须通过打开的 WebSocket 连接发送 JSON 对象。JSON 对象必须包含以下对象集中的恰好一个字段:


{
 
"setup": BidiGenerateContentSetup,
 
"clientContent": BidiGenerateContentClientContent,
 
"realtimeInput": BidiGenerateContentRealtimeInput,
 
"toolResponse": BidiGenerateContentToolResponse
}

支持的客户端消息

请参阅下表中支持的客户端消息:

消息 说明
BidiGenerateContentSetup 要在第一条消息中发送的会话配置
BidiGenerateContentClientContent 从客户端传送的当前对话的增量内容更新
BidiGenerateContentRealtimeInput 实时音频或视频输入
BidiGenerateContentToolResponse 对从服务器收到的 ToolCallMessage 的响应

接收消息

如需接收来自 Gemini 的消息,请监听 WebSocket“message”事件,然后根据支持的服务器消息的定义解析结果。

请参阅以下内容:

async with client.aio.live.connect(model='...', config=config) as session:
    await session.send(input='Hello world!', end_of_turn=True)
    async for message in session.receive():
        print(message)

服务器消息将包含以下对象集中的恰好一个字段:


{
 
"setupComplete": BidiGenerateContentSetupComplete,
 
"serverContent": BidiGenerateContentServerContent,
 
"toolCall": BidiGenerateContentToolCall,
 
"toolCallCancellation": BidiGenerateContentToolCallCancellation
}

支持的服务器消息

请参阅下表中支持的服务器消息:

消息 说明
BidiGenerateContentSetupComplete 来自客户端的 BidiGenerateContentSetup 消息,在设置完成时发送
BidiGenerateContentServerContent 模型为客户端消息生成的内容
BidiGenerateContentToolCall 请求客户端运行函数调用并返回包含匹配 ID 的响应
BidiGenerateContentToolCallCancellation 当函数调用因用户中断模型输出而被取消时发送

消息和事件

BidiGenerateContentClientContent

对客户端传送的当前对话进行增量更新。此处的所有内容都会无条件附加到对话历史记录中,并用作向模型发出的提示的一部分,以便模型生成内容。

此处显示消息会中断任何当前的模型生成。

字段
turns[]

Content

可选。附加到与模型当前对话的内容。

对于单轮查询,这是单个实例。对于多轮查询,这是包含对话历史记录和最新请求的重复字段。

turn_complete

bool

可选。如果为 true,则表示服务器内容生成应从当前累积的提示开始。否则,服务器会等待其他消息,然后再开始生成。

BidiGenerateContentRealtimeInput

实时发送的用户输入。

这与 BidiGenerateContentClientContent 在几个方面有所不同:

  • 可以连续发送,不会中断模型生成。
  • 如果需要混合在 BidiGenerateContentClientContentBidiGenerateContentRealtimeInput 中交错的数据,服务器会尝试进行优化以获得最佳响应,但无法保证。
  • 未明确指定转换结束时间,而是从用户活动(例如语音结束)派生而来。
  • 即使在对话结束之前,系统也会增量处理数据,以便优化模型快速开始回答。
  • 始终假定为用户的输入(无法用于填充对话记录)。可以连续发送,不会中断。该模型会自动检测用户语音的开头和结尾,并相应地开始或终止流式传输响应。系统会在数据到达时逐步进行处理,从而最大限度地减少延迟时间。
字段
media_chunks[]

Blob

可选。媒体输入的内嵌字节数据。

BidiGenerateContentServerContent

模型为响应客户端消息而生成的增量服务器更新。

内容会尽快生成,但不是实时生成。客户端可以选择缓冲并实时播放。

字段
turn_complete

bool

仅限输出。如果为 true,则表示模型已生成完毕。系统仅会在响应其他客户端消息时开始生成。可与 content 一起设置,表示 content 是轮次中的最后一个。

interrupted

bool

仅限输出。如果为 true,则表示客户端消息中断了当前的模型生成。如果客户端正在实时播放内容,则表示可以停止并清空当前的播放队列。

grounding_metadata

GroundingMetadata

仅限输出。为生成的内容提供元数据依据。

model_turn

Content

仅限输出。模型在与用户的当前对话中生成的内容。

BidiGenerateContentSetup

要在第一条(也是唯一一条)客户端消息中发送的消息。包含将在流式传输会话期间应用的配置。

客户端应先等待 BidiGenerateContentSetupComplete 消息,然后才能发送任何其他消息。

字段
model

string

必需。模型的资源名称。此 ID 将用作模型的 ID。

格式:models/{model}

generation_config

GenerationConfig

可选。生成配置。

不支持以下字段:

  • responseLogprobs
  • responseMimeType
  • logprobs
  • responseSchema
  • stopSequence
  • routingConfig
  • audioTimestamp
system_instruction

Content

可选。用户为模型提供的系统说明。

注意:部分中只能使用文本。每个部分的内容将在单独的段落中。

tools[]

Tool

可选。模型可能用于生成下一个回答的 Tools 列表。

Tool 是一段代码,可让系统与外部系统进行交互,以在模型知识和范围之外执行操作或一组操作。

BidiGenerateContentSetupComplete

此类型没有字段。

作为对客户端发送的 BidiGenerateContentSetup 消息的响应而发送。

BidiGenerateContentToolCall

请求客户端执行函数调用,并返回包含匹配 id 的响应。

字段
function_calls[]

FunctionCall

仅限输出。要执行的函数调用。

BidiGenerateContentToolCallCancellation

向客户端发送通知,告知之前使用指定 id 签发的 ToolCallMessage 不应执行,应予以取消。如果这些工具调用产生了副作用,客户端可能会尝试撤消工具调用。只有在客户端中断服务器转换时,才会出现此消息。

字段
ids[]

string

仅限输出。要取消的工具调用的 ID。

BidiGenerateContentToolResponse

客户端针对从服务器收到的 ToolCall 生成的响应。各个 FunctionResponse 对象会通过 id 字段与相应的 FunctionCall 对象进行匹配。

请注意,在单个调用和服务器流式 GenerateContent API 中,函数调用是通过交换 Content 部分进行的,而在双向 GenerateContent API 中,函数调用是通过这组专用消息进行的。

字段
function_responses[]

FunctionResponse

可选。对函数调用的响应。

详细了解常见类型

如需详细了解常用的 API 资源类型 BlobContentFunctionCallFunctionResponseGenerationConfigGroundingMetadataTool,请参阅生成内容

第三方集成

对于网站和移动应用部署,您可以探索以下选项: