Session management with Live API

Live API में, सेशन का मतलब ऐसे लगातार बने रहने वाले कनेक्शन से है जहां इनपुट और आउटपुट को एक ही कनेक्शन पर लगातार स्ट्रीम किया जाता है. यह कैसे काम करता है, इस बारे में ज़्यादा पढ़ें. सेशन के इस यूनीक डिज़ाइन की मदद से, कम इंतज़ार का समय मिलता है और यूनीक सुविधाएं मिलती हैं. हालांकि, इससे कुछ समस्याएं भी आ सकती हैं. जैसे, सेशन के खत्म होने की समयसीमा और सेशन के जल्दी खत्म होने की समस्या. इस गाइड में, सेशन मैनेजमेंट से जुड़ी उन चुनौतियों को हल करने की रणनीतियों के बारे में बताया गया है जो Live API का इस्तेमाल करते समय आ सकती हैं.

सेशन का लाइफ़टाइम

बिना कंप्रेस किए, सिर्फ़ ऑडियो वाले सेशन 15 मिनट तक और ऑडियो-वीडियो वाले सेशन दो मिनट तक ही चलाए जा सकते हैं. इन सीमाओं से ज़्यादा डेटा भेजने पर, सेशन (और कनेक्शन) बंद हो जाएगा. हालांकि, कॉन्टेक्स्ट विंडो कंप्रेसन का इस्तेमाल करके, सेशन को अनलिमिटेड समय तक बढ़ाया जा सकता है.

किसी कनेक्शन का लाइफ़टाइम भी सीमित होता है. यह करीब 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 के साथ काम करने के ज़्यादा तरीके जानें.