El Gemini Live API procesa flujos continuos de audio o texto llamados 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 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 finalizará la conexión. Sin embargo, ten en cuenta que Live API proporciona algunas opciones (consulta a continuación) para controlar estos límites relacionados con las sesiones.
La ventana de contexto de la sesión se limita a 128,000 tokens.
Debido a este límite de la ventana de contexto, estas son las longitudes máximas aproximadas de las sesiones según las modalidades de entrada:
- Las sesiones de entrada solo de audio se limitan a
15 minutos . - La entrada de audio y video se limita a
2 minutos .
- Las sesiones de entrada solo de audio se limitan a
La duración de la conexión se limita 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 las sesiones:
Comprime la ventana de contexto de la sesión para que el servidor mantenga automáticamente el tamaño del contexto dentro del límite.
Reanuda una sesión para evitar perder el contexto de la conversación durante desconexiones breves de la red o después de recibir una notificación de ausencia.
Inicia una sesión
Visita la guía de introducción para Live API para ver un fragmento completo que muestra cómo iniciar una sesión.
Actualización durante la sesión
Los modelos Live API admiten las siguientes capacidades avanzadas para las actualizaciones durante la sesión:
Actualiza las instrucciones del sistema (solo para Vertex AI Gemini API)
Agrega actualizaciones de contenido incrementales
Puedes agregar actualizaciones incrementales durante una sesión activa. Úsalo para enviar entrada de texto, establecer el contexto de la sesión o restablecerlo.
Para contextos más largos, te recomendamos que proporciones un solo resumen del mensaje para liberar la ventana de contexto para interacciones posteriores.
En el caso de contextos breves, puedes enviar interacciones paso a paso para representar la secuencia exacta de eventos, como se muestra en el siguiente fragmento.
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 usas Vertex AI Gemini API como tu proveedor de la API. |
Puedes actualizar las instrucciones del sistema durante una sesión activa. Úsalo 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 actualizadas del sistema 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}");
}
Comprimir la ventana de contexto
|
Haz clic en tu proveedor de Gemini API para ver el contenido y el código específicos del proveedor en esta página. |
La ventana de contexto de la sesión de Live API 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 de 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 las sesiones según las modalidades de entrada:
- Las sesiones de entrada solo de audio se limitan a
15 minutos . - La entrada de audio y video se limita 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 principio 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 constantemente.
Puedes configurar el mecanismo de ventana deslizante y, 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 generales sobre el uso de estos parámetros de configuración:
Si configuras
targetTokensen un valor muy bajo, se liberará más espacio de contexto para los flujos continuos, pero el modelo "olvidará" rápidamente los turnos anteriores de la conversación.Establecer
targetTokensmás cerca detriggerTokenspreserva más memoria, pero activará 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 |
|---|---|---|---|
triggerTokensla longitud del contexto antes de que se active la compresión |
El 80% del límite de la ventana de contexto del modelo | 5,000 | 128,000 |
targetTokensEs la cantidad objetivo de tokens que se deben conservar. |
El 50% del 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 sola conexión WebSocket continua es de aproximadamente
En el siguiente ejemplo, se muestra cómo detectar la finalización inminente de una conexión escuchando una notificación de 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}");
}
}
Cómo reanudar una sesión
Live API admite la reanudación de la sesión para evitar la pérdida del contexto de la conversación. Cada sesión tiene un identificador que se puede usar de las siguientes maneras:
Cómo 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 continua es de aproximadamente
10 minutos . Puedes detectar cuándo está a punto de finalizar una conexión escuchando una notificación de going away y, luego, extender la sesión estableciendo una nueva conexión con el identificador de sesión.Cómo reanudar una sesión justo después de que se interrumpe la conexión
Si una conexión finaliza o se interrumpe antes del límite máximo de tiempo de conexión (por ejemplo, si se cambia de Wi-Fi a 5G), el servidor mantiene el estado de la sesión durante aproximadamente
10 minutos . Durante este período, puedes reanudar la sesión estableciendo una nueva conexión con el identificador de sesión.Cómo 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 algunas horas. Durante este período, puedes reanudar la sesión estableciendo una nueva conexión con el identificador de sesión. Ten en cuenta que este período es diferente para los dos proveedores de Gemini API: Gemini Developer API es de
2 horas y Vertex AI Gemini API es de24 horas .
De forma predeterminada, la reanudación de sesión está inhabilitada. Para habilitar la reanudación de sesión, pasa una configuración de reanudación vacía cuando establezcas una conexión nueva. Cuando está habilitado, el servidor envía periódicamente actualizaciones que contienen un identificador de reanudación de sesión. Si se desconecta la sesión, puedes volver a conectarte y pasar este identificador 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)
);
}