在 Live API 中,工作階段是指持續連線,在同一連線中持續串流輸入和輸出 (進一步瞭解運作方式)。這種獨特的工作階段設計可降低延遲並支援獨特功能,但也可能帶來挑戰,例如工作階段時間限制和提早終止。本指南將說明如何克服使用 Live API 時可能發生的工作階段管理問題。
工作階段生命週期
如未壓縮,僅音訊的會話時間上限為 15 分鐘,音訊/視訊會話時間上限為 2 分鐘。如果超過這些限制,系統會終止工作階段 (並因此終止連線),但您可以使用內容視窗壓縮功能,將工作階段延長至無限的時間。
連線的生命週期也受到限制,大約為 10 分鐘。連線終止時,工作階段也會終止。在這種情況下,您可以使用工作階段恢復功能,將單一工作階段設定為在多個連線中保持有效。在連線結束前,您也會收到GoAway 訊息,方便您採取進一步行動。
脈絡窗口壓縮
如要啟用較長的工作階段,並避免連線突然中斷,您可以將 contextWindowCompression 欄位設為工作階段設定的一部分,啟用內容視窗壓縮功能。
在 ContextWindowCompressionConfig 中,您可以設定滑動視窗機制和觸發壓縮功能的符記數量。
Python
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(),
)
),
)
JavaScript
const config = {
responseModalities: [Modality.AUDIO],
contextWindowCompression: { slidingWindow: {} }
};
繼續工作階段
如要避免在伺服器定期重設 WebSocket 連線時終止工作階段,請在設定配置中設定 sessionResumption 欄位。
傳遞這項設定會導致伺服器傳送 SessionResumptionUpdate 訊息,可用於將上一個恢復權杖傳遞為後續連線的 SessionResumptionConfig.handle
,藉此恢復工作階段。
Python
import asyncio
from google import genai
from google.genai import types
client = genai.Client()
model = "gemini-live-2.5-flash-preview"
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())
JavaScript
import { GoogleGenAI, Modality } from '@google/genai';
const ai = new GoogleGenAI({});
const model = 'gemini-live-2.5-flash-preview';
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.TEXT],
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));
}
main();
在工作階段中斷前接收訊息
伺服器會傳送「GoAway」GoAway訊息,表示目前的連線即將終止。這則訊息包含 timeLeft,可顯示剩餘時間,並讓您在連線因「已中止」而終止前採取進一步行動。
Python
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)
JavaScript
const turns = await handleTurn();
for (const turn of turns) {
if (turn.goAway) {
console.debug('Time left: %s\n', turn.goAway.timeLeft);
}
}
產生完成後收到訊息
伺服器會傳送 generationComplete 訊息,表示模型已完成產生回應。
Python
async for response in session.receive():
if response.server_content.generation_complete is True:
# The generation is complete
JavaScript
const turns = await handleTurn();
for (const turn of turns) {
if (turn.serverContent && turn.serverContent.generationComplete) {
// The generation is complete
}
}
後續步驟
如要進一步瞭解如何使用 Live API,請參閱完整的功能指南、工具使用頁面或 Live API 食譜。