Gemini Live API, oturum adı verilen sürekli ses veya metin akışlarını işler. İlk el sıkışmadan düzgün sonlandırmaya kadar oturum yaşam döngüsünü yönetebilirsiniz.
Oturumlarla ilgili sınırlar
Live API için oturum, giriş ve çıkışın bağlantı üzerinden sürekli olarak aktarıldığı kalıcı bir bağlantıyı ifade eder.
Oturum aşağıdaki sınırlardan herhangi birini aşarsa bağlantı sonlandırılır. Ancak Live API, oturumla ilgili bu sınırları ele almak için bazı seçenekler (aşağıya bakın) sunar.
Oturum bağlam penceresi 128 bin jetonla sınırlıdır.
Bu bağlam penceresi sınırı nedeniyle, giriş yöntemlerine göre yaklaşık maksimum oturum uzunlukları aşağıda verilmiştir:
- Yalnızca sesli giriş oturumları
15 dakika ile sınırlıdır. - Video ve ses girişi
2 dakika ile sınırlıdır.
- Yalnızca sesli giriş oturumları
Bağlantı süresi yaklaşık
10 dakika ile sınırlıdır.Bağlantı sona ermeden yaklaşık
60 saniye önce bağlantının kesileceğine dair bir bildirim alırsınız.
Oturumla ilgili sınırları ele almak için kullanabileceğiniz bazı seçenekler şunlardır:
Sunucunun bağlam boyutunu otomatik olarak sınır içinde tutması için oturum bağlam penceresini sıkıştırın.
Kısa süreli ağ bağlantısı kesintilerinde veya ayrılma bildirimi aldıktan sonra sohbet bağlamını kaybetmemek için oturuma devam edin.
Oturum başlatma
Oturum başlatma işleminin nasıl yapılacağını gösteren tam bir snippet için Live API başlangıç kılavuzunu ziyaret edin.
Oturum ortasında güncelleme
Live API modelleri, oturum ortası güncellemeler için aşağıdaki gelişmiş özellikleri destekler:
Sistem talimatlarını güncelleme (yalnızca Agent Platform Gemini API (formerly Vertex AI) için)
Artımlı içerik güncellemeleri ekleme
Etkin bir oturum sırasında artımlı güncellemeler ekleyebilirsiniz. Metin girişi göndermek, oturum bağlamı oluşturmak veya oturum bağlamını geri yüklemek için kullanılır.
Daha uzun bağlamlar için, sonraki etkileşimlerde bağlam penceresini boşaltmak amacıyla tek bir mesaj özeti sağlamanızı öneririz.
Kısa bağlamlar için, aşağıdaki snippet'te olduğu gibi, etkinliklerin tam sırasını temsil eden adım adım etkileşimler gönderebilirsiniz.
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",
[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
);
Sistem talimatlarını oturumun ortasında güncelleme
| Yalnızca API sağlayıcınız olarak Agent Platform Gemini API (formerly Vertex AI) kullanıldığında kullanılabilir. |
Sistem talimatlarını etkin bir oturum sırasında güncelleyebilirsiniz. Modelin yanıtlarını uyarlamak (ör. yanıt dilini veya üslubunu değiştirmek) için bu seçeneği kullanın.
Sistem talimatlarını oturum sırasında güncellemek için system rolüyle metin içeriği gönderebilirsiniz. Güncellenen sistem talimatları, oturumun geri kalanında geçerli olmaya devam eder.
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',
[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}");
}
Bağlam penceresini sıkıştırma
|
Bu sayfada sağlayıcıya özel içerikleri ve kodları görüntülemek için Gemini API sağlayıcınızı tıklayın. |
Live API Oturum bağlam penceresi, gerçek zamanlı olarak aktarılan verileri (ses için saniyede 25 jeton (TPS) ve video için 258 TPS) ve metin girişleri ile model çıkışları gibi diğer içerikleri depolar. Tüm Live API modellerinde oturum bağlam penceresi sınırı 128 bin parçadır.
Bu bağlam penceresi sınırı nedeniyle varsayılan olarak giriş biçimlerine göre yaklaşık maksimum oturum uzunlukları şunlardır:
- Yalnızca sesli giriş oturumları
15 dakika ile sınırlıdır. - Video ve ses girişi
2 dakika ile sınırlıdır.
Uzun süren oturumlarda, sohbet ilerledikçe ses ve/veya video jetonlarının geçmişi birikir. Bu geçmiş, modelin sınırını aşarsa model halüsinasyon görebilir, yavaşlayabilir veya oturum zorla sonlandırılabilir.
Daha uzun oturumlar için LiveGenerationConfig kapsamında contextWindowCompression alanını ayarlayarak bağlam penceresi sıkıştırmayı etkinleştirebilirsiniz. Etkinleştirildiğinde sunucu, varsayılan veya belirtilen sınırlar içinde bağlam boyutunu korumak için en eski sıraları otomatik olarak silmek veya özetlemek üzere kayan pencere mekanizması kullanır. Sistem talimatları atılmaz ve her zaman bağlam penceresinin başında kalır.
Kullanıcı açısından bakıldığında bu, "bellek" sürekli olarak yönetildiği için teorik olarak sonsuz oturum sürelerine olanak tanır.
Kayan pencere mekanizmasını ve isteğe bağlı olarak sıkıştırmayı tetikleyen jeton sayısını yapılandırabilirsiniz (mevcut ayarları ve değerleri aşağıda bulabilirsiniz). Bu ayarları kullanmayla ilgili bazı önemli noktaları aşağıda bulabilirsiniz:
targetTokensdeğerini çok düşük ayarlamak, sürekli akışlar için daha fazla bağlam alanı açar ancak model, sohbetin eski dönüşlerini hızla "unutur".targetTokensdeğerinitriggerTokensdeğerine yaklaştırmak daha fazla bellek tasarrufu sağlar ancak sıkıştırma rutinlerini çok daha sık tetikler.
| Ayar | Yapılandırmada ayarlanmamışsa kayan pencere için varsayılan değer | Minimum değer | Maksimum değer |
|---|---|---|---|
triggerTokenssıkıştırma tetiklenmeden önceki bağlam uzunluğu |
Modelin bağlam penceresi sınırının% 80'i | 5.000 | 128.000 |
targetTokenstutulacak hedef jeton sayısı |
triggerTokens değerinin% 50'si
|
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)
)
)
);
Oturumun ne zaman sona ereceğini algılama
Tek ve kesintisiz bir WebSocket bağlantısının maksimum süresi yaklaşık
Aşağıdaki örnekte, going away bildirimini dinleyerek yaklaşan bir bağlantı sonlandırmanın nasıl algılanacağı gösterilmektedir:
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}");
}
}
Oturumu devam ettirme
Live API, sohbet bağlamının kaybolmasını önlemek için oturumun devam ettirilmesini destekler. Her oturumun bir herkese açık kullanıcı adı vardır ve bu ad aşağıdaki şekillerde kullanılabilir:
Bağlantı süresi sınırına ulaşmadan önce oturumu sürdürme
Tek ve kesintisiz bir WebSocket bağlantısının maksimum süresi yaklaşık
10 dakikadır . going away bildirimini dinleyerek bir bağlantının ne zaman sona ereceğini tespit edebilir ve ardından oturum tutamacını kullanarak yeni bir bağlantı oluşturup oturumu uzatabilirsiniz.Bağlantı kesildikten hemen sonra oturuma devam etme
Maksimum bağlantı süresi sınırından önce bir bağlantı sonlandırılırsa veya düşerse (ör. kablosuzdan 5G'ye geçiş), sunucu oturum durumunu yaklaşık
10 dakika boyunca korur. Bu süre zarfında, oturum tutamacını kullanarak yeni bir bağlantı oluşturup oturumu devam ettirebilirsiniz.Uzun bir süre sonra oturumu devam ettirme
Bir bağlantı sona erdikten sonra sunucu, oturum durumunu birkaç saat boyunca saklar. Bu süre içinde oturum tutamacını kullanarak yeni bir bağlantı oluşturarak oturuma devam edebilirsiniz. Bu sürenin iki Gemini API sağlayıcısı için farklı olduğunu unutmayın: Gemini Developer API için
2 saat | Agent Platform Gemini API (formerly Vertex AI) için24 saattir .
Oturum devam ettirme varsayılan olarak devre dışıdır. Oturumun devam ettirilmesini etkinleştirmek için yeni bir bağlantı oluştururken boş bir devam ettirme yapılandırması iletin. Etkinleştirildiğinde sunucu, düzenli olarak oturum devam ettirme tanıtıcısı içeren güncellemeler gönderir. Oturumun bağlantısı kesilirse yeniden bağlanabilir ve oturumu bağlamı bozulmadan devam ettirmek için bu herkese açık kullanıcı adını iletebilirsiniz.
Aşağıdaki örneklerde, oturumu devam ettirmek için iki seçenek gösterilmektedir:
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 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!),
);
}
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)
);
}