Gemini Live API elabora flussi continui di audio o testo chiamati sessioni. Puoi gestire il ciclo di vita della sessione, dall'handshake iniziale all'interruzione controllata.
Limiti per le sessioni
Per Live API, una sessione si riferisce a una connessione persistente in cui l'input e l'output vengono trasmessi in streaming continuamente sulla stessa connessione.
Se la sessione supera uno dei seguenti limiti, la connessione viene terminata.
La durata della connessione è limitata a circa 10 minuti.
La durata della sessione dipende dalle modalità di input:
- Le sessioni di input solo audio sono limitate a 15 minuti.
- L'input video e audio è limitato a 2 minuti.
La finestra contestuale della sessione è limitata a 128.000 token.
Riceverai una notifica di interruzione prima che la connessione termini, per consentirti di intraprendere ulteriori azioni.
Avviare una sessione
Visita la guida introduttiva per Live API per uno snippet completo che mostra come avviare una sessione.
Aggiornamento a metà sessione
I modelli Live API supportano le seguenti funzionalità avanzate per gli aggiornamenti a metà sessione:
Aggiornare le istruzioni di sistema (solo per Vertex AI Gemini API)
Aggiungere aggiornamenti incrementali dei contenuti
Puoi aggiungere aggiornamenti incrementali durante una sessione attiva. Utilizzalo per inviare input di testo, stabilire il contesto della sessione o ripristinarlo.
Per contesti più lunghi, ti consigliamo di fornire un riepilogo di un singolo messaggio per liberare la finestra contestuale per le interazioni successive.
Per i contesti brevi, puoi inviare interazioni passo passo per rappresentare la sequenza esatta di eventi, come lo snippet riportato di seguito.
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
);
Aggiornare le istruzioni di sistema a metà sessione
| Disponibile solo quando utilizzi Vertex AI Gemini API come provider API. |
Puoi aggiornare le istruzioni di sistema durante una sessione attiva. Utilizzalo per adattare le risposte del modello, ad esempio per cambiare la lingua della risposta o modificare il tono.
Per aggiornare le istruzioni di sistema a metà sessione, puoi inviare contenuti di testo con
il ruolo system. Le istruzioni di sistema aggiornate rimarranno in vigore per il
resto della sessione.
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}");
}
Rilevare quando una sessione sta per terminare
Una notifica di interruzione viene inviata al client
L'esempio seguente mostra come rilevare l'imminente interruzione della sessione ascoltando una notifica di 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}");
}
}