Gemini Live API обрабатывает непрерывные потоки аудио или текста, называемые сессиями . Вы можете управлять жизненным циклом сессии, от первоначального установления соединения до корректного завершения.
Ограничения на количество сессий
В контексте Live API сессия обозначает постоянное соединение, в котором входные и выходные данные непрерывно передаются по каналу связи.
Если продолжительность сессии превышает любой из следующих лимитов, соединение разрывается. Однако следует отметить, что Live API предоставляет некоторые параметры (см. ниже) для обработки этих ограничений, связанных с сессией.
Окно контекста сессии ограничено 128 тысячами токенов.
В связи с ограничением контекстного окна, приблизительная максимальная продолжительность сеанса в зависимости от способа ввода данных выглядит следующим образом:
- Продолжительность сеансов ввода только аудиоконтента ограничена
15 минутами . - Видео- и аудиовход ограничены
2 минутами .
- Продолжительность сеансов ввода только аудиоконтента ограничена
Продолжительность соединения ограничена примерно
10 минутами .Примерно за
60 секунд до окончания соединения вы получите уведомление о завершении сеанса .
Вот несколько вариантов обработки ограничений, связанных с сессиями:
Сожмите окно контекста сессии таким образом, чтобы сервер автоматически поддерживал размер контекста в пределах допустимого значения.
Возобновите сессию , чтобы предотвратить потерю контекста разговора во время кратковременных разрывов сетевого соединения или после получения уведомления об уходе .
Начать сессию
Для получения подробной информации о том, как начать сессию, посетите руководство по началу работы с Live API .
Обновление в середине сессии
Модели Live API поддерживают следующие расширенные возможности для обновлений в середине сессии :
Инструкции по обновлению системы (только для Vertex AI Gemini API )
Добавить поэтапные обновления контента
В ходе активной сессии можно добавлять поэтапные обновления. Используйте эту функцию для отправки текстового ввода, установления контекста сессии или восстановления контекста сессии.
Для более длинных диалогов мы рекомендуем предоставлять краткое описание сообщения в одном файле, чтобы освободить контекстное окно для последующих взаимодействий.
Для коротких сценариев можно отправлять пошаговые инструкции, точно воспроизводящие последовательность событий, как показано в приведенном ниже фрагменте.
Быстрый
// 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,
);
Единство
// 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
);
Обновите инструкции к системе в середине сеанса.
| Доступно только при использовании API Vertex AI Gemini в качестве поставщика API. |
Вы можете обновлять инструкции системы во время активной сессии. Используйте это для адаптации ответов модели, например, для изменения языка ответа или корректировки тона.
Для обновления системных инструкций в середине сеанса вы можете отправить текстовое содержимое с указанием роли system . Обновленные системные инструкции останутся в силе до конца сеанса.
Быстрый
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');
}
Единство
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}");
}
Сжать контекстное окно
Чтобы просмотреть контент и код, относящиеся к вашему поставщику API Gemini , нажмите на него. |
Окно контекста сессии Live API хранит потоковые данные в реальном времени (25 токенов в секунду (TPS) для аудио и 258 TPS для видео), а также другой контент, включая текстовые входные данные и выходные данные модели. Для всех моделей Live API ограничение на размер окна контекста сессии составляет 128 000 токенов.
По умолчанию, из-за ограничения на контекстное окно, приблизительная максимальная продолжительность сеанса в зависимости от способа ввода данных выглядит следующим образом:
- Продолжительность сеансов ввода только аудиоконтента ограничена
15 минутами . - Видео- и аудиовход ограничены
2 минутами .
В длительных сессиях по мере развития разговора накапливается история аудио- и/или видеотокенов. Если эта история превышает лимит модели, модель может начать галлюцинировать, замедлиться, или сессия может быть принудительно завершена.
Для увеличения продолжительности сеансов можно включить сжатие контекстного окна , установив поле contextWindowCompression в параметре LiveGenerationConfig . При включении сервер использует механизм скользящего окна для автоматического удаления самых старых ходов или их суммирования, чтобы поддерживать размер контекста в пределах значений по умолчанию или заданных ограничений. Системные инструкции не удаляются и всегда остаются в начале контекстного окна.
С точки зрения пользователя, это позволяет теоретически обеспечить бесконечную продолжительность сеансов, поскольку «память» постоянно управляется.
Вы можете настроить механизм скользящего окна, а также , при необходимости, количество токенов, запускающих сжатие (см. доступные настройки и значения ниже). Вот несколько общих соображений по использованию этих настроек:
Установка очень низкого значения
targetTokensосвободит больше контекстного пространства для непрерывных потоков, но модель быстро «забудет» более ранние реплики разговора.Установка
targetTokensближе кtriggerTokensпозволяет сэкономить больше памяти, но при этом процедуры сжатия будут запускаться гораздо чаще.
| Параметр | Если в конфигурации не задано значение по умолчанию, будет использоваться скользящее окно. | Минимальное значение | Максимальное значение |
|---|---|---|---|
triggerTokensДлина контекста до запуска сжатия | 80% от лимита контекстного окна модели | 5000 | 128 000 |
targetTokensцелевое количество токенов, которое необходимо сохранить. | 50% от стоимости triggerTokens
| 0 | 128 000 |
Быстрый
// 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),
),
),
);
Единство
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)
)
)
);
Определять момент завершения сессии
Максимальная продолжительность одного непрерывного соединения WebSocket составляет около
В следующем примере показано, как обнаружить предстоящее завершение соединения, отслеживая уведомление о прекращении соединения:
Быстрый
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}');
}
}
Единство
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}");
}
}
Возобновить сессию
Live API поддерживает возобновление сессии, чтобы предотвратить потерю контекста разговора. Каждая сессия имеет свой идентификатор, который можно использовать следующими способами:
Поддержание сессии до истечения лимита времени соединения.
Максимальная продолжительность одного непрерывного соединения WebSocket составляет около
10 минут . Определить приближение завершения соединения можно , прослушав уведомление о завершении сеанса, а затем продлив его, установив новое соединение с использованием дескриптора сеанса.Возобновление сессии сразу после разрыва соединения.
Если соединение обрывается или прерывается до истечения максимального времени соединения (например, при переключении с Wi-Fi на 5G), сервер сохраняет состояние сессии примерно на
10 минут . В течение этого времени вы можете возобновить сессию, установив новое соединение, используя дескриптор сессии.Возобновление сессии после длительного перерыва.
После завершения соединения сервер сохраняет состояние сессии в течение нескольких часов. В течение этого времени вы можете возобновить сессию, установив новое соединение, используя дескриптор сессии. Обратите внимание, что этот период различен для двух поставщиков API Gemini : для Gemini Developer API —
2 часа , для Vertex AI Gemini API —24 часа .
По умолчанию возобновление сессии отключено. Чтобы включить возобновление сессии, передайте пустую конфигурацию возобновления при установлении нового соединения. При включении сервер периодически отправляет обновления, содержащие дескриптор возобновления сессии. Если сессия разорвана, вы можете повторно подключиться и передать этот дескриптор, чтобы возобновить сессию с сохранением ее контекста.
В следующих примерах показаны два варианта возобновления сессии:
Быстрый
// 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!),
);
}
Единство
// 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)
);
}