Gemini Live API ช่วยให้มีการโต้ตอบด้วยข้อความและเสียงแบบสองทางที่มีเวลาในการตอบสนองต่ำกับ Gemini การใช้ Live API ช่วยให้คุณมอบประสบการณ์การสนทนาด้วยเสียงที่เป็นธรรมชาติและเหมือนมนุษย์แก่ผู้ใช้ปลายทาง พร้อมความสามารถในการขัดจังหวะคำตอบของโมเดลโดยใช้ข้อความหรือคำสั่งเสียง โมเดลนี้ประมวลผลอินพุตข้อความและเสียงได้ (วิดีโอจะพร้อมใช้งานเร็วๆ นี้) และสามารถ แสดงเอาต์พุตข้อความและเสียงได้
คุณสร้างต้นแบบด้วยพรอมต์และ Live API ใน Vertex AI Studio ได้
Live API เป็น API แบบมีสถานะที่สร้างการเชื่อมต่อ WebSocket เพื่อ สร้างเซสชันระหว่างไคลเอ็นต์กับเซิร์ฟเวอร์ Gemini ดูรายละเอียดได้ที่Live APIเอกสารอ้างอิง
ก่อนเริ่มต้น
ใช้ได้เมื่อใช้ Vertex AI Gemini API เป็นผู้ให้บริการ API เท่านั้น |
หากยังไม่ได้ดำเนินการ ให้ทำตามคู่มือเริ่มต้นใช้งาน
ซึ่งอธิบายวิธีตั้งค่าโปรเจ็กต์ Firebase
เชื่อมต่อแอปกับ Firebase เพิ่ม SDK เริ่มต้นบริการแบ็กเอนด์สำหรับ
Vertex AI Gemini API และ
สร้างอินสแตนซ์ LiveModel
รุ่นที่รองรับความสามารถนี้
Live API รองรับเฉพาะ gemini-2.0-flash-live-preview-04-09
เท่านั้น (ไม่ใช่ gemini-2.0-flash
)
นอกจากนี้ โปรดทราบว่า gemini-2.0-flash-live-preview-04-09
รองรับเฉพาะใน
us-central1
เท่านั้น
ใช้ฟีเจอร์มาตรฐานของ Live API
ส่วนนี้จะอธิบายวิธีใช้ฟีเจอร์มาตรฐานของ Live API โดยเฉพาะอย่างยิ่งในการสตรีมอินพุตและเอาต์พุตประเภทต่างๆ
สร้างข้อความที่สตรีมจากอินพุตข้อความที่สตรีม
ก่อนที่จะลองใช้ตัวอย่างนี้ ให้ทำตามส่วน
ก่อนที่จะเริ่มของคู่มือนี้
เพื่อตั้งค่าโปรเจ็กต์และแอป ในส่วนนั้น คุณจะคลิกปุ่มสำหรับ ผู้ให้บริการ Gemini API ที่เลือกเพื่อให้เห็นเนื้อหาเฉพาะของผู้ให้บริการ ในหน้านี้ด้วย |
คุณส่งอินพุตข้อความแบบสตรีมและรับเอาต์พุตข้อความแบบสตรีมได้ อย่าลืมสร้างอินสแตนซ์ liveModel
และตั้งค่ารูปแบบการตอบกลับเป็น Text
Swift
ระบบยังไม่รองรับ Live API สำหรับแอปแพลตฟอร์ม Apple แต่โปรดกลับมาตรวจสอบอีกครั้งในเร็วๆ นี้
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 สำหรับเว็บแอป แต่จะรองรับเร็วๆ นี้
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);
}
}
}
สร้างเสียงที่สตรีมจากอินพุตเสียงที่สตรีม
ก่อนที่จะลองใช้ตัวอย่างนี้ ให้ทำตามส่วน
ก่อนที่จะเริ่มของคู่มือนี้
เพื่อตั้งค่าโปรเจ็กต์และแอป ในส่วนนั้น คุณจะคลิกปุ่มสำหรับ ผู้ให้บริการ Gemini API ที่เลือกเพื่อให้เห็นเนื้อหาเฉพาะของผู้ให้บริการ ในหน้านี้ด้วย |
คุณสามารถส่งอินพุตเสียงที่สตรีมและรับเอาต์พุตเสียงที่สตรีมได้ โปรดสร้างอินสแตนซ์ LiveModel
และตั้งค่ารูปแบบการตอบกลับเป็น Audio
ดูวิธีกำหนดค่าและปรับแต่งเสียงตอบ (อ่านต่อในหน้านี้)
Swift
ระบบยังไม่รองรับ Live API สำหรับแอปแพลตฟอร์ม Apple แต่โปรดกลับมาตรวจสอบอีกครั้งในเร็วๆ นี้
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 สำหรับเว็บแอป แต่จะรองรับเร็วๆ นี้
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++;
}
}
สร้างประสบการณ์ที่น่าสนใจและมีการโต้ตอบมากขึ้น
ส่วนนี้จะอธิบายวิธีสร้างและจัดการฟีเจอร์ที่น่าสนใจหรือมีการโต้ตอบมากขึ้นของ Live API
เปลี่ยนเสียงตอบกลับ
Live API ใช้ Chirp 3 เพื่อรองรับการตอบกลับด้วยเสียงสังเคราะห์ เมื่อใช้ Firebase AI Logic คุณจะส่งเสียงในภาษาต่างๆ ด้วยเสียง HD ได้ ดูรายการทั้งหมดและตัวอย่างเสียงแต่ละเสียงได้ที่ Chirp 3: เสียง HD
หากต้องการระบุเสียง ให้ตั้งค่าชื่อเสียงภายในออบเจ็กต์ speechConfig
เป็นส่วนหนึ่งของการกำหนดค่าโมเดล
หากไม่ได้ระบุเสียง ระบบจะใช้เสียง Puck
เป็นค่าเริ่มต้น
Swift
ระบบยังไม่รองรับ Live API สำหรับแอปแพลตฟอร์ม Apple แต่โปรดกลับมาตรวจสอบอีกครั้งในเร็วๆ นี้
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 สำหรับเว็บแอป แต่จะรองรับเร็วๆ นี้
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"),
);
เพื่อให้ได้ผลลัพธ์ที่ดีที่สุดเมื่อป้อนพรอมต์และกำหนดให้โมเดลตอบกลับเป็นภาษาอื่นที่ไม่ใช่ภาษาอังกฤษ ให้ระบุข้อมูลต่อไปนี้เป็นส่วนหนึ่งของคำสั่งของระบบ
RESPOND IN LANGUAGE. YOU MUST RESPOND UNMISTAKABLY IN LANGUAGE.
คงบริบทในเซสชันและคำขอต่างๆ
คุณสามารถใช้โครงสร้างแชทเพื่อรักษาบริบทในเซสชันและคำขอต่างๆ โปรดทราบว่าวิธีนี้ใช้ได้กับอินพุตและเอาต์พุตที่เป็นข้อความเท่านั้น
แนวทางนี้เหมาะที่สุดสำหรับบริบทสั้นๆ คุณสามารถส่งการโต้ตอบแบบเลี้ยวต่อเลี้ยว เพื่อแสดงลำดับเหตุการณ์ที่แน่นอนได้ สำหรับบริบทที่ยาวขึ้น เราขอแนะนำให้สรุปข้อความเดียวเพื่อเพิ่ม หน้าต่างบริบทสำหรับการโต้ตอบในภายหลัง
จัดการการหยุดชะงัก
Firebase AI Logic ยังไม่รองรับการจัดการการหยุดชะงัก โปรดกลับมาใหม่หลังจากนี้
ใช้การเรียกฟังก์ชัน (เครื่องมือ)
คุณกำหนดเครื่องมือ เช่น ฟังก์ชันที่พร้อมใช้งาน เพื่อใช้กับ Live API ได้เช่นเดียวกับที่ทำได้ด้วยวิธีการสร้างเนื้อหามาตรฐาน ส่วนนี้ อธิบายรายละเอียดบางอย่างเมื่อใช้ Live API กับการเรียกใช้ฟังก์ชัน ดูคำอธิบายและตัวอย่างที่สมบูรณ์สำหรับการเรียกใช้ฟังก์ชันได้ที่คู่มือการเรียกใช้ฟังก์ชัน
โมเดลสามารถสร้างการเรียกใช้ฟังก์ชันหลายรายการและโค้ดที่จำเป็นต่อการเชื่อมโยงเอาต์พุตจากพรอมต์เดียว โค้ดนี้จะทำงานในสภาพแวดล้อมแซนด์บ็อกซ์
เพื่อสร้างข้อความBidiGenerateContentToolCall
ที่ตามมา การดำเนินการจะหยุดชั่วคราวจนกว่าผลลัพธ์ของการเรียกใช้ฟังก์ชันแต่ละรายการจะพร้อมใช้งาน ซึ่งจะช่วยให้มั่นใจได้ว่าการประมวลผลจะเป็นไปตามลำดับ
นอกจากนี้ การใช้ Live API กับการเรียกใช้ฟังก์ชันยังทรงพลังเป็นพิเศษ เนื่องจากโมเดลสามารถขอข้อมูลติดตามผลหรือข้อมูลที่ชัดเจนจากผู้ใช้ได้ ตัวอย่างเช่น หากโมเดลมีข้อมูลไม่เพียงพอที่จะระบุค่าพารามิเตอร์ ให้กับฟังก์ชันที่ต้องการเรียกใช้ โมเดลจะขอให้ผู้ใช้ระบุข้อมูลเพิ่มเติมหรือข้อมูลที่ชัดเจนยิ่งขึ้นได้
ไคลเอ็นต์ควรตอบกลับด้วย
BidiGenerateContentToolResponse
ข้อจำกัดและข้อกำหนด
โปรดทราบข้อจำกัดและข้อกำหนดต่อไปนี้ของ Live API
การถอดเสียงเป็นคำ
Firebase AI Logic ยังไม่รองรับการถอดเสียงเป็นคำ โปรดกลับมาใหม่หลังจากนี้
ภาษา
- ภาษาที่ป้อน: ดูรายการทั้งหมดของ ภาษาที่ป้อนที่รองรับสำหรับโมเดล Gemini
- ภาษาเอาต์พุต: ดูรายการภาษาเอาต์พุตทั้งหมดที่พร้อมใช้งานได้ใน Chirp 3: เสียง HD
รูปแบบเสียง
Live API รองรับรูปแบบเสียงต่อไปนี้
- รูปแบบเสียงอินพุต: เสียง PCM แบบ 16 บิตดิบที่ 16 kHz แบบ Little-Endian
- รูปแบบเสียงเอาต์พุต: เสียง PCM แบบ 16 บิตดิบที่ 24 kHz แบบ Little-Endian
ขีดจำกัดอัตรา
โดยมีการจำกัดจำนวนพรอมต์ดังนี้
- เซสชันพร้อมกัน 10 เซสชันต่อโปรเจ็กต์ Firebase
- โทเค็น 4 ล้านรายการต่อนาที
ระยะเวลาของเซสชัน
ระยะเวลาเริ่มต้นของเซสชันคือ 30 นาที เมื่อระยะเวลาเซสชัน เกินขีดจำกัด ระบบจะสิ้นสุดการเชื่อมต่อ
นอกจากนี้ โมเดลยังมีข้อจำกัดด้านขนาดบริบทด้วย การส่งอินพุตเป็นก้อนขนาดใหญ่อาจ ส่งผลให้เซสชันสิ้นสุดเร็วขึ้น
การตรวจจับกิจกรรมเสียงพูด (VAD)
โมเดลจะทำการตรวจหาการพูด (VAD) โดยอัตโนมัติในสตรีมอินพุตเสียงอย่างต่อเนื่อง VAD จะเปิดใช้โดยค่าเริ่มต้น
การนับโทเค็น
คุณไม่สามารถใช้ CountTokens
API กับ Live API ได้
แสดงความคิดเห็น เกี่ยวกับประสบการณ์การใช้งาน Firebase AI Logic