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 la misma conexión.
Si la sesión supera cualquiera de los siguientes límites, se finalizará la conexión.
La duración de la conexión se limita a unos 10 minutos.
La duración de la sesión depende de las modalidades de entrada:
- Las sesiones de entrada solo de audio tienen un límite de 15 minutos.
- La entrada de audio y video se limita a 2 minutos.
La ventana de contexto de la sesión está limitada a 128,000 tokens.
Recibirás una notificación de desconexión antes de que finalice la conexión, lo que te permitirá tomar medidas adicionales.
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}");
}
Detecta cuándo finalizará una sesión
Se envía una notificación de desconexión al cliente
En el siguiente ejemplo, se muestra cómo detectar la finalización inminente de una sesió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}");
}
}