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 yayınlandığı 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ı yönetmek 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ş 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.
- Yalnızca sesli giriş oturumları
Bağlantı süresi yaklaşık
10 dakika ile sınırlıdır.Bağlantı sona ermeden
60 saniye önce kullanımdan kaldırılma bildirimi alırsınız.
Oturumla ilgili sınırlara yönelik bazı seçenekleri aşağıda bulabilirsiniz:
Sunucunun bağlam boyutunu sınır içinde otomatik olarak 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 görüşme bağlamını kaybetmemek için oturuma devam edin.
Oturum başlatma
Oturum başlatma hakkında tam bir snippet görmek için Live API başlangıç kılavuzunu ziyaret edin.
Oturum ortasında güncelleme
Live API modelleri, oturum ortasında güncellemeler için aşağıdaki gelişmiş özellikleri destekler:
Sistem talimatlarını güncelleme (yalnızca Vertex AI Gemini API için)
Artımlı içerik güncellemeleri ekleme
Etkin bir oturum sırasında artımlı güncellemeler ekleyebilirsiniz. Bu işlevi kullanarak metin girişi gönderebilir, oturum bağlamı oluşturabilir veya oturum bağlamını geri yükleyebilirsiniz.
Daha uzun bağlamlar için, sonraki etkileşimlerde bağlam penceresini boşaltmak amacıyla tek bir ileti ö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 etmek üzere 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
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,
);
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
);
Oturum ortasında sistem talimatlarını güncelleme
| Yalnızca Vertex AI Gemini API API sağlayıcısı olarak kullanılırken kullanılabilir. |
Etkin bir oturum sırasında sistem talimatlarını güncelleyebilirsiniz. Bunu, modelin yanıtlarını uyarlamak için kullanın. Örneğin, yanıt dilini değiştirebilir veya üslubu düzenleyebilirsiniz.
Sistem talimatlarını oturum ortasında güncellemek için system rolüyle metin içeriği gönderebilirsiniz. Güncellenen sistem talimatları, oturumun geri kalanı için geçerli olmaya devam edecek.
Swift
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');
}
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 kodu 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 yayınlanan verileri (ses için saniyede 25 jeton (TPS), video için 258 TPS) ve metin girişleri ile model çıkışları gibi diğer içerikleri depolar. Tüm Live API modellerinde 128 bin parçalık oturum bağlamı penceresi sınırı vardır.
Varsayılan olarak, bu bağlam penceresi sınırı nedeniyle, 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 sağlamak için contextWindowCompression alanını LiveGenerationConfig'ün bir parçası olarak ayarlayarak bağlam penceresi sıkıştırmayı etkinleştirebilirsiniz. Etkinleştirildiğinde sunucu, bağlam boyutunu varsayılan veya belirtilen sınırlar içinde tutmak için en eski dönüşleri otomatik olarak silmek ya da özetlemek üzere kayan pencere mekanizmasını kullanır. Sistem talimatları atılmaz ve her zaman bağlam penceresinin başında kalır.
Kullanıcı açısından bu, "bellek" sürekli olarak yönetildiğinden teorik olarak sonsuz oturum sürelerine olanak tanır.
Kayar pencere mekanizmasını ve isteğe bağlı olarak sıkıştırmayı tetikleyen jeton sayısını yapılandırabilirsiniz (Aşağıda, kullanılabilir ayarları ve değerleri görebilirsiniz). Bu ayarları kullanmayla ilgili bazı önemli noktaları aşağıda bulabilirsiniz:
targetTokensayarını çok düşürmek, sürekli akışlar için daha fazla bağlam alanı açar ancak model, konuşmanın eski dönüşlerini hızla "unutur".targetTokensdeğerinitriggerTokensdeğerine daha yakın ayarlamak daha fazla bellek saklar 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 |
targetTokensSaklanacak hedef jeton sayısı |
triggerTokens değerinin% 50'si
|
0 | 128.000 |
Swift
// 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),
),
),
);
Unity
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)
)
)
);
Oturumun ne zaman sona ereceğini algılama
Tek bir kesintisiz WebSocket bağlantısının maksimum süresi yaklaşık
Aşağıdaki örnekte, going away bildirimi dinlenerek bağlantının yakında sonlandırılacağının nasıl tespit edileceği 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}");
}
}
Oturuma devam etme
Live API, sohbet bağlamının kaybolmasını önlemek için oturum devam ettirmeyi destekler. Her oturumun bir tanımlayıcısı vardır ve bu tanımlayıcı aşağıdaki şekillerde kullanılabilir:
Bağlantı zaman sınırına ulaşmadan oturumu sürdürme
Tek bir kesintisiz WebSocket bağlantısının maksimum süresi yaklaşık
10 dakikadır . Bir bağlantının ne zaman sona ereceğini going away bildirimini dinleyerek tespit edebilir ve ardından oturum tutamacını kullanarak yeni bir bağlantı oluşturarak 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 (örneğin, kablosuz ağdan 5G'ye geçiş yapılması), sunucu oturum durumunu yaklaşık
10 dakika boyunca korur. Bu süre zarfında, oturum tutamacını kullanarak yeni bir bağlantı oluşturarak oturuma devam edebilirsiniz.Uzun bir süre sonra oturuma devam etme
Bir bağlantı sona erdikten sonra sunucu, oturum durumunu birkaç saat boyunca saklar. Bu süre boyunca, 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 | Vertex AI Gemini API için24 saattir .
Oturuma devam etme özelliği varsayılan olarak devre dışıdır. Oturuma devam etme özelliğini etkinleştirmek için yeni bir bağlantı oluştururken boş bir devam etme yapılandırması iletin. Etkinleştirildiğinde sunucu, oturum devam ettirme işleyicisi içeren güncellemeleri düzenli olarak gönderir. Oturumun bağlantısı kesilirse yeniden bağlanabilir ve bu tutma yerini ileterek oturuma bağlamı bozulmadan devam edebilirsiniz.
Aşağıdaki örneklerde oturuma devam etmek 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)
);
}