Administra sesiones para la API de Live

El Gemini Live API procesa transmisiones continuas de audio o texto llamadas sesiones. Puedes administrar el ciclo de vida de la sesión, desde el protocolo de enlace inicial hasta la finalización correcta.

Límites para las sesiones

En el caso de la Live API, una sesión hace referencia a una conexión persistente en la que la entrada y la salida se transmiten de forma continua a través de una conexión.

Si la sesión supera cualquiera de los siguientes límites, se finaliza la conexión. Sin embargo, ten en cuenta que el Live API proporciona algunas opciones (consulta a continuación) para controlar estos límites relacionados con la sesión.

  • La ventana de contexto de la sesión está limitada a 128,000 tokens.

    Debido a este límite de la ventana de contexto, estas son las duraciones máximas aproximadas de la sesión según las modalidades de entrada:

    • Las sesiones de entrada solo de audio están limitadas a 15 minutos.
    • La entrada de video y audio está limitada a 2 minutos.
  • La duración de la conexión está limitada a unos 10 minutos.

    Recibirás una notificación de desconexión unos 60 segundos antes de que finalice la conexión.

Estas son algunas opciones para controlar los límites relacionados con la sesión:

Inicia una sesión

Consulta la guía de introducción de la Live API para obtener un fragmento completo que muestre cómo iniciar una sesión.

Actualiza durante la sesión

Los modelos Live API admiten las siguientes capacidades avanzadas para actualizaciones durante la sesión:

Agrega actualizaciones de contenido incrementales

Puedes agregar actualizaciones incrementales durante una sesión activa. Usa esta opción para enviar entradas de texto, establecer el contexto de la sesión o restaurarlo.

  • Para contextos más largos, te recomendamos que proporciones un solo resumen del mensaje para liberar la ventana de contexto para interacciones posteriores.

  • Para contextos breves, puedes enviar interacciones paso a paso para representar la secuencia exacta de eventos, como el fragmento que se muestra a continuación.

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
);

Actualiza las instrucciones del sistema durante la sesión

Solo está disponible cuando se usa Vertex AI Gemini API como proveedor de API.

Puedes actualizar las instrucciones del sistema durante una sesión activa. Usa esta opción para adaptar las respuestas del modelo, por ejemplo, para cambiar el idioma de la respuesta o modificar el tono.

Para actualizar las instrucciones del sistema durante la sesión, puedes enviar contenido de texto con el rol system. Las instrucciones del sistema actualizadas seguirán vigentes durante el resto de la sesión.

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}");
}

Comprime la ventana de contexto

Haz clic en tu proveedor de Gemini API para ver el contenido específico del proveedor y el código en esta página.

La Live API ventana de contexto de la sesión de la API de Live almacena datos transmitidos en tiempo real (25 tokens por segundo [TPS] para audio y 258 TPS para video), así como otro contenido, incluidas las entradas de texto y las salidas del modelo. Todos los modelos Live API tienen un límite de ventana de contexto de sesión de 128,000 tokens.

De forma predeterminada, debido a este límite de la ventana de contexto, estas son las duraciones máximas aproximadas de la sesión según las modalidades de entrada:

  • Las sesiones de entrada solo de audio están limitadas a 15 minutos.
  • La entrada de video y audio está limitada a 2 minutos.

En las sesiones de larga duración, a medida que avanza la conversación, se acumula el historial de tokens de audio o video. Si este historial supera el límite del modelo, es posible que el modelo alucine, se ralentice o que la sesión se finalice de forma forzosa.

Para habilitar sesiones más largas, puedes habilitar la compresión de la ventana de contexto configurando el campo contextWindowCompression como parte de LiveGenerationConfig. Cuando está habilitado, el servidor usa un mecanismo de ventana deslizante para descartar automáticamente los turnos más antiguos o resumirlos para mantener el tamaño del contexto dentro de los límites predeterminados o especificados. Las instrucciones del sistema no se descartan y siempre permanecerán al comienzo de la ventana de contexto.

Desde la perspectiva del usuario, esto permite duraciones de sesión teóricamente infinitas, ya que la "memoria" se administra de forma constante.

Puedes configurar el mecanismo de ventana deslizante, así como opcionalmente la cantidad de tokens que activan la compresión (consulta la configuración y los valores disponibles a continuación). Estas son algunas consideraciones de alto nivel sobre el uso de esta configuración:

  • Si configuras targetTokens en un valor muy bajo, se liberará más espacio de contexto para las transmisiones continuas, pero el modelo "olvidará" rápidamente los turnos más antiguos de la conversación.

  • Si configuras targetTokens más cerca de triggerTokens, se conservará más memoria, pero se activarán rutinas de compresión con mucha más frecuencia.

Configuración Valor predeterminado para la ventana deslizante si no se configura en la configuración Valor mínimo Valor máximo
triggerTokens
la longitud del contexto antes de que se active la compresión
80% del límite de la ventana de contexto del modelo 5,000 128,000
targetTokens
la cantidad objetivo de tokens que se deben conservar
50% del valor de triggerTokens
  • Si triggerTokens no se configura explícitamente, entonces targetTokens se establece de forma predeterminada en el 50% del valor predeterminado triggerTokens.
  • El valor de targetTokens debe ser inferior al valor de 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)
        )
    )
);

Detecta cuándo finalizará una sesión

La duración máxima de una conexión WebSocket única y continua es de aproximadamente 10 minutos. Se envía una notificación de desconexión al cliente 60 segundos antes de que finalice la conexión, lo que puede ayudarte a realizar acciones adicionales (por ejemplo, al reanudar una sesión).

En el siguiente ejemplo, se muestra cómo detectar una finalización de conexión inminente escuchando una notificación de desconexión:

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}");
    }
}

Reanuda una sesión

El Live API admite la reanudación de la sesión para evitar perder el contexto de la conversación. Cada sesión tiene un controlador y se puede usar de las siguientes maneras:

  • Mantener una sesión antes de alcanzar el límite de tiempo de conexión

    La duración máxima de una conexión WebSocket única y continua es de aproximadamente 10 minutos. Puedes detectar cuándo está a punto de finalizar una conexión con escuchando una notificación de desconexión y, luego, extendiendo la sesión estableciendo una nueva conexión con el controlador de la sesión.

  • Reanudar una sesión justo después de una caída de conexión

    Si una conexión finaliza o se cae antes del límite máximo de tiempo de conexión (por ejemplo, si cambias de Wi-Fi a 5G), el servidor mantiene el estado de la sesión durante unos 10 minutos. Durante esta ventana, puedes reanudar la sesión estableciendo una nueva conexión con el controlador de la sesión.

  • Reanudar una sesión después de un período prolongado

    Después de que finaliza una conexión, el servidor mantiene el estado de la sesión durante unas horas. Durante esta ventana, puedes reanudar la sesión estableciendo una nueva conexión con el controlador de la sesión. Ten en cuenta que esta ventana es diferente para los dos proveedores Gemini API: Gemini Developer API es 2 horas | Vertex AI Gemini API es 24 horas.

De forma predeterminada, la reanudación de la sesión está inhabilitada. Para habilitar la reanudación de la sesión, pasa una configuración de reanudación vacía cuando establezcas una conexión nueva. Cuando está habilitado, el servidor envía actualizaciones periódicamente que contienen un controlador de reanudación de la sesión. Si se desconecta la sesión, puedes volver a conectarte y pasar este controlador para reanudar la sesión con su contexto intacto.

En los siguientes ejemplos, se muestran dos opciones para reanudar la sesión:

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)
  );
}