Session management with Live API

ใน 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 ซึ่งบ่งบอกว่าการเชื่อมต่อปัจจุบันจะสิ้นสุดลงในไม่ช้า ข้อความนี้มี 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