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 را اضافه کنید، سرویس Backend را برای Vertex AI Gemini API راهاندازی کنید و یک نمونه LiveModel
ایجاد کنید.
مدل هایی که از این قابلیت پشتیبانی می کنند
Live API فقط توسط gemini-2.0-flash-live-preview-04-09
(نه gemini-2.0-flash
) پشتیبانی می شود.
از ویژگی های استاندارد Live API استفاده کنید
این بخش نحوه استفاده از ویژگیهای استاندارد Live API را توضیح میدهد، بهویژه برای پخش جریانی انواع ورودیها و خروجیها:
متن پخش شده را از ورودی متن پخش شده تولید کنید
قبل از امتحان این نمونه، بخش قبل از شروع این راهنما را تکمیل کنید تا پروژه و برنامه خود را راه اندازی کنید. در آن بخش، همچنین روی دکمه ای برای ارائه دهنده API Gemini انتخابی خود کلیک می کنید تا محتوای خاص ارائه دهنده را در این صفحه ببینید . |
می توانید ورودی متن پخش شده را ارسال کنید و خروجی متن پخش شده را دریافت کنید. مطمئن شوید که یک نمونه liveModel
ایجاد کرده اید و حالت پاسخ را روی Text
تنظیم کنید.
سویفت
Live API هنوز برای برنامه های پلتفرم اپل پشتیبانی نمی شود، اما به زودی دوباره بررسی کنید!
Kotlin
// Initialize the Vertex AI Gemini API backend service
// Create a `LiveModel` instance with the model that supports the Live API
val model = Firebase.ai(backend = GenerativeBackend.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 هنوز برای برنامه های وب پشتیبانی نمی شود، اما به زودی دوباره بررسی کنید!
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
}
وحدت
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);
}
}
}
بیاموزید که چگونه یک مدل مناسب برای مورد استفاده و برنامه خود انتخاب کنید.
صدای پخش شده را از ورودی صوتی پخش شده تولید کنید
قبل از امتحان این نمونه، بخش قبل از شروع این راهنما را تکمیل کنید تا پروژه و برنامه خود را راه اندازی کنید. در آن بخش، همچنین روی دکمه ای برای ارائه دهنده API Gemini انتخابی خود کلیک می کنید تا محتوای خاص ارائه دهنده را در این صفحه ببینید . |
می توانید ورودی صوتی پخش شده را ارسال کنید و خروجی صدای پخش شده را دریافت کنید. مطمئن شوید که یک نمونه LiveModel
ایجاد کرده اید و حالت پاسخ را روی Audio
تنظیم کنید.
با نحوه پیکربندی و سفارشی کردن صدای پاسخ آشنا شوید (در ادامه این صفحه).
سویفت
Live API هنوز برای برنامه های پلتفرم اپل پشتیبانی نمی شود، اما به زودی دوباره بررسی کنید!
Kotlin
// Initialize the Vertex AI Gemini API backend service
// Create a `LiveModel` instance with the model that supports the Live API
val model = Firebase.ai(backend = GenerativeBackend.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 هنوز برای برنامه های وب پشتیبانی نمی شود، اما به زودی دوباره بررسی کنید!
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
}
وحدت
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++;
}
}
بیاموزید که چگونه یک مدل مناسب برای مورد استفاده و برنامه خود انتخاب کنید.
قبل از امتحان این نمونه، بخش قبل از شروع این راهنما را تکمیل کنید تا پروژه و برنامه خود را راه اندازی کنید. در آن بخش، همچنین روی دکمه ای برای ارائه دهنده API Gemini انتخابی خود کلیک می کنید تا محتوای خاص ارائه دهنده را در این صفحه ببینید . |
می توانید ورودی صوتی پخش شده را ارسال کنید و خروجی متن پخش شده را دریافت کنید. مطمئن شوید که یک نمونه LiveModel
ایجاد کرده اید و حالت پاسخ را روی Text
تنظیم کنید.
سویفت
Live API هنوز برای برنامه های پلتفرم اپل پشتیبانی نمی شود، اما به زودی دوباره بررسی کنید!
Kotlin
// Initialize the Vertex AI Gemini API backend service
// Create a `LiveModel` instance with the model that supports the Live API
val model = Firebase.ai(backend = GenerativeBackend.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 audioContent = content("user") { audioData }
session.send(audioContent)
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);
// Send Audio data
session.send(new Content.Builder().addInlineData(audioData, "audio/pcm").build());
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';
import 'package:your_audio_recorder_package/your_audio_recorder_package.dart';
import 'dart:async';
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 text
config: LiveGenerationConfig(responseModality: ResponseModality.text),
);
_session = await model.connect();
final audioRecordStream = _audioRecorder.startRecordingStream();
final mediaChunkStream = audioRecordStream.map((data) {
return InlineDataPart('audio/pcm', data);
});
await _session.startMediaStream(mediaChunkStream);
final responseStream = _session.receive();
return responseStream.asyncMap((response) async {
if (response.parts.isNotEmpty && response.parts.first.text != null) {
return response.parts.first.text!;
} else {
throw Exception('Text response not found.');
}
});
Future main() async {
try {
final textStream = await audioToText();
await for (final text in textStream) {
print('Received text: $text');
// Handle the text response
}
} catch (e) {
print('Error: $e');
}
}
وحدت
using Firebase;
using Firebase.AI;
async Task SendAudioReceiveText() {
// 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();
// Start a coroutine to send audio from the Microphone
var recordingCoroutine = StartCoroutine(SendAudio(session));
// 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);
}
}
StopCoroutine(recordingCoroutine);
}
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);
}
}
بیاموزید که چگونه یک مدل مناسب برای مورد استفاده و برنامه خود انتخاب کنید.
قبل از امتحان این نمونه، بخش قبل از شروع این راهنما را تکمیل کنید تا پروژه و برنامه خود را راه اندازی کنید. در آن بخش، همچنین روی دکمه ای برای ارائه دهنده API Gemini انتخابی خود کلیک می کنید تا محتوای خاص ارائه دهنده را در این صفحه ببینید . |
می توانید ورودی متن پخش شده را ارسال کنید و خروجی صوتی پخش شده را دریافت کنید. مطمئن شوید که یک نمونه LiveModel
ایجاد کرده اید و حالت پاسخ را روی Audio
تنظیم کنید.
با نحوه پیکربندی و سفارشی کردن صدای پاسخ آشنا شوید (در ادامه این صفحه).
سویفت
Live API هنوز برای برنامه های پلتفرم اپل پشتیبانی نمی شود، اما به زودی دوباره بررسی کنید!
Kotlin
// Initialize the Vertex AI Gemini API backend service
// Create a `LiveModel` instance with the model that supports the Live API
val model = Firebase.ai(backend = GenerativeBackend.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()
// Provide a text prompt
val text = "tell a short story"
session.send(text)
session.receive().collect {
if(it.status == Status.TURN_COMPLETE) {
// Optional: if you don't require to send more requests.
session.stopReceiving();
}
// Handle 16bit pcm audio data at 24khz
playAudio(it.data)
}
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.AUDIO)
.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 16bit pcm audio data at 24khz
liveContentResponse.getData();
}
@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';
import 'dart:async';
import 'dart:typed_data';
late LiveModelSession _session;
Future<Stream<Uint8List>> textToAudio(String textPrompt) async {
WidgetsFlutterBinding.ensureInitialized();
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(responseModality: ResponseModality.audio),
);
_session = await model.connect();
final prompt = Content.text(textPrompt);
await _session.send(input: prompt);
return _session.receive().asyncMap((response) async {
if (response is LiveServerContent && response.modelTurn?.parts != null) {
for (final part in response.modelTurn!.parts) {
if (part is InlineDataPart) {
return part.bytes;
}
}
}
throw Exception('Audio data not found');
});
}
Future<void> main() async {
try {
final audioStream = await textToAudio('Convert this text to audio.');
await for (final audioData in audioStream) {
// Process the audio data (e.g., play it using an audio player package)
print('Received audio data: ${audioData.length} bytes');
// Example using flutter_sound (replace with your chosen package):
// await _flutterSoundPlayer.startPlayer(fromDataBuffer: audioData);
}
} catch (e) {
print('Error: $e');
}
}
وحدت
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();
// Provide a text prompt
var prompt = ModelContent.Text("Convert this text to audio.");
await session.SendAsync(content: prompt, turnComplete: true);
// Start receiving the response
await ReceiveAudio(session);
}
Queue<float> audioBuffer = new();
async Task ReceiveAudio(LiveSession session) {
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>();
audioSource.clip = clip;
audioSource.loop = true;
audioSource.Play();
// Start receiving the response
await foreach (var message in session.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 و ۳۱ زبان ارسال کنید.
اگر صدایی را مشخص نکنید، پیشفرض Puck
است. همچنین، میتوانید مدل را طوری پیکربندی کنید که به یکی از صداهای زیر پاسخ دهد:
Aoede (مونث)Charon (مرد) | Fenrir (مرد)Kore (مونث) | Puck (مرد) |
برای اطلاع از نحوه صدای این صداها و فهرست کامل زبانهای موجود، به Chirp 3: صداهای HD مراجعه کنید.
برای تعیین یک صدا، نام صدا را در شی speechConfig
به عنوان بخشی از پیکربندی مدل تنظیم کنید:
سویفت
Live API هنوز برای برنامه های پلتفرم اپل پشتیبانی نمی شود، اما به زودی دوباره بررسی کنید!
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 = 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),
),
);
// ...
وحدت
Snippets coming soon!
برای بهترین نتایج در هنگام درخواست و الزام مدل به پاسخگویی به زبان غیر انگلیسی، موارد زیر را به عنوان بخشی از دستورالعملهای سیستم خود بگنجانید:
RESPOND IN LANGUAGE. YOU MUST RESPOND UNMISTAKABLY IN LANGUAGE.
زمینه را در طول جلسات و درخواست ها حفظ کنید
میتوانید از ساختار چت برای حفظ زمینه در جلسات و درخواستها استفاده کنید. توجه داشته باشید که این فقط برای ورودی متن و خروجی متن کار می کند.
این رویکرد برای زمینه های کوتاه بهترین است. می توانید تعاملات نوبت به نوبه خود را برای نشان دادن توالی دقیق رویدادها ارسال کنید. برای زمینههای طولانیتر، توصیه میکنیم یک خلاصه پیام واحد ارائه کنید تا پنجره زمینه برای تعاملات بعدی آزاد شود.
وقفه ها را مدیریت کنید
Firebase AI Logic هنوز از مدیریت وقفه ها پشتیبانی نمی کند. به زودی دوباره بررسی کنید!
استفاده از فراخوانی تابع (ابزار)
میتوانید ابزارهایی مانند توابع موجود را برای استفاده با Live API درست مانند روشهای تولید محتوای استاندارد تعریف کنید. این بخش برخی تفاوت های ظریف را در هنگام استفاده از Live API با فراخوانی تابع توضیح می دهد. برای توضیحات کامل و مثال هایی برای فراخوانی تابع، راهنمای فراخوانی تابع را ببینید.
از یک اعلان واحد، مدل می تواند چندین فراخوانی تابع و کدهای لازم برای زنجیره خروجی های آنها را ایجاد کند. این کد در محیط sandbox اجرا می شود و پیام های BidiGenerateContentToolCall
بعدی را ایجاد می کند. اجرا متوقف می شود تا زمانی که نتایج هر فراخوانی در دسترس باشد، که پردازش متوالی را تضمین می کند.
علاوه بر این، استفاده از Live API با فراخوانی تابع بسیار قدرتمند است زیرا مدل میتواند اطلاعات پیگیری یا شفافسازی را از کاربر درخواست کند. برای مثال، اگر مدل اطلاعات کافی برای ارائه مقدار پارامتر به تابعی که میخواهد فراخوانی کند، نداشته باشد، آنگاه مدل میتواند از کاربر بخواهد اطلاعات بیشتری یا شفافسازی را ارائه دهد.
مشتری باید با BidiGenerateContentToolResponse
پاسخ دهد.
محدودیت ها و الزامات
محدودیت ها و الزامات زیر را در Live API به خاطر داشته باشید.
رونویسی
Firebase AI Logic هنوز از رونویسی پشتیبانی نمی کند. به زودی دوباره بررسی کنید!
زبان ها
- زبانهای ورودی: فهرست کامل زبانهای ورودی پشتیبانیشده برای مدلهای Gemini را ببینید
- زبانهای خروجی: فهرست کامل زبانهای خروجی موجود را در صدای Chirp 3: HD ببینید
فرمت های صوتی
Live API از فرمت های صوتی زیر پشتیبانی می کند:
- فرمت صوتی ورودی: صدای خام 16 بیتی PCM با فرکانس 16 کیلوهرتز کمی اندین
- فرمت صدای خروجی: صدای خام 16 بیتی PCM با فرکانس 24 کیلوهرتز کمی endian
محدودیت های نرخ
محدودیت های نرخ زیر اعمال می شود:
- 10 جلسه همزمان در هر پروژه Firebase
- 4 میلیون توکن در دقیقه
طول جلسه
مدت زمان پیش فرض برای یک جلسه 30 دقیقه است. هنگامی که مدت زمان جلسه از حد مجاز بیشتر شود، اتصال قطع می شود.
مدل نیز با اندازه زمینه محدود شده است. ارسال قطعات بزرگ ورودی ممکن است منجر به خاتمه زودتر جلسه شود.
تشخیص فعالیت صوتی (VAD)
این مدل به طور خودکار تشخیص فعالیت صوتی (VAD) را در جریان ورودی صوتی پیوسته انجام می دهد. VAD به طور پیش فرض فعال است.
توکن شمارش
نمیتوانید از CountTokens
API با Live API استفاده کنید.
درباره تجربه خود با Firebase AI Logic بازخورد بدهید