ניהול סשנים ב-Live API

Gemini Live API מעבד זרמים רציפים של אודיו או טקסט שנקראים סשנים. אתם יכולים לנהל את מחזור החיים של הסשן, מהלחיצה הראשונית ועד לסיום תקין.

מגבלות על סשנים

במקרה של Live API, סשן הוא חיבור מתמשך שבו הקלט והפלט מוזרמים ברציפות דרך החיבור.

אם הסשן חורג מכל אחת מהמגבלות הבאות, החיבור מסתיים. עם זאת, Live API מספק כמה אפשרויות (מפורטות בהמשך) לטיפול במגבלות שקשורות לסשן.

  • חלון ההקשר של הסשן מוגבל ל-128 אלף טוקנים.

    בגלל המגבלה הזו של חלון ההקשר, אלה אורכי הסשנים המקסימליים המשוערים על סמך שיטות הקלט:

    • הזמן המקסימלי לשיחות עם קלט אודיו בלבד הוא 15 דקות.
    • הקלט של וידאו ואודיו מוגבל ל-2 דקות.
  • אורך החיבור מוגבל לכ-10 דקות.

    תקבלו התראה על סיום השיתוף כ-60 שניות לפני שהשיתוף יסתיים.

ריכזנו כאן כמה אפשרויות לטיפול במגבלות שקשורות להפעלת המערכת:

  • דחיסת חלון ההקשר של הסשן כך שהשרת ישמור אוטומטית על גודל ההקשר במסגרת המגבלה.

  • המשך סשן כדי לא לאבד את ההקשר של השיחה במהלך ניתוקים קצרים מהרשת או אחרי קבלת התראה על עזיבה.

התחלת סשן

מדריך מפורט לתחילת העבודה עם Live API זמין כאן. במדריך מופיע קטע קוד מלא שמראה איך להתחיל סשן.

עדכון באמצע הסשן

מודלים של Live API תומכים ביכולות המתקדמות הבאות של עדכונים באמצע הסשן:

הוספת עדכוני תוכן מצטברים

אפשר להוסיף עדכונים מצטברים במהלך סשן פעיל. אפשר להשתמש בזה כדי לשלוח קלט טקסט, ליצור הקשר של סשן או לשחזר הקשר של סשן.

  • בהקשרים ארוכים יותר, מומלץ לספק סיכום של ההודעה כדי לפנות מקום בחלון ההקשר לאינטראקציות הבאות.

  • במקרים של הקשרים קצרים, אפשר לשלוח אינטראקציות של תור אחר תור כדי לייצג את רצף האירועים המדויק, כמו בקטע הקוד שלמטה.

Swift

// Define initial turns (history/context).
let turns: [ModelContent] = [
  ModelContent(role: "user", parts: [TextPart("What is the capital of France?")]),
  ModelContent(role: "model", parts: [TextPart("Paris")]),
]

// Send history, keeping the conversational turn OPEN (false).
await session.sendContent(turns, turnComplete: false)

// Define the new user query.
let newTurn: [ModelContent] = [
  ModelContent(role: "user", parts: [TextPart("What is the capital of Germany?")]),
]

// Send the final query, CLOSING the turn (true) to trigger the model response.
await session.sendContent(newTurn, turnComplete: true)

Kotlin

Not yet supported for Android apps - check back soon!

Java

Not yet supported for Android apps - check back soon!

Web

const turns = [{ text: "Hello from the user!" }];

await session.send(
  turns,
  false // turnComplete: false
);

console.log("Sent history. Waiting for next input...");

// Define the new user query.
const newTurn [{ text: "And what is the capital of Germany?" }];

// Send the final query, CLOSING the turn (true) to trigger the model response.
await session.send(
    newTurn,
    true // turnComplete: true
);
console.log("Sent final query. Model response expected now.");

Dart

// Define initial turns (history/context).
final List turns = [
  Content(
    "user",
    [Part.text("What is the capital of France?")],
  ),
  Content(
    "model",
    [Part.text("Paris")],
  ),
];

// Send history, keeping the conversational turn OPEN (false).
await session.send(
  input: turns,
  turnComplete: false,
);

// Define the new user query.
final List newTurn = [
  Content(
    "user",
    [Part.text("What is the capital of Germany?")],
  ),
];

// Send the final query, CLOSING the turn (true) to trigger the model response.
await session.send(
  input: newTurn,
  turnComplete: true,
);

Unity

// Define initial turns (history/context).
List turns = new List {
    new ModelContent("user", new ModelContent.TextPart("What is the capital of France?") ),
    new ModelContent("model", new ModelContent.TextPart("Paris") ),
};

// Send history, keeping the conversational turn OPEN (false).
foreach (ModelContent turn in turns)
{
    await session.SendAsync(
        content: turn,
        turnComplete: false
    );
}

// Define the new user query.
ModelContent newTurn = ModelContent.Text("What is the capital of Germany?");

// Send the final query, CLOSING the turn (true) to trigger the model response.
await session.SendAsync(
    content: newTurn,
    turnComplete: true
);

עדכון הוראות המערכת באמצע הסשן

האפשרות הזו זמינה רק כשמשתמשים ב-Vertex AI Gemini API כספק ה-API.

אפשר לעדכן את ההוראות למערכת במהלך סשן פעיל. אפשר להשתמש בה כדי להתאים את התשובות של המודל, למשל כדי לשנות את שפת התשובה או את הטון שלה.

כדי לעדכן את הוראות המערכת באמצע השיחה, אפשר לשלוח תוכן טקסט עם התפקיד system. ההוראות המעודכנות למערכת יישארו בתוקף למשך שארית הסשן.

Swift

await session.sendContent(
  [ModelContent(
    role: "system",
    parts: [TextPart("new system instruction")]
  )],
  turnComplete: false
)

Kotlin

Not yet supported for Android apps - check back soon!

Java

Not yet supported for Android apps - check back soon!

Web

Not yet supported for Web apps - check back soon!

Dart

try {
  await _session.send(
    input: Content(
      'system',
      [Part.text('new system instruction')],
    ),
    turnComplete: false,
  );
} catch (e) {
  print('Failed to update system instructions: $e');
}

Unity

try
{
    await session.SendAsync(
        content: new ModelContent(
            "system",
            new ModelContent.TextPart("new system instruction")
        ),
        turnComplete: false
    );
}
catch (Exception e)
{
    Debug.LogError($"Failed to update system instructions: {e.Message}");
}

דחיסת חלון ההקשר

לוחצים על הספק Gemini API כדי לראות בדף הזה תוכן וקוד שספציפיים לספק.

Live API חלון ההקשר של הסשן מאחסן נתונים שמוזרמים בזמן אמת (25 טוקנים לשנייה (TPS) לאודיו ו-258 טוקנים לשנייה לווידאו) וגם תוכן אחר, כולל קלט טקסט ופלט של המודל. לכל המודלים של Live API יש מגבלת טוקנים של 128 אלף בחלון ההקשר של הסשן.

כברירת מחדל, בגלל המגבלה הזו של חלון ההקשר, אלה אורכי הסשנים המקסימליים המשוערים על סמך אופנויות הקלט:

  • הזמן המקסימלי לשיחות עם קלט אודיו בלבד הוא 15 דקות.
  • הקלט של וידאו ואודיו מוגבל ל-2 דקות.

בסשנים ארוכים, ככל שהשיחה מתקדמת, מצטברת היסטוריה של טוקנים של אודיו או וידאו. אם ההיסטוריה הזו חורגת מהמגבלה של המודל, יכול להיות שהמודל יפיק הזיות, יפעל לאט יותר או שהסשן יסתיים בכפייה.

כדי להאריך את משך הסשנים, אפשר להפעיל דחיסה של חלון ההקשר על ידי הגדרת השדה contextWindowCompression כחלק מLiveGenerationConfig. כשהתכונה הזו מופעלת, השרת משתמש במנגנון של חלון הזזה כדי להסיר באופן אוטומטי את התורות הכי ישנות או לסכם אותן, כדי לשמור על גודל ההקשר במסגרת המגבלות שמוגדרות כברירת מחדל או המגבלות שצוינו. ההוראות למערכת לא נמחקות ותמיד יישארו בתחילת חלון ההקשר.

מנקודת המבט של המשתמש, זה מאפשר משך הפעלה אינסופי מבחינה תיאורטית, כי הזיכרון מנוהל באופן קבוע.

אפשר להגדיר את מנגנון החלון הנע וגם אופציונלית את מספר הטוקנים שמפעיל דחיסה (ראו את ההגדרות והערכים הזמינים בהמשך). הנה כמה דברים שכדאי לקחת בחשבון כשמשתמשים בהגדרות האלה:

  • הגדרה של targetTokens כנמוכה מאוד תפנה יותר מקום בהקשר לשיחות רציפות, אבל המודל ישכח במהירות את התפניות הקודמות בשיחה.

  • אם מגדירים את targetTokens קרוב יותר ל-triggerTokens, נשמר יותר זיכרון אבל תהליכי הדחיסה יופעלו בתדירות גבוהה יותר.

הגדרה ברירת המחדל לחלון נע אם לא מוגדרת תצורה ערך מינימלי ערך מקסימלי
triggerTokens
חלון ההקשר לפני הפעלת הדחיסה
‫80% ממגבלת חלון ההקשר של המודל 5,000 128,000
targetTokens
מספר הטוקנים שרוצים לשמור
‫50% מהערך triggerTokens
  • אם לא מגדירים את triggerTokens במפורש, ברירת המחדל של targetTokens היא 50% מהערך המוגדר כברירת מחדל של triggerTokens.
  • הערך של targetTokens חייב להיות קטן מהערך של triggerTokens.
0 128,000

Swift


// Initialize the Gemini Developer API backend service
let liveModel = FirebaseAI.firebaseAI(backend: .googleAI()).liveModel(
  modelName: "gemini-2.5-flash-native-audio-preview-12-2025",
  // Enable context window compression.
  // (Optional) Configure the number of tokens in the context window that triggers the compression.
  generationConfig: LiveGenerationConfig(
    responseModalities: [.audio],
    contextWindowCompression: ContextWindowCompressionConfig(
      triggerTokens: 10000,
      slidingWindow: SlidingWindow(
        targetTokens: 2000,
      )
    )
  )
)

Kotlin


// Initialize the Gemini Developer API backend service
val liveModel = Firebase.ai(backend = GenerativeBackend.googleAI()).liveModel(
    modelName = "gemini-2.5-flash-native-audio-preview-12-2025",
    // Enable context window compression.
    // (Optional) Configure the number of tokens in the context window that triggers the compression.
    generationConfig = liveGenerationConfig {
        responseModality = ResponseModality.AUDIO,
        contextWindowCompression = ContextWindowCompressionConfig(
            triggerTokens = 10000,
            slidingWindow = SlidingWindow(targetTokens = 2000)
        )
    }
)

Java


// Initialize the Gemini Developer API backend service
LiveGenerativeModel lm = FirebaseAI.getInstance(GenerativeBackend.googleAI()).liveModel(
        "gemini-2.5-flash-native-audio-preview-12-2025",
        // Enable context window compression.
        // (Optional) Configure the number of tokens in the context window that triggers the compression.
        new LiveGenerationConfig.Builder()
                .setResponseModality(ResponseModality.AUDIO)
                .setContextWindowCompression(
                        new ContextWindowCompressionConfig(10000, new SlidingWindow(2000))
                )
                .build()
);

Web


const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

const liveModel = getLiveGenerativeModel(ai, {
  model: "gemini-2.5-flash-native-audio-preview-12-2025",
  // Enable context window compression.
  // (Optional) Configure the number of tokens in the context window that triggers the compression.
  generationConfig: {
    responseModalities: [ResponseModality.AUDIO],
    contextWindowCompression: {
      triggerTokens: 10000,
      slidingWindow: {
        targetTokens: 2000,
      },
    },
  },
});

Dart


final _liveModel = FirebaseAI.googleAI().liveGenerativeModel(
  model: 'gemini-2.5-flash-native-audio-preview-12-2025',
  // Enable context window compression.
  // (Optional) Configure the number of tokens in the context window that triggers the compression.
  liveGenerationConfig: LiveGenerationConfig(
    responseModalities: [ResponseModalities.audio],
    contextWindowCompression: ContextWindowCompressionConfig(
      triggerTokens: 10000,
      slidingWindow: SlidingWindow(targetTokens: 2000),
    ),
  ),
);

Unity


var liveModel = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()).GetLiveModel(
    modelName: "gemini-2.5-flash-native-audio-preview-12-2025",
    // Enable context window compression.
    // (Optional) Configure the number of tokens in the context window that triggers the compression.
    liveGenerationConfig: new LiveGenerationConfig(
        responseModalities: new[] { ResponseModality.Audio },
        contextWindowCompression: new ContextWindowCompressionConfig(
            triggerTokens: 10000,
            slidingWindow: new SlidingWindow(targetTokens: 2000)
        )
    )
);

זיהוי מתי סשן עומד להסתיים

המשך המקסימלי של חיבור WebSocket רציף הוא בערך 10 דקות. התראה על סיום השיחה נשלחת ללקוח 60 שניות לפני סיום החיבור, כדי שתוכלו לבצע פעולות נוספות (לדוגמה, להמשיך את הסשן).

בדוגמה הבאה מוצג איך לזהות סיום חיבור מתקרב באמצעות האזנה להתראה על התנתקות:

Swift

for try await response in session.responses {
  switch response.payload {

  case .goingAwayNotice(let goingAwayNotice):
    // Prepare for the session to close soon
    if let timeLeft = goingAwayNotice.timeLeft {
        print("Server going away in \(timeLeft) seconds")
    }
  }
}

Kotlin

for (response in session.responses) {
    when (val message = response.payload) {
        is LiveServerGoAway -> {
            // Prepare for the session to close soon
            val remaining = message.timeLeft
            logger.info("Server going away in $remaining")
        }
    }
}

Java

session.getResponses().forEach(response -> {
    if (response.getPayload() instanceof LiveServerResponse.GoingAwayNotice) {
        LiveServerResponse.GoingAwayNotice notice = (LiveServerResponse.GoingAwayNotice) response.getPayload();
        // Prepare for the session to close soon
        Duration timeLeft = notice.getTimeLeft();
    }
});

Web

for await (const message of session.receive()) {
  switch (message.type) {

  ...
  case "goingAwayNotice":
    console.log("Server going away. Time left:", message.timeLeft);
    break;
  }
}

Dart

Future _handleLiveServerMessage(LiveServerResponse response) async {
  final message = response.message;
  if (message is GoingAwayNotice) {
     // Prepare for the session to close soon
     developer.log('Server going away. Time left: ${message.timeLeft}');
  }
}

Unity

foreach (var response in session.Responses) {
    if (response.Payload is LiveSessionGoingAway notice) {
        // Prepare for the session to close soon
        TimeSpan timeLeft = notice.TimeLeft;
        Debug.Log($"Server going away notice received. Remaining: {timeLeft}");
    }
}

המשך של סשן

Live API תומך בהמשך השיחה כדי שלא תאבדו את ההקשר שלה. לכל סשן יש נקודת אחיזה, ואפשר להשתמש בה בדרכים הבאות:

  • שמירה על הפעילות של סשן לפני שמגיעים למגבלת הזמן של החיבור

    המשך המקסימלי של חיבור WebSocket רציף הוא בערך 10 דקות. כדי לזהות מתי חיבור עומד להסתיים, מאזינים להתראה going away, ואז מאריכים את הסשן על ידי יצירת חיבור חדש באמצעות ה-handle של הסשן.

  • המשכת סשן מיד אחרי ניתוק

    אם החיבור מסתיים או נכשל לפני מגבלת הזמן המקסימלית לחיבור (לדוגמה, אם עוברים מ-Wi-Fi ל-5G), השרת שומר את מצב הסשן למשך כ-10 דקות. במהלך חלון הזמן הזה, אפשר לחדש את הסשן על ידי יצירת חיבור חדש באמצעות ה-handle של הסשן.

  • המשך של סשן אחרי תקופה ממושכת

    אחרי שחיבור מסתיים, השרת שומר את מצב הסשן למשך כמה שעות. במהלך חלון הזמן הזה, אפשר לחדש את הסשן על ידי יצירת חיבור חדש באמצעות ה-handle של הסשן. שימו לב שהחלון הזה שונה אצל שני ספקי Gemini API: אצל Gemini Developer API הוא שעתיים | אצל Vertex AI Gemini API הוא 24 שעות.

כברירת מחדל, האפשרות להמשך הפעילות מושבתת. כדי להפעיל את חידוש הסשן, צריך להעביר הגדרת חידוש ריקה כשיוצרים חיבור חדש. כשההגדרה הזו מופעלת, השרת שולח מדי פעם עדכונים שמכילים את פרטי הסשן. אם החיבור לסשן מתנתק, אפשר להתחבר מחדש ולהעביר את ה-handle הזה כדי להמשיך את הסשן עם ההקשר שלו.

בדוגמאות הבאות מוצגות שתי אפשרויות לחידוש הסשן:

Swift

// Local variable to save the active session handle
var activeSessionHandle: String?

// Initialize the session. Passing an empty config requests the server to send SessionResumptionUpdate
var session = try await liveModel.connect(
  sessionResumption: SessionResumptionConfig()
)

// Start receiving responses
for try await message in session.responses {
  // Check for new session handles inside your message handling loop
  switch message.payload {
  case let .sessionResumptionUpdate(updateMessage):
    guard let newHandle = updateMessage.newHandle, updateMessage.resumable else {
      continue
    }
    activeSessionHandle = newHandle
    print("SessionResumptionUpdate: handle \(newHandle)")
  // ... handle other LiveServerMessage types ...
  default:
    break
  }
}

// The following are alternative options to resume a session. Choose only one.

// Option 1: Create and connect a session to resume with the saved handle
if let handle = activeSessionHandle {
  session = try await liveModel.connect(
    sessionResumption: SessionResumptionConfig(handle: handle)
  )
}

// Option 2: Resume the session directly on an existing session object
if let handle = activeSessionHandle {
  try await session.resumeSession(
    sessionResumption: SessionResumptionConfig(handle: handle)
  )
}

Kotlin

// Local variable to save the active session handle
var activeSessionHandle: String? = null

// Initialize the session. Passing an empty config requests the server to send SessionResumptionUpdate
var session = liveModel.connect(
    sessionResumption = SessionResumptionConfig()
)

// Start receiving responses
session.receive().collect { message ->
    // Process other received response types...

    // Check for new session handles inside your message handling loop
    if (message is LiveSessionResumptionUpdate) {
        if (message.resumable == true && message.newHandle != null) {
            activeSessionHandle = message.newHandle
            Log.d("TAG", "SessionResumptionUpdate: handle ${message.newHandle}")
        }
    }
}

// The following are alternative options to resume a session. Choose only one.

// Option 1: Create and connect a session to resume with the saved handle
activeSessionHandle?.let { handle ->
    session = liveModel.connect(
        sessionResumption = SessionResumptionConfig(handle = handle)
    )
}

// Option 2: Resume the session directly on an existing session object
activeSessionHandle?.let { handle ->
    session.resumeSession(
        sessionResumption = SessionResumptionConfig(handle = handle)
    )
}

Java

For Java, session resumption is not yet supported. Check back soon!

Web

// Local variable to save the active session handle
let activeSessionHandle = null;

// Initialize the session. Passing an empty object requests the server to send SessionResumptionUpdate
let session = await liveModel.connect({});

// Start receiving responses
for await (const message of session.receive()) {
  // Process other received response types...

  // Check for new session handles inside your message handling loop
  if (message.type === 'sessionResumptionUpdate') {
    if (message.resumable && message.newHandle) {
      activeSessionHandle = message.newHandle;
      console.log(`SessionResumptionUpdate: handle ${activeSessionHandle}`);
    }
  }
}

// The following are alternative options to resume a session. Choose only one.

// Option 1: Create and connect a session to resume with the saved handle
if (activeSessionHandle) {
  session = await liveModel.connect({
    handle: activeSessionHandle
  });
}

// Option 2: Resume the session directly on an existing session object
if (activeSessionHandle) {
  await session.resumeSession({
    handle: activeSessionHandle
  });
}

Dart

// Local variable to save the active session handle
String? _activeSessionHandle;

// Initialize the session. Passing an empty config requests the server to send SessionResumptionUpdate
var _session = await _liveModel.connect(
  sessionResumption: SessionResumptionConfig(),
);

// Start receiving responses
await for (final message in _session.receive()) {
  // Process other received response types...

  // Check for new session handles inside your message handling loop
  if (message is SessionResumptionUpdate &&
      message.resumable != null &&
      message.resumable!) {
    _activeSessionHandle = message.newHandle;
    log('SessionResumptionUpdate: handle ${message.newHandle}');
  }
}

// The following are alternative options to resume a session. Choose only one.

// Option 1: Create and connect a session to resume with the saved handle
if (_activeSessionHandle != null) {
  _session = await _liveModel.connect(
    sessionResumption: SessionResumptionConfig.resume(_activeSessionHandle!),
  );
}

// Option 2: Alternatively, resume the session directly on an existing session object
if (_activeSessionHandle != null) {
  await _session.resumeSession(
    sessionResumption: SessionResumptionConfig.resume(_activeSessionHandle!),
  );
}

Unity

// Local variable to save the active session handle
string activeSessionHandle = null;

// Initialize the session. Passing an empty config requests the server to send SessionResumptionUpdate
var session = await liveModel.ConnectAsync(
    sessionResumption: new SessionResumptionConfig()
);

// Start receiving responses
await foreach (var response in session.ReceiveAsync())
{
  // Process other received response types...

  // Check for new session handles inside your message handling loop
  if (response.Message is LiveSessionResumptionUpdate updateMessage)
  {
    if (updateMessage.Resumable == true && !string.IsNullOrEmpty(updateMessage.NewHandle))
    {
      activeSessionHandle = updateMessage.NewHandle;
      Debug.Log($"SessionResumptionUpdate: handle {activeSessionHandle}");
    }
  }
}

// The following are alternative options to resume a session. Choose only one.

// Option 1: Create and connect a session to resume with the saved handle
if (!string.IsNullOrEmpty(activeSessionHandle)) {
  session = await liveModel.ConnectAsync(
      sessionResumption: new SessionResumptionConfig(activeSessionHandle)
  );
}

// Option 2: Resume the session directly on an existing session object
if (!string.IsNullOrEmpty(activeSessionHandle)) {
  await session.ResumeSessionAsync(
      sessionResumption: new SessionResumptionConfig(activeSessionHandle)
  );
}