Gemini Live API memungkinkan interaksi teks dan suara dua arah latensi rendah dengan Gemini. Dengan Live API, Anda dapat memberikan pengalaman percakapan suara yang alami dan mirip manusia kepada pengguna akhir, dengan kemampuan untuk menginterupsi respons model menggunakan perintah teks atau suara. Model ini dapat memproses input teks dan audio (video akan segera hadir!), dan dapat memberikan output teks dan audio.
Anda dapat membuat prototipe dengan perintah dan Live API di Vertex AI Studio.
Live API adalah API stateful yang membuat koneksi WebSocket untuk membuat sesi antara klien dan server Gemini. Untuk mengetahui detailnya, lihat dokumentasi referensi Live API.
Sebelum memulai
Hanya tersedia saat menggunakan Vertex AI Gemini API sebagai penyedia API Anda. |
Jika belum melakukannya, selesaikan
panduan memulai,
yang menjelaskan cara menyiapkan project Firebase,
menghubungkan aplikasi ke Firebase, menambahkan SDK, menginisialisasi layanan backend untuk
Vertex AI Gemini API, dan
membuat instance LiveModel
.
Model yang mendukung kemampuan ini
Live API hanya didukung oleh gemini-2.0-flash-live-preview-04-09
(bukan gemini-2.0-flash
).
Perhatikan juga bahwa gemini-2.0-flash-live-preview-04-09
hanya didukung di lokasi
us-central1
.
Menggunakan fitur standar Live API
Bagian ini menjelaskan cara menggunakan fitur standar Live API, khususnya untuk melakukan streaming berbagai jenis input dan output:
- Mengirim dan menerima teks
- Mengirim audio dan menerima audio
- Mengirim audio dan menerima teks
- Mengirim teks dan menerima audio
Membuat teks yang di-streaming dari input teks yang di-streaming
Sebelum mencoba sampel ini, selesaikan bagian
Sebelum memulai dalam panduan ini
untuk menyiapkan project dan aplikasi Anda. Di bagian tersebut, Anda juga akan mengklik tombol untuk penyedia Gemini API yang Anda pilih agar Anda dapat melihat konten khusus penyedia di halaman ini. |
Anda dapat mengirim input teks yang di-streaming dan menerima output teks yang di-streaming. Pastikan untuk
membuat instance liveModel
dan menetapkan
modalitas respons
ke Text
.
Swift
Live API belum didukung untuk aplikasi platform Apple, tetapi periksa kembali nanti.
Kotlin
// Initialize the Vertex AI Gemini API backend service
// Set the location to `us-central1` (the flash-live model is only supported in that location)
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
val model = Firebase.ai(backend = GenerativeBackend.vertexAI(location = "us-central1")).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
// Set the location to `us-central1` (the flash-live model is only supported in that location)
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
LiveGenerativeModel lm = FirebaseAI.getInstance(GenerativeBackend.vertexAI("us-central1")).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 belum didukung untuk aplikasi Web, tetapi periksa kembali nanti.
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
// Set the location to `us-central1` (the flash-live model is only supported in that location)
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
final model = FirebaseAI.vertexAI(location: 'us-central1').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
// Set the location to `us-central1` (the flash-live model is only supported in that location)
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
var model = FirebaseAI.GetInstance(FirebaseAI.Backend.VertexAI(location: "us-central1")).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);
}
}
}
Membuat audio yang di-streaming dari input audio yang di-streaming
Sebelum mencoba sampel ini, selesaikan bagian
Sebelum memulai dalam panduan ini
untuk menyiapkan project dan aplikasi Anda. Di bagian tersebut, Anda juga akan mengklik tombol untuk penyedia Gemini API yang Anda pilih agar Anda dapat melihat konten khusus penyedia di halaman ini. |
Anda dapat mengirim input audio yang di-streaming dan menerima output audio yang di-streaming. Pastikan
untuk membuat instance LiveModel
dan menyetel
modalitas respons
ke Audio
.
Pelajari cara mengonfigurasi dan menyesuaikan suara respons (nanti di halaman ini).
Swift
Live API belum didukung untuk aplikasi platform Apple, tetapi periksa kembali nanti.
Kotlin
// Initialize the Vertex AI Gemini API backend service
// Set the location to `us-central1` (the flash-live model is only supported in that location)
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
val model = Firebase.ai(backend = GenerativeBackend.vertexAI(location = "us-central1")).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
// Set the location to `us-central1` (the flash-live model is only supported in that location)
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
LiveGenerativeModel lm = FirebaseAI.getInstance(GenerativeBackend.vertexAI("us-central1")).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 belum didukung untuk aplikasi Web, tetapi periksa kembali nanti.
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
// Set the location to `us-central1` (the flash-live model is only supported in that location)
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
final model = FirebaseAI.vertexAI(location: 'us-central1').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
// Set the location to `us-central1` (the flash-live model is only supported in that location)
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
var model = FirebaseAI.GetInstance(FirebaseAI.Backend.VertexAI(location: "us-central1")).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++;
}
}
Menciptakan pengalaman yang lebih menarik dan interaktif
Bagian ini menjelaskan cara membuat dan mengelola fitur Live API yang lebih menarik atau interaktif.
Mengubah suara respons
Live API menggunakan Chirp 3 untuk mendukung respons ucapan yang disintesis. Saat menggunakan Firebase AI Logic, Anda dapat mengirim audio dalam berbagai bahasa dan suara HD. Untuk mengetahui daftar lengkap dan demo suara yang dihasilkan oleh setiap suara, lihat Chirp 3: Suara HD.
Untuk menentukan suara, tetapkan nama suara dalam objek speechConfig
sebagai bagian
dari
konfigurasi model.
Jika Anda tidak menentukan suara, defaultnya adalah Puck
.
Swift
Live API belum didukung untuk aplikasi platform Apple, tetapi periksa kembali nanti.
Kotlin
// ...
val model = Firebase.ai(backend = GenerativeBackend.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 = FirebaseAI.getInstance(GenerativeBackend.vertexAI()).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 belum didukung untuk aplikasi Web, tetapi periksa kembali nanti.
Dart
// ...
final model = FirebaseAI.vertexAI().liveGenerativeModel(
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(voiceName: 'Fenrir'),
),
);
// ...
Unity
var model = FirebaseAI.GetInstance(FirebaseAI.Backend.VertexAI()).GetLiveModel(
modelName: "gemini-2.0-flash-live-preview-04-09",
liveGenerationConfig: new LiveGenerationConfig(
responseModalities: new[] { ResponseModality.Audio },
speechConfig: SpeechConfig.UsePrebuiltVoice("Fenrir"),
);
Untuk mendapatkan hasil terbaik saat memberikan perintah dan meminta model merespons dalam bahasa non-Inggris, sertakan hal berikut sebagai bagian dari petunjuk sistem Anda:
RESPOND IN LANGUAGE. YOU MUST RESPOND UNMISTAKABLY IN LANGUAGE.
Mempertahankan konteks di seluruh sesi dan permintaan
Anda dapat menggunakan struktur chat untuk mempertahankan konteks di seluruh sesi dan permintaan. Perhatikan bahwa ini hanya berfungsi untuk input teks dan output teks.
Pendekatan ini paling cocok untuk konteks singkat; Anda dapat mengirim interaksi belokan demi belokan untuk merepresentasikan urutan peristiwa yang tepat . Untuk konteks yang lebih panjang, sebaiknya berikan ringkasan pesan tunggal untuk mengosongkan jendela konteks untuk interaksi berikutnya.
Menangani gangguan
Firebase AI Logic belum mendukung penanganan gangguan. Periksa kembali nanti!
Menggunakan panggilan fungsi (alat)
Anda dapat menentukan alat, seperti fungsi yang tersedia, untuk digunakan dengan Live API seperti yang dapat Anda lakukan dengan metode pembuatan konten standar. Bagian ini menjelaskan beberapa nuansa saat menggunakan Live API dengan panggilan fungsi. Untuk deskripsi lengkap dan contoh pemanggilan fungsi, lihat panduan pemanggilan fungsi.
Dari satu perintah, model dapat menghasilkan beberapa panggilan fungsi dan kode yang diperlukan untuk menggabungkan outputnya. Kode ini dieksekusi di lingkungan sandbox, yang menghasilkan pesan BidiGenerateContentToolCall
berikutnya. Eksekusi akan dijeda hingga hasil setiap panggilan fungsi tersedia, yang memastikan pemrosesan berurutan.
Selain itu, penggunaan Live API dengan panggilan fungsi sangat efektif karena model dapat meminta informasi lanjutan atau klarifikasi dari pengguna. Misalnya, jika model tidak memiliki cukup informasi untuk memberikan nilai parameter ke fungsi yang ingin dipanggil, model dapat meminta pengguna untuk memberikan informasi tambahan atau klarifikasi.
Klien harus merespons dengan
BidiGenerateContentToolResponse
.
Batasan dan persyaratan
Perhatikan batasan dan persyaratan berikut dari Live API.
Transkripsi
Firebase AI Logic belum mendukung transkripsi. Periksa kembali nanti!
Languages
- Bahasa input: Lihat daftar lengkap bahasa input yang didukung untuk model Gemini
- Bahasa output: Lihat daftar lengkap bahasa output yang tersedia di Chirp 3: Suara HD
Format audio
Live API mendukung format audio berikut:
- Format audio input: Audio PCM 16 bit mentah pada 16 kHz little-endian
- Format audio output: Audio PCM 16 bit mentah pada 24 kHz little-endian
Batas kapasitas
Batas frekuensi berikut berlaku:
- 10 sesi serentak per project Firebase
- 4 juta token per menit
Durasi sesi
Durasi default untuk sesi adalah 30 menit. Jika durasi sesi melebihi batas, koneksi akan dihentikan.
Model ini juga dibatasi oleh ukuran konteks. Mengirim input dalam jumlah besar dapat menyebabkan penghentian sesi lebih awal.
Deteksi aktivitas suara (VAD)
Model ini secara otomatis melakukan deteksi aktivitas suara (VAD) pada aliran input audio yang berkelanjutan. VAD diaktifkan secara default.
Penghitungan token
Anda tidak dapat menggunakan CountTokens
API dengan Live API.
Memberikan masukan tentang pengalaman Anda dengan Firebase AI Logic