در Live API، یک جلسه به یک اتصال دائمی اشاره دارد که در آن ورودی و خروجی به طور مداوم از طریق یک اتصال پخش میشوند (در مورد نحوه عملکرد آن بیشتر بخوانید). این طراحی منحصربهفرد جلسه تأخیر کم را امکانپذیر میکند و از ویژگیهای منحصربهفرد پشتیبانی میکند، اما میتواند چالشهایی مانند محدودیتهای زمانی جلسه و خاتمه زودهنگام را نیز ایجاد کند. این راهنما استراتژیهایی را برای غلبه بر چالشهای مدیریت جلسه که ممکن است هنگام استفاده از Live API ایجاد شود، پوشش میدهد.
طول عمر جلسه
بدون فشرده سازی، جلسات فقط صوتی به 15 دقیقه و جلسات صوتی و تصویری به 2 دقیقه محدود می شود. فراتر از این محدودیتها، جلسه (و در نتیجه، اتصال) خاتمه مییابد، اما میتوانید از فشردهسازی پنجره زمینه برای گسترش جلسات به مدت نامحدود استفاده کنید.
طول عمر اتصال نیز به حدود 10 دقیقه محدود شده است. هنگامی که اتصال قطع می شود، جلسه نیز خاتمه می یابد. در این مورد، میتوانید یک جلسه را برای فعال ماندن در چندین اتصال با استفاده از از سرگیری جلسه پیکربندی کنید. همچنین قبل از پایان اتصال یک پیام GoAway دریافت خواهید کرد که به شما امکان می دهد اقدامات بیشتری انجام دهید.
فشرده سازی پنجره زمینه
برای فعال کردن جلسات طولانی تر و جلوگیری از قطع ناگهانی اتصال، می توانید فشرده سازی پنجره زمینه را با تنظیم فیلد contextWindowCompression به عنوان بخشی از پیکربندی جلسه فعال کنید.
در ContextWindowCompressionConfig ، میتوانید مکانیزم پنجره کشویی و تعداد نشانههایی را که فشردهسازی را آغاز میکنند، پیکربندی کنید.
پایتون
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 را بازنشانی می کند، فیلد sessionResumption را در پیکربندی راه اندازی پیکربندی کنید.
عبور از این پیکربندی باعث میشود سرور پیامهای SessionResumptionUpdate را ارسال کند، که میتوان با ارسال آخرین نشانه Resumption به عنوان SessionResumptionConfig.handle
از اتصال بعدی، جلسه را از سر گرفت.
پایتون
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())
جاوا اسکریپت
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 قطع شود، اقدامات بیشتری انجام دهید.
پایتون
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);
}
}
دریافت پیام پس از تکمیل نسل
سرور یک پیام GenerationComplete می فرستد که سیگنال می دهد که مدل تولید پاسخ را به پایان رسانده است.
پایتون
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 کاوش کنید.