Gemini Live API は、セッションと呼ばれる音声またはテキストの連続ストリームを処理します。最初のハンドシェイクから正常な終了まで、セッションのライフサイクルを管理できます。
セッションの上限
Live API の場合、セッションとは、入力と出力が接続を介して継続的にストリーミングされる永続的な接続を指します。
セッションが次のいずれかの上限を超えると、接続が終了します。ただし、Live API には、これらのセッション関連の上限を処理するためのオプションがいくつか用意されています(下記参照)。
セッション コンテキスト ウィンドウは 128k トークンに制限されています。
このコンテキスト ウィンドウの上限により、入力モダリティに基づくセッションの最大長は次のようになります。
- 音声のみの入力セッションは
15 分 に制限されています。 - 動画と音声の入力は
2 分 に制限されています。
- 音声のみの入力セッションは
接続時間は
10 分 程度に制限されています。接続が終了する約
60 秒 前に、going away 通知が届きます。
セッション関連の制限を処理するには、次の方法があります。
セッション コンテキスト ウィンドウを圧縮して、サーバーがコンテキスト サイズを自動的に上限内に維持するようにします。
セッションを再開して、ネットワークが一時的に切断された場合や、going away 通知を受け取った後に、会話のコンテキストが失われないようにします。
セッションを開始する
セッションを開始する方法を示す完全なスニペットについては、Live API のスタートガイドをご覧ください。
セッション中の更新
Live API モデルは、セッション中の更新に関する次の高度な機能をサポートしています。
システム指示を更新する (Agent Platform Gemini API (formerly Vertex AI) のみ)
コンテンツの増分更新を追加する
アクティビティ セッション中に増分アップデートを追加できます。これを使用して、テキスト入力の送信、セッション コンテキストの確立、セッション コンテキストの復元を行います。
コンテキストが長い場合は、1 つのメッセージの概要を提供して、後続のインタラクション用にコンテキスト ウィンドウを空けておくことをおすすめします。
コンテキストが短い場合は、ターンバイターンのインタラクションを送信して、イベントの正確なシーケンスを表すことができます。
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
);
セッション中にシステム指示を更新する
| API プロバイダとして Agent Platform Gemini API (formerly Vertex AI) を使用している場合にのみ使用できます。 |
アクティビティ セッション中にシステム指示を更新できます。これを使用して、レスポンスの言語の変更やトーンの変更など、モデルのレスポンスを調整します。
セッション中にシステム指示を更新するには、system ロールでテキスト コンテンツを送信します。更新されたシステム指示は、セッションの残りの部分で有効になります。
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}");
}
ユーザー アクティビティを手動で通知する
デフォルトでは、Live API は音声検出(VAD)を使用してユーザーの発話の開始と終了を自動的に検出します。これにより、モデルをいつでも中断できます(中断を処理する方法をご覧ください)。
ただし、自動音声検出(VAD)を無効にすることで、会話のターン(プッシュ ツー トーク インターフェースなど)を手動で完全に制御できます。
VAD を無効にすると、サーバーはユーザーの音声を自動的に検出したり、音声の無音に基づいてレスポンスをトリガーしたりしません。このシナリオでは、各ユーザー アクティビティ ターンの境界を手動で区切る必要があります。
自動音声検出(VAD)を無効にして、ユーザー アクティビティを手動で通知する方法を学習する。
コンテキスト ウィンドウを圧縮する
|
Gemini API プロバイダをクリックして、このページでプロバイダ固有のコンテンツとコードを表示します。 |
Live API セッション コンテキスト ウィンドウには、リアルタイムでストリーミングされたデータ(音声の場合は 1 秒あたり 25 トークン(TPS)、動画の場合は 258 TPS)や、テキスト入力やモデル出力などの他のコンテンツが保存されます。すべての Live API モデルには、128,000 トークンのセッション コンテキスト ウィンドウの上限があります。
デフォルトでは、このコンテキスト ウィンドウの上限により、入力モダリティに基づくおおよその最大セッション長は次のようになります。
- 音声のみの入力セッションは
15 分 に制限されています。 - 動画と音声の入力は
2 分 に制限されています。
長時間実行されるセッションでは、会話の進行に伴い、音声トークンや動画トークンの履歴が蓄積されます。この履歴がモデルの上限を超えると、モデルがハルシネーションを起こしたり、速度が低下したり、セッションが強制終了されたりする可能性があります。
セッションを長くするには、LiveGenerationConfig の一部として contextWindowCompression フィールドを設定して、コンテキスト ウィンドウの圧縮を有効にします。有効にすると、サーバーはスライディング ウィンドウ メカニズムを使用して、最も古いターンを自動的に破棄するか、要約して、コンテキスト サイズをデフォルトまたは指定された上限内に維持します。システム指示は破棄されず、常にコンテキスト ウィンドウの先頭に配置されます。
ユーザーの観点から見ると、この方法では「メモリ」が常に管理されるため、理論上はセッションの継続時間を無限にすることができます。
スライディング ウィンドウ メカニズムと、圧縮をトリガーするトークン数を構成できます(省略可)。使用可能な設定と値については、以下をご覧ください。これらの設定を使用する際の主な考慮事項は次のとおりです。
targetTokensを非常に低く設定すると、継続的なストリームのコンテキスト ルームが解放されますが、モデルは会話の古いターンをすぐに「忘れて」しまいます。targetTokensをtriggerTokensに近づけると、より多くのメモリが保持されますが、圧縮ルーティンがより頻繁にトリガーされます。
| 設定 | 構成で設定されていない場合のスライディング ウィンドウのデフォルト | 最小値 | 最大値 |
|---|---|---|---|
triggerTokens圧縮がトリガーされる前のコンテキストの長さ |
モデルのコンテキスト ウィンドウの上限の 80% | 5,000 | 128,000 |
targetTokens保持するトークンの目標数 |
triggerTokens 値の 50%
|
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)
)
)
);
セッションが終了するタイミングを検出する
1 つの継続的な WebSocket 接続の最大時間は約
次の例は、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}");
}
}
セッションを再開する
Live API は、会話のコンテキストが失われないように、セッションの再開をサポートしています。すべてのセッションにはハンドルがあり、次の方法で使用できます。
接続時間の上限に達する前にセッションを維持する
1 つの継続的な WebSocket 接続の最大時間は約
10 分 です。接続が終了するタイミングを検出するには、going away 通知をリッスンし、セッション ハンドルを使用して新しい接続を確立することでセッションを延長します。接続が切断された直後にセッションを再開する
最大接続時間の上限に達する前に接続が終了または切断された場合(Wi-Fi から 5G への切り替えなど)、サーバーはセッション状態を約 10 分間保持します。
この期間中は、セッション ハンドルを使用して新しい接続を確立することで、セッションを再開できます。 長期間経過後にセッションを再開する
接続が終了した後、サーバーはセッション状態を数時間保持します。この期間中は、セッション ハンドルを使用して新しい接続を確立することで、セッションを再開できます。このウィンドウは、2 つの Gemini API プロバイダで異なります。Gemini Developer API は
2 時間 、Agent Platform Gemini API (formerly Vertex AI) は24 時間 です。
デフォルトでは、セッションの再開は無効になっています。セッションの再開を有効にするには、新しい接続を確立するときに空の再開構成を渡します。有効にすると、サーバーはセッション再開ハンドルを含む更新を定期的に送信します。セッションが切断された場合は、再接続してこのハンドルを渡すことで、コンテキストをそのままにしてセッションを再開できます。
次の例は、セッションを再開するための 2 つのオプションを示しています。
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)
);
}