Управление сессиями для Live API

Gemini Live API обрабатывает непрерывные потоки аудио или текста, называемые сессиями . Вы можете управлять жизненным циклом сессии, от первоначального установления соединения до корректного завершения.

Ограничения на количество сессий

В контексте Live API сессия обозначает постоянное соединение, при котором входные и выходные данные непрерывно передаются по одному и тому же соединению.

Если продолжительность сеанса превысит любой из следующих лимитов, соединение будет разорвано.

  • Продолжительность соединения ограничена примерно 10 минутами.

  • Длительность сеанса зависит от используемых способов ввода:

    • Продолжительность сеансов ввода только аудиоконтента ограничена 15 минутами.
    • Видео- и аудиовходы ограничены 2 минутами.
  • Окно контекста сессии ограничено 128 тысячами токенов.

Перед завершением соединения вы получите уведомление о прекращении подключения , которое позволит вам предпринять дальнейшие действия.

Начать сессию

Для получения подробной информации о том, как начать сессию, посетите руководство по началу работы с Live API .

Обновление в середине сессии

Модели Live 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}");
}

Определять момент завершения сессии

За 60 секунд до окончания сессии клиенту отправляется уведомление о завершении сеанса, позволяющее предпринять дальнейшие действия.

В следующем примере показано, как обнаружить предстоящее завершение сеанса, отслеживая уведомление о завершении сеанса :

Быстрый

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}");
    }
}