Live API 会话管理
在 Live API 中,会话是指持久连接,其中输入和输出通过同一连接连续流式传输(了解更多信息 它是如何运作的)。这种独特的会话设计可实现低延迟并支持独特的功能,但也会带来挑战,例如会话时间限制和提前终止。本指南涵盖了克服使用 Live API 时可能出现的会话管理挑战的策略。
会话生命周期 #
如果不进行压缩,纯音频会话将限制为 15 分钟,音频-视频会话将限制为 2 分钟。超过这些限制将终止会话(并因此终止连接),但您可以使用 上下文窗口压缩 将会话延长到无限的时间。
连接的生命周期也受到限制,约为 10 分钟。当连接终止时,会话也会终止。在这种情况下,您可以使用以下命令将单个会话配置为在多个连接上保持活动状态 会话恢复。您还将收到一个 离开消息 在连接结束之前,您可以采取进一步的操作。
上下文窗口压缩 #
要启用更长的会话并避免连接突然终止,您可以通过设置来启用上下文窗口压缩 上下文窗口压缩 字段作为会话配置的一部分。
在 上下文窗口压缩配置,您可以配置一个 滑动窗口机制 和 token 数量 从而触发压缩。
from google.genai import types
config = types.LiveConnectConfig(
response_modalities=["AUDIO"],
context_window_compression=(
# Configures compression with default parameters.
types.ContextWindowCompressionConfig(
sliding_window=types.SlidingWindow(),
)
),
)
const config = {
responseModalities: [Modality.AUDIO],
contextWindowCompression: { slidingWindow: {} }
};
会话恢复 #
为了防止服务器定期重置 WebSocket 连接时会话终止,请配置 会话恢复 领域内的 设置配置.
传递此配置会导致服务器发送 会话恢复更新 消息,可用于通过传递上次恢复 token 作为恢复会话 SessionResumptionConfig.handle 的后续连接。
恢复 token 在最后一次会话终止后的 2 小时内有效。
import asyncio
from google import genai
from google.genai import types
client = genai.Client(http_options={"api_version": "v1beta"})
model = "gemini-3.8-live"
async def main():
print(f"Connecting to the service with handle {previous_session_handle}...")
async with client.aio.live.connect(
model=model,
config=types.LiveConnectConfig(
response_modalities=["AUDIO"],
session_resumption=types.SessionResumptionConfig(
# The handle of the session to resume is passed here,
# or else None to start a new session.
handle=previous_session_handle
),
),
) as session:
while True:
await session.send_client_content(
turns=types.Content(
role="user", parts=[types.Part(text="Hello world!")]
)
)
async for message in session.receive():
# Periodically, the server will send update messages that may
# contain a handle for the current state of the session.
if message.session_resumption_update:
update = message.session_resumption_update
if update.resumable and update.new_handle:
# The handle should be retained and linked to the session.
return update.new_handle
# For the purposes of this example, placeholder input is continually fed
# to the model. In non-sample code, the model inputs would come from
# the user.
if message.server_content and message.server_content.turn_complete:
break
if __name__ == "__main__":
asyncio.run(main())
import { GoogleGenAI, Modality } from '@google/genai';
const ai = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });
const model = 'gemini-3.8-live';
async function live() {
const responseQueue = [];
async function waitMessage() {
let done = false;
let message = undefined;
while (!done) {
message = responseQueue.shift();
if (message) {
done = true;
} else {
await new Promise((resolve) => setTimeout(resolve, 100));
}
}
return message;
}
async function handleTurn() {
const turns = [];
let done = false;
while (!done) {
const message = await waitMessage();
turns.push(message);
if (message.serverContent && message.serverContent.turnComplete) {
done = true;
}
}
return turns;
}
console.debug('Connecting to the service with handle %s...', previousSessionHandle)
const session = await ai.live.connect({
model: model,
callbacks: {
onopen: function () {
console.debug('Opened');
},
onmessage: function (message) {
responseQueue.push(message);
},
onerror: function (e) {
console.debug('Error:', e.message);
},
onclose: function (e) {
console.debug('Close:', e.reason);
},
},
config: {
responseModalities: [Modality.AUDIO],
sessionResumption: { handle: previousSessionHandle }
// The handle of the session to resume is passed here, or else null to start a new session.
}
});
const inputTurns = 'Hello how are you?';
session.sendClientContent({ turns: inputTurns });
const turns = await handleTurn();
for (const turn of turns) {
if (turn.sessionResumptionUpdate) {
if (turn.sessionResumptionUpdate.resumable && turn.sessionResumptionUpdate.newHandle) {
let newHandle = turn.sessionResumptionUpdate.newHandle
// ...Store newHandle and start new session with this handle here
}
}
}
session.close();
}
async function main() {
await live().catch((e) => console.error('got error', e));
}
await main();
在会话断开之前接收消息 #
服务器发送一个 走开 表示当前连接即将终止的消息。该消息包括 剩余时间,指示剩余时间,让您在连接因 ABORTED 终止之前采取进一步操作。
async for response in session.receive():
if response.go_away is not None:
# The connection will soon be terminated
print(response.go_away.time_left)
const turns = await handleTurn();
for (const turn of turns) {
if (turn.goAway) {
console.debug('Time left: %s\n', turn.goAway.timeLeft);
}
}
生成完成后收到消息 #
服务器发送一个 生成完成 表示模型已完成生成响应的消息。
async for response in session.receive():
if response.server_content.generation_complete is True:
# The generation is complete
const turns = await handleTurn();
for (const turn of turns) {
if (turn.serverContent && turn.serverContent.generationComplete) {
// The generation is complete
}
}
后续步骤 #
探索更多全面使用 Live API 的方法 功能 指南, 工具使用 页面,或 Live API食谱.