Gerenciar sessões da API Live 

O Gemini Live API processa streams 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 por uma conexão.

Se a sessão exceder qualquer um dos limites a seguir, a conexão será encerrada. No entanto, o Live API oferece algumas opções (veja abaixo) para lidar com esses limites relacionados à sessão.

  • A janela de contexto da sessão é limitada a 128 mil tokens.

    Devido a esse limite da janela de contexto, confira as durações máximas aproximadas da sessão com base nas modalidades de entrada:

    • As sessões de entrada somente de áudio são limitadas a 15 minutos.
    • A entrada de vídeo + áudio é limitada a 2 minutos.
  • A duração da conexão é limitada a cerca de 10 minutos.

    Você vai receber uma notificação de saída cerca de 60 segundos antes do encerramento da conexão.

Veja algumas opções para lidar com limites relacionados à sessão:

Iniciar uma sessão

Acesse o guia de iniciação do Live API para ver um snippet completo que mostra como iniciar uma sessão.

Atualizar no meio da sessão

Os modelos Live API são compatíveis com os seguintes recursos avançados para atualizações no meio da sessão:

Adicionar atualizações de conteúdo incrementais

É possível adicionar atualizações incrementais durante uma sessão ativa. Use isso para enviar entrada de texto, estabelecer o contexto da sessão ou restaurar o contexto da sessão.

  • Para contextos mais longos, recomendamos fornecer um resumo de uma única mensagem para liberar a janela de contexto para interações subsequentes.

  • Para contextos curtos, é possível enviar interações de navegação guiada 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

// Define initial turns (history/context).
val turns = listOf(
  content("user") {
    text("What is the capital of France?")
  },
  content("model") {
    text("Paris")
  }
)

// Send history, keeping the conversational turn OPEN (false).
turns.forEach {
  session.send(
    content = it,
    turnComplete = false
  )
}

// Define the new user query.
val newTurn = content("user") {
  text("What is the capital of Germany?")
}

// Send the final query, CLOSING the turn (true) to trigger the model response.
session.send(
  content = newTurn,
  turnComplete = true
)

Java

// Define initial turns (history/context).
List turns =
    Arrays.asList(
        new Content.Builder().setRole("user").addText("What is the capital of France?").build(),
        new Content.Builder().setRole("model").addText("Paris").build());

for (Content turn : turns) {
  session.send(
    turn,
    false // turnComplete: false
  );
}

// Define the new user query.
Content newTurn = new Content.Builder().addText("What is the capital of Germany?").build();

// Send the final query, CLOSING the turn (true) to trigger the model response.
session.send(
  newTurn,
  true // isTurnComplete: true
);

Web

const turns = [{ type: "text", 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 = [{ type: "text", 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",
    [TextPart("What is the capital of France?")],
  ),
  Content(
    "model",
    [TextPart("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",
    [TextPart("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 as instruções do sistema no meio da sessão

Disponível apenas ao usar o Agent Platform Gemini API (formerly Vertex AI) 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 da resposta ou modificar o tom.

Para atualizar as instruções do sistema no meio da sessão, envie conteúdo de texto com o papel system. As instruções atualizadas do sistema vão permanecer em vigor pelo restante da sessão.

Swift

await session.sendContent(
  [ModelContent(
    role: "system",
    parts: [TextPart("new system instruction")]
  )],
  turnComplete: false
)

Kotlin

// In a coroutine scope
session.send(
    content = content("system") {
        text("new system instruction")
    },
    turnComplete = false
)

Java

session.send(
    new Content.Builder()
        .setRole("system")
        .addText("new system instruction")
        .build(),
    /* turnComplete: */ false
);

Web

Not yet supported for Web apps - check back soon!

Dart

try {
  await _session.send(
    input: Content(
      'system',
      [TextPart('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}");
}

Sinalizar manualmente a atividade do usuário

Por padrão, a Live API detecta automaticamente o início e o fim da fala do usuário usando a detecção de atividade de voz (VAD, na sigla em inglês), que permite interromper o modelo a qualquer momento (saiba como lidar com interrupções).

No entanto, é possível assumir o controle manual completo sobre as interações de conversação (como para uma interface push-to-talk) desativando a detecção de atividade de voz (VAD, na sigla em inglês).

Se você desativar a VAD, o servidor não vai detectar automaticamente a fala do usuário nem acionar respostas com base no silêncio do áudio. Nesse cenário, é preciso demarcar manualmente os limites de cada turno de atividade do usuário.

Saiba como desativar a detecção automática de atividade de voz (VAD) e sinalizar manualmente a atividade do usuário.

Compactar a janela de contexto

Clique no seu provedor de Gemini API para conferir o conteúdo e o código específicos do provedor nesta página.

A janela de contexto da sessão do Live API armazena dados transmitidos em tempo real (25 tokens por segundo (TPS) para áudio e 258 TPS para vídeo), além de outros conteúdos, incluindo entradas de texto e saídas do modelo. Todos os modelos Live API têm um limite de janela de contexto de sessão de 128 mil tokens.

Por padrão, devido a esse limite da janela de contexto, estas são as durações máximas aproximadas das sessões com base nas modalidades de entrada:

  • As sessões de entrada somente de áudio são limitadas a 15 minutos.
  • A entrada de vídeo + áudio é limitada a 2 minutos.

Em sessões de longa duração, conforme a conversa avança, o histórico de tokens de áudio e/ou vídeo se acumula. Se esse histórico exceder o limite do modelo, ele poderá alucinar, ficar mais lento ou a sessão poderá ser encerrada à força.

Para permitir sessões mais longas, ative a compactação da janela de contexto definindo o campo contextWindowCompression como parte do LiveGenerationConfig. Quando ativado, o servidor usa um mecanismo de janela deslizante para descartar automaticamente as interações mais antigas ou resumi-las para manter o tamanho do contexto dentro dos limites padrão ou especificados. As instruções do sistema não são descartadas e sempre permanecem no início da janela de contexto.

Do ponto de vista do usuário, isso permite durações de sessão teoricamente infinitas, já que a "memória" é gerenciada constantemente.

É possível configurar o mecanismo de janela deslizante e, opcionalmente, o número de tokens que aciona a compactação (confira as configurações e os valores disponíveis abaixo). Confira algumas considerações gerais sobre o uso dessas configurações:

  • Definir targetTokens como um valor muito baixo vai liberar mais espaço de contexto para streams contínuos, mas o modelo vai "esquecer" rapidamente as partes mais antigas da conversa.

  • Definir targetTokens mais próximo de triggerTokens preserva mais memória, mas aciona rotinas de compactação com muito mais frequência.

Configuração Padrão para janela deslizante se não estiver definido na configuração Valor mínimo Valor máximo
triggerTokens
o tamanho do contexto antes que a compactação seja acionada
80% do limite da janela de contexto do modelo 5.000 128.000
targetTokens
o número desejado de tokens a serem mantidos
50% do valor de triggerTokens
  • Se triggerTokens não for definido explicitamente, targetTokens vai usar como padrão 50% do valor padrão de triggerTokens.
  • O valor de targetTokens precisa ser menor que o valor de triggerTokens.
0 128.000

Swift


// ...

let liveModel = FirebaseAI.firebaseAI(backend: .googleAI()).liveModel(
  modelName: "GEMINI_LIVE_API_MODEL_NAME",
  // 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


// ...

val liveModel = Firebase.ai(backend = GenerativeBackend.googleAI()).liveModel(
    modelName = "GEMINI_LIVE_API_MODEL_NAME",
    // 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


// ...

LiveGenerativeModel lm = FirebaseAI.getInstance(GenerativeBackend.googleAI()).liveModel(
        "GEMINI_LIVE_API_MODEL_NAME",
        // 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_LIVE_API_MODEL_NAME",
  // 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_LIVE_API_MODEL_NAME',
  // 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),
    ),
  ),
);

Unity


// ...

var liveModel = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()).GetLiveModel(
    modelName: "GEMINI_LIVE_API_MODEL_NAME",
    // 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)
        )
    )
);

Detectar quando uma sessão vai terminar

A duração máxima de uma única conexão WebSocket contínua é de cerca de 10 minutos. Uma notificação de saída é enviada ao cliente 60 segundos antes do término da conexão, o que pode ajudar você a tomar outras medidas (por exemplo, retomar uma sessão).

O exemplo a seguir mostra como detectar um encerramento de conexão iminente ouvindo uma notificação de saída:

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

Retomar uma sessão

O Live API permite retomar sessões para evitar a perda do contexto da conversa. Cada sessão tem um identificador, que pode ser usado das seguintes maneiras:

  • Manter uma sessão antes de atingir o limite de tempo de conexão

    A duração máxima de uma única conexão WebSocket contínua é de cerca de 10 minutos. É possível detectar quando uma conexão está prestes a terminar detectando uma notificação de saída e, em seguida, estendendo a sessão estabelecendo uma nova conexão usando o identificador da sessão.

  • Retomar uma sessão logo após uma queda de conexão

    Se uma conexão for encerrada ou cair antes do limite máximo de tempo de conexão (por exemplo, ao mudar de Wi-Fi para 5G), o servidor manterá o estado da sessão por cerca de 10 minutos. Durante esse período, é possível retomar a sessão estabelecendo uma nova conexão usando o identificador de sessão.

  • Retomar uma sessão após um período prolongado

    Depois que uma conexão é encerrada, o servidor mantém o estado da sessão por algumas horas. Durante esse período, é possível retomar a sessão estabelecendo uma nova conexão usando o identificador de sessão. Essa janela é diferente para os dois provedores de Gemini API: Gemini Developer API é de 2 horas | Agent Platform Gemini API (formerly Vertex AI) é de 24 horas.

Por padrão, a retomada de sessão está desativada. Para ativar a retomada de sessão, transmita uma configuração de retomada vazia ao estabelecer uma nova conexão. Quando ativado, o servidor envia periodicamente atualizações que contêm um identificador de retomada de sessão. Se a sessão for desconectada, você poderá se reconectar e transmitir esse identificador para retomar a sessão com o contexto intacto.

Os exemplos a seguir mostram duas opções para retomar a sessão:

Swift

// 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 response in _session.receive()) {
  // Process other received response types...

  // Check for new session handles inside your message handling loop
  final message = response.message;
  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!),
  );
}

Unity

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