O Gemini Live API processa fluxos contínuos de áudio ou texto chamados de sessões. É possível gerenciar o ciclo de vida da sessão, desde o handshake inicial até o encerramento normal.
Limites para sessões
Para o Live API, uma sessão se refere a uma conexão persistente em que a entrada e a saída são transmitidas continuamente pela mesma conexão.
Se a sessão exceder qualquer um dos seguintes limites, a conexão será encerrada.
A duração da conexão é limitada a cerca de 10 minutos.
A duração da sessão depende das modalidades de entrada:
- As sessões de entrada somente de áudio são limitadas a 15 minutos.
- A entrada de vídeo e áudio é limitada a 2 minutos.
A janela de contexto da sessão é limitada a 128 mil tokens.
Você vai receber uma notificação de encerramento antes do fim da conexão para que possa tomar outras medidas.
Iniciar uma sessão
Consulte o guia de primeiros passos do Live API para ver um snippet completo mostrando como iniciar uma sessão.
Atualização no meio da sessão
Os modelos Live API oferecem suporte aos seguintes recursos avançados para atualizações no meio da sessão:
Atualizar instruções do sistema (somente para Vertex AI Gemini API)
Adicionar atualizações incrementais de conteúdo
É possível adicionar atualizações incrementais durante uma sessão ativa. Use isso para enviar entrada de texto, estabelecer ou restaurar o contexto da sessão.
Para contextos mais longos, recomendamos fornecer um único resumo da mensagem para liberar a janela de contexto para interações subsequentes.
Para contextos curtos, você pode enviar interações de turno a turno para representar a sequência exata de eventos, como o snippet abaixo.
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
);
Atualizar instruções do sistema no meio da sessão
| Disponível apenas quando você usa o Vertex AI Gemini API como seu provedor de API. |
É possível atualizar as instruções do sistema durante uma sessão ativa. Use isso para adaptar as respostas do modelo, por exemplo, para mudar o idioma ou modificar o tom.
Para atualizar as instruções do sistema no meio da sessão, envie conteúdo de texto com a função system. As instruções atualizadas do sistema vão permanecer em vigor durante o restante da sessão.
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}");
}
Detectar quando uma sessão vai terminar
Uma notificação de encerramento é enviada ao cliente
O exemplo a seguir mostra como detectar um encerramento de sessão iminente ao ouvir uma notificação 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}");
}
}