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

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

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

ב-Live API, סשן הוא חיבור קבוע שבו הקלט והפלט מועברים בסטרימינג באופן רציף דרך החיבור.

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

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

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

    • סשנים של קלט אודיו בלבד מוגבלים ל-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

// Define initial turns (history/context).
val turns = listOf(
  content("user") {
    text("What is the capital of France?")
  },
  content("model") {
    text("Paris")
  }
)

// Send history, keeping the conversational turn OPEN (false).
turns.forEach {
  session.send(
    content = it,
    turnComplete = false
  )
}

// Define the new user query.
val newTurn = content("user") {
  text("What is the capital of Germany?")
}

// Send the final query, CLOSING the turn (true) to trigger the model response.
session.send(
  content = newTurn,
  turnComplete = true
)

Java

// Define initial turns (history/context).
List turns =
    Arrays.asList(
        new Content.Builder().setRole("user").addText("What is the capital of France?").build(),
        new Content.Builder().setRole("model").addText("Paris").build());

for (Content turn : turns) {
  session.send(
    turn,
    false // turnComplete: false
  );
}

// Define the new user query.
Content newTurn = new Content.Builder().addText("What is the capital of Germany?").build();

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

Web

const turns = [{ type: "text", 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 = [{ type: "text", 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",
    [TextPart("What is the capital of France?")],
  ),
  Content(
    "model",
    [TextPart("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",
    [TextPart("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
);

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

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

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

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

Swift

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

Kotlin

// In a coroutine scope
session.send(
    content = content("system") {
        text("new system instruction")
    },
    turnComplete = false
)

Java

session.send(
    new Content.Builder()
        .setRole("system")
        .addText("new system instruction")
        .build(),
    /* turnComplete: */ false
);

Web

Not yet supported for Web apps - check back soon!

Dart

try {
  await _session.send(
    input: Content(
      'system',
      [TextPart('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}");
}

דיווח ידני על פעילות משתמשים

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

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

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

איך משביתים את זיהוי הדיבור (VAD) האוטומטי ומסמנים באופן ידני את פעילות המשתמש

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

כדי לראות תוכן וקוד שספציפיים לספק, לוחצים על הספק 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


// ...

let liveModel = FirebaseAI.firebaseAI(backend: .googleAI()).liveModel(
  modelName: "GEMINI_LIVE_API_MODEL_NAME",
  // 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


// ...

val liveModel = Firebase.ai(backend = GenerativeBackend.googleAI()).liveModel(
    modelName = "GEMINI_LIVE_API_MODEL_NAME",
    // 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


// ...

LiveGenerativeModel lm = FirebaseAI.getInstance(GenerativeBackend.googleAI()).liveModel(
        "GEMINI_LIVE_API_MODEL_NAME",
        // 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_LIVE_API_MODEL_NAME",
  // 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_LIVE_API_MODEL_NAME',
  // 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_LIVE_API_MODEL_NAME",
    // 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 דקות. הודעת going away נשלחת ללקוח 60 שניות לפני שהחיבור מסתיים, כדי שתוכלו לבצע פעולות נוספות (לדוגמה, להמשיך את הסשן).

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

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, ואז להאריך את הסשן על ידי יצירת חיבור חדש באמצעות נקודת האחיזה של הסשן.

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

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

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

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

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

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

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 response in _session.receive()) {
  // Process other received response types...

  // Check for new session handles inside your message handling loop
  final message = response.message;
  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)
  );
}