Gemini Live API, Gemini ile düşük gecikmeli iki yönlü metin ve ses etkileşimlerini sağlar. Live API'ü kullanarak son kullanıcılara metin veya sesli komutlar kullanarak modelin yanıtlarını kesintiye uğratma olanağı sunan, doğal ve insan benzeri sesli sohbet deneyimi sağlayabilirsiniz. Model, metin ve ses girişini işleyebilir (video yakında kullanıma sunulacak) ve metin ile ses çıkışı sağlayabilir.
Vertex AI Studio'de istemler ve Live API ile prototip oluşturabilirsiniz.
Live API, istemci ile Gemini sunucusu arasında oturum oluşturmak için WebSocket bağlantısı oluşturan durum bilgisine sahip bir API'dir. Ayrıntılar için Live API referans belgelerine bakın.
Başlamadan önce
Yalnızca API sağlayıcınız olarak Vertex AI Gemini API kullanıldığında kullanılabilir. |
Henüz yapmadıysanız Firebase projenizi oluşturma, uygulamanızı Firebase'e bağlama, SDK'yı ekleme, Vertex AI Gemini API için arka uç hizmetini başlatma ve LiveModel
örneği oluşturma hakkında bilgi veren başlangıç kılavuzunu tamamlayın.
Bu özelliği destekleyen modeller
Live API yalnızca gemini-2.0-flash-live-preview-04-09
tarafından desteklenir (gemini-2.0-flash
tarafından desteklenmez).
Live API'ün standart özelliklerini kullanma
Bu bölümde, Live API'ün standart özelliklerinin özellikle çeşitli giriş ve çıkış türlerini yayınlamak için nasıl kullanılacağı açıklanmaktadır:
- Kısa mesaj gönderme ve alma
- Ses gönderme ve alma
- Ses gönderme ve metin alma
- Metin gönderme ve ses alma
Aktarılan metin girişinden aktarılan metin oluşturma
Bu örneği denemeden önce, projenizi ve uygulamanızı oluşturmak için bu kılavuzun Başlamadan önce bölümünü tamamlayın. Bu sayfada sağlayıcıya özel içerikleri görmek için seçtiğiniz Gemini API sağlayıcının düğmesini de bu bölümde tıklayacaksınız. |
Akışlı metin girişi gönderebilir ve akışlı metin çıkışı alabilirsiniz. Bir liveModel
örneği oluşturduğunuzdan ve yanıt modunu Text
olarak ayarladığınızdan emin olun.
Swift
Live API henüz Apple platform uygulamaları için desteklenmemektedir. Kısa süre sonra tekrar kontrol edin.
Kotlin
// Initialize the Vertex AI Gemini API backend service
// Create a `LiveModel` instance with the model that supports the Live API
val model = Firebase.vertexAI.liveModel(
modelName = "gemini-2.0-flash-live-preview-04-09",
// Configure the model to respond with text
generationConfig = liveGenerationConfig {
responseModality = ResponseModality.TEXT
}
)
val session = model.connect()
// Provide a text prompt
val text = "tell a short story"
session.send(text)
var outputText = ""
session.receive().collect {
if(it.status == Status.TURN_COMPLETE) {
// Optional: if you don't require to send more requests.
session.stopReceiving();
}
outputText = outputText + it.text
}
// Output received from the server.
println(outputText)
Java
ExecutorService executor = Executors.newFixedThreadPool(1);
// Initialize the Vertex AI Gemini API backend service
// Create a `LiveModel` instance with the model that supports the Live API
LiveGenerativeModel lm = FirebaseAI.getInstance(GenerativeBackend.vertexAI()).liveModel(
"gemini-2.0-flash-live-preview-04-09",
// Configure the model to respond with text
new LiveGenerationConfig.Builder()
.setResponseModalities(ResponseModality.TEXT)
.build()
);
LiveModelFutures model = LiveModelFutures.from(lm);
ListenableFuture<LiveSession> sessionFuture = model.connect();
class LiveContentResponseSubscriber implements Subscriber<LiveContentResponse> {
@Override
public void onSubscribe(Subscription s) {
s.request(Long.MAX_VALUE); // Request an unlimited number of items
}
@Override
public void onNext(LiveContentResponse liveContentResponse) {
// Handle the response from the server.
System.out.println(liveContentResponse.getText());
}
@Override
public void onError(Throwable t) {
System.err.println("Error: " + t.getMessage());
}
@Override
public void onComplete() {
System.out.println("Done receiving messages!");
}
}
Futures.addCallback(sessionFuture, new FutureCallback<LiveSession>() {
@Override
public void onSuccess(LiveSession ses) {
LiveSessionFutures session = LiveSessionFutures.from(ses);
// Provide a text prompt
String text = "tell me a short story?";
session.send(text);
Publisher<LiveContentResponse> publisher = session.receive();
publisher.subscribe(new LiveContentResponseSubscriber());
}
@Override
public void onFailure(Throwable t) {
// Handle exceptions
}
}, executor);
Web
Live API henüz web uygulamaları için desteklenmemektedir. Lütfen daha sonra tekrar kontrol edin.
Dart
import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
late LiveModelSession _session;
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Vertex AI Gemini API backend service
// Create a `LiveModel` instance with the model that supports the Live API
final model = FirebaseAI.vertexAI().liveModel(
model: 'gemini-2.0-flash-live-preview-04-09',
// Configure the model to respond with text
config: LiveGenerationConfig(responseModalities: [ResponseModality.text]),
);
_session = await model.connect();
// Provide a text prompt
final prompt = Content.text('tell a short story');
await _session.send(input: prompt, turnComplete: true);
// In a separate thread, receive the response
await for (final message in _session.receive()) {
// Process the received message
}
Unity
using Firebase;
using Firebase.AI;
async Task SendTextReceiveText() {
// Initialize the Vertex AI Gemini API backend service
// Create a `LiveModel` instance with the model that supports the Live API
var model = FirebaseAI.GetInstance(FirebaseAI.Backend.VertexAI()).GetLiveModel(
modelName: "gemini-2.0-flash-live-preview-04-09",
// Configure the model to respond with text
liveGenerationConfig: new LiveGenerationConfig(
responseModalities: new[] { ResponseModality.Text })
);
LiveSession session = await model.ConnectAsync();
// Provide a text prompt
var prompt = ModelContent.Text("tell a short story");
await session.SendAsync(content: prompt, turnComplete: true);
// Receive the response
await foreach (var message in session.ReceiveAsync()) {
// Process the received message
if (!string.IsNullOrEmpty(message.Text)) {
UnityEngine.Debug.Log("Received message: " + message.Text);
}
}
}
Kullanım alanınıza ve uygulamanıza uygun bir model nasıl seçeceğinizi öğrenin.
Akışlı ses girişinden akışlı ses oluşturma
Bu örneği denemeden önce, projenizi ve uygulamanızı oluşturmak için bu kılavuzun Başlamadan önce bölümünü tamamlayın. Bu sayfada sağlayıcıya özel içerikleri görmek için seçtiğiniz Gemini API sağlayıcının düğmesini de bu bölümde tıklayacaksınız. |
Aktarılan ses girişi gönderebilir ve aktarılan ses çıkışı alabilirsiniz. Bir LiveModel
örneği oluşturduğunuzdan ve yanıt modunu Audio
olarak ayarladığınızdan emin olun.
Yanıt sesini nasıl yapılandıracağınızı ve özelleştireceğinizi öğrenin (bu sayfanın sonraki bölümlerinde).
Swift
Live API henüz Apple platform uygulamaları için desteklenmemektedir. Kısa süre sonra tekrar kontrol edin.
Kotlin
// Initialize the Vertex AI Gemini API backend service
// Create a `LiveModel` instance with the model that supports the Live API
val model = Firebase.vertexAI.liveModel(
modelName = "gemini-2.0-flash-live-preview-04-09",
// Configure the model to respond with text
generationConfig = liveGenerationConfig {
responseModality = ResponseModality.AUDIO
}
)
val session = model.connect()
// This is the recommended way.
// However, you can create your own recorder and handle the stream.
session.startAudioConversation()
Java
ExecutorService executor = Executors.newFixedThreadPool(1);
// Initialize the Vertex AI Gemini API backend service
// Create a `LiveModel` instance with the model that supports the Live API
LiveGenerativeModel lm = FirebaseAI.getInstance(GenerativeBackend.vertexAI()).liveModel(
"gemini-2.0-flash-live-preview-04-09",
// Configure the model to respond with text
new LiveGenerationConfig.Builder()
.setResponseModalities(ResponseModality.TEXT)
.build()
);
LiveModelFutures model = LiveModelFutures.from(lm);
ListenableFuture<LiveSession> sessionFuture = model.connect();
Futures.addCallback(sessionFuture, new FutureCallback<LiveSession>() {
@Override
public void onSuccess(LiveSession ses) {
LiveSessionFutures session = LiveSessionFutures.from(ses);
session.startAudioConversation();
}
@Override
public void onFailure(Throwable t) {
// Handle exceptions
}
}, executor);
Web
Live API henüz web uygulamaları için desteklenmemektedir. Lütfen daha sonra tekrar kontrol edin.
Dart
import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
import 'package:your_audio_recorder_package/your_audio_recorder_package.dart';
late LiveModelSession _session;
final _audioRecorder = YourAudioRecorder();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Vertex AI Gemini API backend service
// Create a `LiveModel` instance with the model that supports the Live API
final model = FirebaseAI.vertexAI().liveModel(
model: 'gemini-2.0-flash-live-preview-04-09',
// Configure the model to respond with audio
config: LiveGenerationConfig(responseModalities: [ResponseModality.audio]),
);
_session = await model.connect();
final audioRecordStream = _audioRecorder.startRecordingStream();
// Map the Uint8List stream to InlineDataPart stream
final mediaChunkStream = audioRecordStream.map((data) {
return InlineDataPart('audio/pcm', data);
});
await _session.startMediaStream(mediaChunkStream);
// In a separate thread, receive the audio response from the model
await for (final message in _session.receive()) {
// Process the received message
}
Unity
using Firebase;
using Firebase.AI;
async Task SendTextReceiveAudio() {
// Initialize the Vertex AI Gemini API backend service
// Create a `LiveModel` instance with the model that supports the Live API
var model = FirebaseAI.GetInstance(FirebaseAI.Backend.VertexAI()).GetLiveModel(
modelName: "gemini-2.0-flash-live-preview-04-09",
// Configure the model to respond with audio
liveGenerationConfig: new LiveGenerationConfig(
responseModalities: new[] { ResponseModality.Audio })
);
LiveSession session = await model.ConnectAsync();
// Start a coroutine to send audio from the Microphone
var recordingCoroutine = StartCoroutine(SendAudio(session));
// Start receiving the response
await ReceiveAudio(session);
}
IEnumerator SendAudio(LiveSession liveSession) {
string microphoneDeviceName = null;
int recordingFrequency = 16000;
int recordingBufferSeconds = 2;
var recordingClip = Microphone.Start(microphoneDeviceName, true,
recordingBufferSeconds, recordingFrequency);
int lastSamplePosition = 0;
while (true) {
if (!Microphone.IsRecording(microphoneDeviceName)) {
yield break;
}
int currentSamplePosition = Microphone.GetPosition(microphoneDeviceName);
if (currentSamplePosition != lastSamplePosition) {
// The Microphone uses a circular buffer, so we need to check if the
// current position wrapped around to the beginning, and handle it
// accordingly.
int sampleCount;
if (currentSamplePosition > lastSamplePosition) {
sampleCount = currentSamplePosition - lastSamplePosition;
} else {
sampleCount = recordingClip.samples - lastSamplePosition + currentSamplePosition;
}
if (sampleCount > 0) {
// Get the audio chunk
float[] samples = new float[sampleCount];
recordingClip.GetData(samples, lastSamplePosition);
// Send the data, discarding the resulting Task to avoid the warning
_ = liveSession.SendAudioAsync(samples);
lastSamplePosition = currentSamplePosition;
}
}
// Wait for a short delay before reading the next sample from the Microphone
const float MicrophoneReadDelay = 0.5f;
yield return new WaitForSeconds(MicrophoneReadDelay);
}
}
Queue audioBuffer = new();
async Task ReceiveAudio(LiveSession liveSession) {
int sampleRate = 24000;
int channelCount = 1;
// Create a looping AudioClip to fill with the received audio data
int bufferSamples = (int)(sampleRate * channelCount);
AudioClip clip = AudioClip.Create("StreamingPCM", bufferSamples, channelCount,
sampleRate, true, OnAudioRead);
// Attach the clip to an AudioSource and start playing it
AudioSource audioSource = GetComponent();
audioSource.clip = clip;
audioSource.loop = true;
audioSource.Play();
// Start receiving the response
await foreach (var message in liveSession.ReceiveAsync()) {
// Process the received message
foreach (float[] pcmData in message.AudioAsFloat) {
lock (audioBuffer) {
foreach (float sample in pcmData) {
audioBuffer.Enqueue(sample);
}
}
}
}
}
// This method is called by the AudioClip to load audio data.
private void OnAudioRead(float[] data) {
int samplesToProvide = data.Length;
int samplesProvided = 0;
lock(audioBuffer) {
while (samplesProvided < samplesToProvide && audioBuffer.Count > 0) {
data[samplesProvided] = audioBuffer.Dequeue();
samplesProvided++;
}
}
while (samplesProvided < samplesToProvide) {
data[samplesProvided] = 0.0f;
samplesProvided++;
}
}
Kullanım alanınıza ve uygulamanıza uygun bir model nasıl seçeceğinizi öğrenin.
Daha ilgi çekici ve etkileşimli deneyimler oluşturun
Bu bölümde, Live API'te daha ilgi çekici veya etkileşimli özellikler oluşturma ve yönetme hakkında bilgi verilmektedir.
Yanıt sesini değiştirme
Live API, sentezlenmiş konuşma yanıtlarını desteklemek için Chirp 3'ü kullanır. Firebase AI Logic'ü kullanırken 5 HD ses ve 31 dilde ses gönderebilirsiniz.
Ses belirtmezseniz varsayılan olarak Puck
kullanılır. Alternatif olarak, modeli aşağıdaki seslerden birinde yanıt verecek şekilde yapılandırabilirsiniz:
Aoede (kadın)Charon (erkek) |
Fenrir (erkek)Kore (kadın) |
Puck (erkek) |
Bu seslerin nasıl ses çıkardığını gösteren demoları ve kullanılabilen dillerin tam listesini Chirp 3: HD sesler başlıklı makalede bulabilirsiniz.
Ses belirlemek için speechConfig
nesnesinde ses adını model yapılandırmasının bir parçası olarak ayarlayın:
Swift
Live API henüz Apple platform uygulamaları için desteklenmemektedir. Kısa süre sonra tekrar kontrol edin.
Kotlin
// ...
val model = Firebase.vertexAI.liveModel(
modelName = "gemini-2.0-flash-live-preview-04-09",
// Configure the model to use a specific voice for its audio response
generationConfig = liveGenerationConfig {
responseModality = ResponseModality.AUDIO
speechConfig = SpeechConfig(voice = Voices.FENRIR)
}
)
// ...
Java
// ...
LiveModel model = Firebase.getVertexAI().liveModel(
"gemini-2.0-flash-live-preview-04-09",
// Configure the model to use a specific voice for its audio response
new LiveGenerationConfig.Builder()
.setResponseModalities(ResponseModality.AUDIO)
.setSpeechConfig(new SpeechConfig(Voices.FENRIR))
.build()
);
// ...
Web
Live API henüz web uygulamaları için desteklenmemektedir. Lütfen daha sonra tekrar kontrol edin.
Dart
// ...
final model = FirebaseVertexAI.instance.liveModel(
model: 'gemini-2.0-flash-live-preview-04-09',
// Configure the model to use a specific voice for its audio response
config: LiveGenerationConfig(
responseModality: ResponseModality.audio,
speechConfig: SpeechConfig(voice: Voice.fenrir),
),
);
// ...
Unity
Snippets coming soon!
Modelden İngilizce dışında bir dilde yanıt vermesini istediğinizde en iyi sonuçları elde etmek için sistem talimatlarınıza aşağıdakileri ekleyin:
RESPOND IN LANGUAGE. YOU MUST RESPOND UNMISTAKABLY IN LANGUAGE.
Oturumlar ve istekler arasında bağlamı koruma
Oturumlar ve istekler arasında bağlamı korumak için sohbet yapısı kullanabilirsiniz. Bunun yalnızca metin girişi ve metin çıkışı için çalıştığını unutmayın.
Bu yaklaşım, kısa bağlamlar için en iyisidir. Etkinliklerin tam sırasını temsil etmek için adım adım etkileşimler gönderebilirsiniz. Daha uzun bağlamlar için bağlam penceresini sonraki etkileşimler için boşaltmak amacıyla tek bir mesaj özeti sağlamanızı öneririz.
Kesintileri ele alma
Firebase AI Logic henüz kesintilerin ele alınmasını desteklemez. Bir süre sonra tekrar kontrol edin.
İşlev çağrısını kullanma (araçlar)
Standart içerik oluşturma yöntemlerinde olduğu gibi, Live API ile kullanılacak araçları (ör. mevcut işlevler) tanımlayabilirsiniz. Bu bölümde, Live API'nin işlev çağrımıyla birlikte kullanılmasıyla ilgili bazı ayrıntılar açıklanmaktadır. İşlev çağırmayla ilgili tam açıklama ve örnekler için işlev çağırma kılavuzuna bakın.
Model, tek bir istemden birden fazla işlev çağrısı ve çıktılarını zincirlemek için gereken kodu oluşturabilir. Bu kod, korumalı bir ortamda yürütülerek sonraki BidiGenerateContentToolCall
mesajlarını oluşturur. Yürütme, her işlev çağrısının sonuçları hazır olana kadar duraklatılır. Bu, sıralı işleme sağlar.
Ayrıca, Live API'yi işlev çağrısıyla kullanmak özellikle güçlüdür çünkü model kullanıcıdan takip veya açıklayıcı bilgi isteyebilir. Örneğin, model, çağırmak istediği bir işleve parametre değeri sağlamak için yeterli bilgiye sahip değilse kullanıcıdan daha fazla veya açıklayıcı bilgi vermesini isteyebilir.
Müşteri BidiGenerateContentToolResponse
ile yanıt vermelidir.
Sınırlamalar ve koşullar
Live API ile ilgili aşağıdaki sınırlamaları ve koşulları göz önünde bulundurun.
Çeviri yazı
Firebase AI Logic henüz transkriptleri desteklemiyor. Bir süre sonra tekrar kontrol edin.
Diller
- Giriş dilleri: Gemini modelleri için desteklenen giriş dillerinin tam listesini inceleyin.
- Çıkış dilleri: Chirp 3: HD sesler'de kullanılabilen çıkış dillerinin tam listesini inceleyin.
Ses biçimleri
Live API aşağıdaki ses biçimlerini destekler:
- Giriş ses biçimi: 16 kHz little-endian'da ham 16 bit PCM ses
- Çıkış ses biçimi: 24 kHz little-endian'da ham 16 bit PCM ses
Hız sınırları
Aşağıdaki hız sınırları geçerlidir:
- Firebase projesi başına 10 eşzamanlı oturum
- Dakikada 4 milyon jeton
Oturum süresi
Oturumların varsayılan süresi 30 dakikadır. Oturum süresi sınırı aşıldığında bağlantı sonlandırılır.
Model, bağlam boyutuyla da sınırlıdır. Büyük giriş parçaları göndermek, oturumun daha erken sonlandırılmasına neden olabilir.
Konuşma etkinliği algılama (VAD)
Model, sürekli bir ses girişi akışında otomatik olarak ses etkinliği algılama (VAD) işlemi gerçekleştirir. VAD varsayılan olarak etkindir.
Jeton sayımı
CountTokens
API'yi Live API ile kullanamazsınız.
Firebase AI Logic ile ilgili deneyiminiz hakkında geri bildirim verme