Live API では、セッションとは、同じ接続を介して入力と出力が継続的にストリーミングされる永続接続を指します(仕組みの詳細をご覧ください)。この独自のセッション設計により、低レイテンシが可能になり、独自の機能をサポートできますが、セッション時間の制限や早期終了などの課題も生じます。このガイドでは、Live API の使用時に発生する可能性のあるセッション管理の課題を克服するための戦略について説明します。
セッションの存続期間
圧縮なしの場合、音声のみのセッションは 15 分に制限され、音声と動画のセッションは 2 分に制限されます。この上限を超えるとセッション(および接続)が終了しますが、コンテキスト ウィンドウ圧縮を使用してセッションを無制限に延長できます。
接続の存続期間も 10 分程度に制限されています。接続が終了すると、セッションも終了します。この場合、セッションの再開を使用して、複数の接続でアクティブなままになるように 1 つのセッションを構成できます。また、接続が終了する前に 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(api_key="GEMINI_API_KEY")
model = "gemini-2.0-flash-live-001"
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({ apiKey: "GEMINI_API_KEY" });
const model = 'gemini-2.0-flash-live-001';
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 メッセージを送信します。このメッセージには、残り時間を示す timeLeft が含まれており、接続が ABORTED として終了する前に追加のアクションを実行できます。
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 クックブックをご覧ください。