Gemini Live API تعاملات متنی و صوتی دوسویه کم تأخیر را با Gemini فعال میکند. با استفاده از Live API ، میتوانید تجربه مکالمات صوتی طبیعی و انسانمانند را در اختیار کاربران نهایی قرار دهید و با استفاده از دستورات نوشتاری یا صوتی، پاسخهای مدل را قطع کنید. این مدل می تواند متن و ورودی صوتی را پردازش کند (ویدئو به زودی!)، و می تواند متن و خروجی صدا را ارائه دهد.
میتوانید با دستورات و Live API در Vertex AI Studio نمونهسازی اولیه کنید.
Live API یک API حالت دار است که یک اتصال WebSocket برای ایجاد یک جلسه بین مشتری و سرور Gemini ایجاد می کند. برای جزئیات، به مستندات مرجع Live API مراجعه کنید.
قبل از شروع
اگر قبلاً این کار را نکردهاید، راهنمای شروع را تکمیل کنید، که نحوه راهاندازی پروژه Firebase را توضیح میدهد، برنامه خود را به Firebase متصل کنید، SDK را اضافه کنید، سرویس Vertex AI را راهاندازی کنید، و یک نمونه LiveModel
ایجاد کنید.
مطمئن شوید که حداقل از این نسخه های کتابخانه Firebase استفاده می کنید:
iOS+ : هنوز پشتیبانی نمی شود | Android : v16.3.0+ ( BoM : v33.12.0+) | وب : هنوز پشتیبانی نمی شود | فلوتر : نسخه 1.5.0+ (BoM: نسخه 3.9.0+)
مدل هایی که از این قابلیت پشتیبانی می کنند
Live API فقط توسط gemini-2.0-flash-live-preview-04-09
(نه gemini-2.0-flash
) پشتیبانی می شود.
از ویژگی های استاندارد Live API استفاده کنید
این بخش نحوه استفاده از ویژگیهای استاندارد Live API را توضیح میدهد، بهویژه برای پخش جریانی انواع ورودیها و خروجیها:
ارسال متن و دریافت متن
می توانید ورودی متن پخش شده را ارسال کنید و خروجی متن پخش شده را دریافت کنید. مطمئن شوید که یک نمونه liveModel
ایجاد کرده اید و حالت پاسخ را روی Text
تنظیم کنید.
سویفت
Live API هنوز برای برنامه های پلتفرم اپل پشتیبانی نمی شود، اما به زودی دوباره بررسی کنید!
Kotlin
// Initialize the Vertex AI service and create a `LiveModel` instance
val model = Firebase.vertexAI.liveModel(
// The Live API requires this specific model.
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 service and create a `LiveModel` instance
LiveGenerativeModel lm = FirebaseVertexAI.getInstance().liveModel(
// The Live API requires this specific model.
"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_vertexai/firebase_vertexai.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 service and create a `LiveModel` instance
final model = FirebaseVertexAI.instance.liveModel(
// The Live API requires this specific model.
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
}
نحوه انتخاب یک مدل و به صورت اختیاری مکان مناسب برای مورد استفاده و برنامه خود را بیاموزید.
ارسال صوت و دریافت صدا
می توانید ورودی صوتی پخش شده را ارسال کنید و خروجی صدای پخش شده را دریافت کنید. مطمئن شوید که یک نمونه LiveModel
ایجاد کرده اید و حالت پاسخ را روی Audio
تنظیم کنید.
با نحوه پیکربندی و سفارشی کردن صدای پاسخ آشنا شوید (در ادامه این صفحه).
سویفت
Live API هنوز برای برنامه های پلتفرم اپل پشتیبانی نمی شود، اما به زودی دوباره بررسی کنید!
Kotlin
// Initialize the Vertex AI service and create a `LiveModel` instance
val model = Firebase.vertexAI.liveModel(
// The Live API requires this specific model.
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 service and create a `LiveModel` instance
LiveGenerativeModel lm = FirebaseVertexAI.getInstance().liveModel(
// The Live API requires this specific model.
"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);
وب
Live API هنوز برای برنامه های وب پشتیبانی نمی شود، اما به زودی دوباره بررسی کنید!
Dart
import 'package:firebase_vertexai/firebase_vertexai.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 service and create a `LiveModel` instance
final model = FirebaseVertexAI.instance.liveModel(
// The Live API requires this specific model.
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
}
نحوه انتخاب یک مدل و به صورت اختیاری مکان مناسب برای مورد استفاده و برنامه خود را بیاموزید.
می توانید ورودی صوتی پخش شده را ارسال کنید و خروجی متن پخش شده را دریافت کنید. مطمئن شوید که یک نمونه LiveModel
ایجاد کرده اید و حالت پاسخ را روی Text
تنظیم کنید.
سویفت
Live API هنوز برای برنامه های پلتفرم اپل پشتیبانی نمی شود، اما به زودی دوباره بررسی کنید!
Kotlin
// Initialize the Vertex AI service and create a `LiveModel` instance
val model = Firebase.vertexAI.liveModel(
// The Live API requires this specific model.
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
TODO - snippet ExecutorService executor = Executors.newFixedThreadPool(1);
// Initialize the Vertex AI service and create a `LiveModel` instance
LiveGenerativeModel lm = FirebaseVertexAI.getInstance().liveModel(
// The Live API requires this specific model.
"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_vertexai/firebase_vertexai.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,
);
final model = FirebaseVertexAI.instance.liveModel(
model: 'gemini-2.0-flash-live-preview-04-09',
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');
}
}
نحوه انتخاب یک مدل و به صورت اختیاری مکان مناسب برای مورد استفاده و برنامه خود را بیاموزید.
می توانید ورودی متن پخش شده را ارسال کنید و خروجی صوتی پخش شده را دریافت کنید. مطمئن شوید که یک نمونه LiveModel
ایجاد کرده اید و حالت پاسخ را روی Audio
تنظیم کنید.
با نحوه پیکربندی و سفارشی کردن صدای پاسخ آشنا شوید (در ادامه این صفحه).
سویفت
Live API هنوز برای برنامه های پلتفرم اپل پشتیبانی نمی شود، اما به زودی دوباره بررسی کنید!
Kotlin
// Initialize the Vertex AI service and create a `LiveModel` instance
val model = Firebase.vertexAI.liveModel(
// The Live API requires this specific model.
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 service and create a `LiveModel` instance
LiveGenerativeModel lm = FirebaseVertexAI.getInstance().liveModel(
// The Live API requires this specific model.
"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_vertexai/firebase_vertexai.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,
);
final model = FirebaseVertexAI.instance.liveModel(
model: 'gemini-2.0-flash-live-preview-04-09',
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');
}
}
نحوه انتخاب یک مدل و به صورت اختیاری مکان مناسب برای مورد استفاده و برنامه خود را بیاموزید.
تجربیات جذاب و تعاملی بیشتری ایجاد کنید
این بخش نحوه ایجاد و مدیریت ویژگیهای جذاب یا تعاملی Live API را شرح میدهد.
صدای پاسخ را تغییر دهید
Live API از Chirp 3 برای پشتیبانی از پاسخ های گفتاری ترکیبی استفاده می کند. هنگام استفاده از Vertex AI در Firebase ، میتوانید صدا را با ۵ صدای HD و ۳۱ زبان ارسال کنید.
اگر صدایی را مشخص نکنید، پیشفرض Puck
است. همچنین، میتوانید مدل را طوری پیکربندی کنید که به یکی از صداهای زیر پاسخ دهد:
Aoede (مونث)Charon (مرد) | Fenrir (مرد)Kore (مونث) | Puck (مرد) |
برای اطلاع از نحوه صدای این صداها و فهرست کامل زبانهای موجود، به Chirp 3: صداهای HD مراجعه کنید.
برای تعیین یک صدا، نام صدا را در شی speechConfig
به عنوان بخشی از پیکربندی مدل تنظیم کنید:
سویفت
Live API هنوز برای برنامه های پلتفرم اپل پشتیبانی نمی شود، اما به زودی دوباره بررسی کنید!
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 هنوز برای برنامه های وب پشتیبانی نمی شود، اما به زودی دوباره بررسی کنید!
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),
),
);
// ...
برای بهترین نتایج در هنگام درخواست و الزام مدل به پاسخگویی به زبان غیر انگلیسی، موارد زیر را به عنوان بخشی از دستورالعملهای سیستم خود بگنجانید:
RESPOND IN LANGUAGE. YOU MUST RESPOND UNMISTAKABLY IN LANGUAGE.
زمینه را در طول جلسات و درخواست ها حفظ کنید
میتوانید از ساختار چت برای حفظ زمینه در جلسات و درخواستها استفاده کنید. توجه داشته باشید که این فقط برای ورودی متن و خروجی متن کار می کند.
این رویکرد برای زمینه های کوتاه بهترین است. می توانید تعاملات نوبت به نوبه خود را برای نشان دادن توالی دقیق رویدادها ارسال کنید. برای زمینههای طولانیتر، توصیه میکنیم یک خلاصه پیام واحد ارائه کنید تا پنجره زمینه برای تعاملات بعدی آزاد شود.
وقفه ها را مدیریت کنید
Vertex AI در Firebase هنوز از مدیریت وقفه پشتیبانی نمی کند. به زودی دوباره بررسی کنید!
استفاده از فراخوانی تابع (ابزار)
میتوانید ابزارهایی مانند توابع موجود را برای استفاده با Live API درست مانند روشهای تولید محتوای استاندارد تعریف کنید. این بخش برخی تفاوت های ظریف را در هنگام استفاده از Live API با فراخوانی تابع توضیح می دهد. برای توضیحات کامل و مثال هایی برای فراخوانی تابع، راهنمای فراخوانی تابع را ببینید.
از یک اعلان واحد، مدل می تواند چندین فراخوانی تابع و کدهای لازم برای زنجیره خروجی های آنها را ایجاد کند. این کد در محیط sandbox اجرا می شود و پیام های BidiGenerateContentToolCall
بعدی را ایجاد می کند. اجرا متوقف می شود تا زمانی که نتایج هر فراخوانی در دسترس باشد، که پردازش متوالی را تضمین می کند.
علاوه بر این، استفاده از Live API با فراخوانی تابع بسیار قدرتمند است زیرا مدل میتواند اطلاعات پیگیری یا شفافسازی را از کاربر درخواست کند. برای مثال، اگر مدل اطلاعات کافی برای ارائه مقدار پارامتر به تابعی که میخواهد فراخوانی کند، نداشته باشد، آنگاه مدل میتواند از کاربر بخواهد اطلاعات بیشتری یا شفافسازی را ارائه دهد.
مشتری باید با BidiGenerateContentToolResponse
پاسخ دهد.
محدودیت ها و الزامات
محدودیت ها و الزامات زیر را در Live API به خاطر داشته باشید.
رونویسی
Vertex AI در Firebase هنوز از رونویسی پشتیبانی نمی کند. به زودی دوباره بررسی کنید!
زبان ها
- زبانهای ورودی: فهرست کامل زبانهای ورودی پشتیبانیشده برای مدلهای Gemini را ببینید
- زبانهای خروجی: فهرست کامل زبانهای خروجی موجود را در صدای Chirp 3: HD ببینید
فرمت های صوتی
Live API از فرمت های صوتی زیر پشتیبانی می کند:
- فرمت صوتی ورودی: صدای خام 16 بیتی PCM با فرکانس 16 کیلوهرتز کمی اندین
- فرمت صدای خروجی: صدای خام 16 بیتی PCM با فرکانس 24 کیلوهرتز کمی endian
محدودیت های نرخ
محدودیت های نرخ زیر اعمال می شود:
- 10 جلسه همزمان در هر پروژه Firebase
- 4 میلیون توکن در دقیقه
طول جلسه
مدت زمان پیش فرض برای یک جلسه 30 دقیقه است. هنگامی که مدت زمان جلسه از حد مجاز بیشتر شود، اتصال قطع می شود.
مدل نیز با اندازه زمینه محدود شده است. ارسال قطعات بزرگ ورودی ممکن است منجر به خاتمه زودتر جلسه شود.
تشخیص فعالیت صوتی (VAD)
این مدل به طور خودکار تشخیص فعالیت صوتی (VAD) را در جریان ورودی صوتی پیوسته انجام می دهد. VAD به طور پیش فرض فعال است.
توکن شمارش
نمیتوانید از CountTokens
API با Live API استفاده کنید.
Gemini Live API تعاملات متنی و صوتی دوسویه کم تأخیر را با Gemini فعال میکند. با استفاده از Live API ، میتوانید تجربه مکالمات صوتی طبیعی و انسانمانند را در اختیار کاربران نهایی قرار دهید و با استفاده از دستورات نوشتاری یا صوتی، پاسخهای مدل را قطع کنید. این مدل می تواند متن و ورودی صوتی را پردازش کند (ویدئو به زودی!)، و می تواند متن و خروجی صدا را ارائه دهد.
میتوانید با دستورات و Live API در Vertex AI Studio نمونهسازی اولیه کنید.
Live API یک API حالت دار است که یک اتصال WebSocket برای ایجاد یک جلسه بین مشتری و سرور Gemini ایجاد می کند. برای جزئیات، به مستندات مرجع Live API مراجعه کنید.
قبل از شروع
اگر قبلاً این کار را نکردهاید، راهنمای شروع را تکمیل کنید، که نحوه راهاندازی پروژه Firebase را توضیح میدهد، برنامه خود را به Firebase متصل کنید، SDK را اضافه کنید، سرویس Vertex AI را راهاندازی کنید، و یک نمونه LiveModel
ایجاد کنید.
مطمئن شوید که حداقل از این نسخه های کتابخانه Firebase استفاده می کنید:
iOS+ : هنوز پشتیبانی نمی شود | Android : v16.3.0+ ( BoM : v33.12.0+) | وب : هنوز پشتیبانی نمی شود | فلوتر : نسخه 1.5.0+ (BoM: نسخه 3.9.0+)
مدل هایی که از این قابلیت پشتیبانی می کنند
Live API فقط توسط gemini-2.0-flash-live-preview-04-09
(نه gemini-2.0-flash
) پشتیبانی می شود.
از ویژگی های استاندارد Live API استفاده کنید
این بخش نحوه استفاده از ویژگیهای استاندارد Live API را توضیح میدهد، بهویژه برای پخش جریانی انواع ورودیها و خروجیها:
ارسال متن و دریافت متن
می توانید ورودی متن پخش شده را ارسال کنید و خروجی متن پخش شده را دریافت کنید. مطمئن شوید که یک نمونه liveModel
ایجاد کرده اید و حالت پاسخ را روی Text
تنظیم کنید.
سویفت
Live API هنوز برای برنامه های پلتفرم اپل پشتیبانی نمی شود، اما به زودی دوباره بررسی کنید!
Kotlin
// Initialize the Vertex AI service and create a `LiveModel` instance
val model = Firebase.vertexAI.liveModel(
// The Live API requires this specific model.
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 service and create a `LiveModel` instance
LiveGenerativeModel lm = FirebaseVertexAI.getInstance().liveModel(
// The Live API requires this specific model.
"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_vertexai/firebase_vertexai.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 service and create a `LiveModel` instance
final model = FirebaseVertexAI.instance.liveModel(
// The Live API requires this specific model.
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
}
نحوه انتخاب یک مدل و به صورت اختیاری مکان مناسب برای مورد استفاده و برنامه خود را بیاموزید.
ارسال صوت و دریافت صدا
می توانید ورودی صوتی پخش شده را ارسال کنید و خروجی صدای پخش شده را دریافت کنید. مطمئن شوید که یک نمونه LiveModel
ایجاد کرده اید و حالت پاسخ را روی Audio
تنظیم کنید.
با نحوه پیکربندی و سفارشی کردن صدای پاسخ آشنا شوید (در ادامه این صفحه).
سویفت
Live API هنوز برای برنامه های پلتفرم اپل پشتیبانی نمی شود، اما به زودی دوباره بررسی کنید!
Kotlin
// Initialize the Vertex AI service and create a `LiveModel` instance
val model = Firebase.vertexAI.liveModel(
// The Live API requires this specific model.
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 service and create a `LiveModel` instance
LiveGenerativeModel lm = FirebaseVertexAI.getInstance().liveModel(
// The Live API requires this specific model.
"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);
وب
Live API هنوز برای برنامه های وب پشتیبانی نمی شود، اما به زودی دوباره بررسی کنید!
Dart
import 'package:firebase_vertexai/firebase_vertexai.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 service and create a `LiveModel` instance
final model = FirebaseVertexAI.instance.liveModel(
// The Live API requires this specific model.
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
}
نحوه انتخاب یک مدل و به صورت اختیاری مکان مناسب برای مورد استفاده و برنامه خود را بیاموزید.
می توانید ورودی صوتی پخش شده را ارسال کنید و خروجی متن پخش شده را دریافت کنید. مطمئن شوید که یک نمونه LiveModel
ایجاد کرده اید و حالت پاسخ را روی Text
تنظیم کنید.
سویفت
Live API هنوز برای برنامه های پلتفرم اپل پشتیبانی نمی شود، اما به زودی دوباره بررسی کنید!
Kotlin
// Initialize the Vertex AI service and create a `LiveModel` instance
val model = Firebase.vertexAI.liveModel(
// The Live API requires this specific model.
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
TODO - snippet ExecutorService executor = Executors.newFixedThreadPool(1);
// Initialize the Vertex AI service and create a `LiveModel` instance
LiveGenerativeModel lm = FirebaseVertexAI.getInstance().liveModel(
// The Live API requires this specific model.
"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_vertexai/firebase_vertexai.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,
);
final model = FirebaseVertexAI.instance.liveModel(
model: 'gemini-2.0-flash-live-preview-04-09',
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');
}
}
نحوه انتخاب یک مدل و به صورت اختیاری مکان مناسب برای مورد استفاده و برنامه خود را بیاموزید.
می توانید ورودی متن پخش شده را ارسال کنید و خروجی صوتی پخش شده را دریافت کنید. مطمئن شوید که یک نمونه LiveModel
ایجاد کرده اید و حالت پاسخ را روی Audio
تنظیم کنید.
با نحوه پیکربندی و سفارشی کردن صدای پاسخ آشنا شوید (در ادامه این صفحه).
سویفت
Live API هنوز برای برنامه های پلتفرم اپل پشتیبانی نمی شود، اما به زودی دوباره بررسی کنید!
Kotlin
// Initialize the Vertex AI service and create a `LiveModel` instance
val model = Firebase.vertexAI.liveModel(
// The Live API requires this specific model.
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 service and create a `LiveModel` instance
LiveGenerativeModel lm = FirebaseVertexAI.getInstance().liveModel(
// The Live API requires this specific model.
"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_vertexai/firebase_vertexai.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,
);
final model = FirebaseVertexAI.instance.liveModel(
model: 'gemini-2.0-flash-live-preview-04-09',
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');
}
}
نحوه انتخاب یک مدل و به صورت اختیاری مکان مناسب برای مورد استفاده و برنامه خود را بیاموزید.
تجربیات جذاب و تعاملی بیشتری ایجاد کنید
این بخش نحوه ایجاد و مدیریت ویژگیهای جذاب یا تعاملی Live API را شرح میدهد.
صدای پاسخ را تغییر دهید
Live API از Chirp 3 برای پشتیبانی از پاسخ های گفتاری ترکیبی استفاده می کند. هنگام استفاده از Vertex AI در Firebase ، میتوانید صدا را با ۵ صدای HD و ۳۱ زبان ارسال کنید.
اگر صدایی را مشخص نکنید، پیشفرض Puck
است. همچنین، میتوانید مدل را طوری پیکربندی کنید که به یکی از صداهای زیر پاسخ دهد:
Aoede (مونث)Charon (مرد) | Fenrir (مرد)Kore (مونث) | Puck (مرد) |
برای اطلاع از نحوه صدای این صداها و فهرست کامل زبانهای موجود، به Chirp 3: صداهای HD مراجعه کنید.
برای تعیین یک صدا، نام صدا را در شی speechConfig
به عنوان بخشی از پیکربندی مدل تنظیم کنید:
سویفت
Live API هنوز برای برنامه های پلتفرم اپل پشتیبانی نمی شود، اما به زودی دوباره بررسی کنید!
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 هنوز برای برنامه های وب پشتیبانی نمی شود، اما به زودی دوباره بررسی کنید!
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),
),
);
// ...
برای بهترین نتایج در هنگام درخواست و الزام مدل به پاسخگویی به زبان غیر انگلیسی، موارد زیر را به عنوان بخشی از دستورالعملهای سیستم خود بگنجانید:
RESPOND IN LANGUAGE. YOU MUST RESPOND UNMISTAKABLY IN LANGUAGE.
زمینه را در طول جلسات و درخواست ها حفظ کنید
میتوانید از ساختار چت برای حفظ زمینه در جلسات و درخواستها استفاده کنید. توجه داشته باشید که این فقط برای ورودی متن و خروجی متن کار می کند.
این رویکرد برای زمینه های کوتاه بهترین است. می توانید تعاملات نوبت به نوبه خود را برای نشان دادن توالی دقیق رویدادها ارسال کنید. برای زمینههای طولانیتر، توصیه میکنیم یک خلاصه پیام واحد ارائه کنید تا پنجره زمینه برای تعاملات بعدی آزاد شود.
وقفه ها را مدیریت کنید
Vertex AI در Firebase هنوز از مدیریت وقفه پشتیبانی نمی کند. به زودی دوباره بررسی کنید!
استفاده از فراخوانی تابع (ابزار)
میتوانید ابزارهایی مانند توابع موجود را برای استفاده با Live API درست مانند روشهای تولید محتوای استاندارد تعریف کنید. این بخش برخی تفاوت های ظریف را در هنگام استفاده از Live API با فراخوانی تابع توضیح می دهد. برای توضیحات کامل و مثال هایی برای فراخوانی تابع، راهنمای فراخوانی تابع را ببینید.
از یک اعلان واحد، مدل می تواند چندین فراخوانی تابع و کدهای لازم برای زنجیره خروجی های آنها را ایجاد کند. این کد در محیط sandbox اجرا می شود و پیام های BidiGenerateContentToolCall
بعدی را ایجاد می کند. اجرا متوقف می شود تا زمانی که نتایج هر فراخوانی در دسترس باشد، که پردازش متوالی را تضمین می کند.
علاوه بر این، استفاده از Live API با فراخوانی تابع بسیار قدرتمند است زیرا مدل میتواند اطلاعات پیگیری یا شفافسازی را از کاربر درخواست کند. برای مثال، اگر مدل اطلاعات کافی برای ارائه مقدار پارامتر به تابعی که میخواهد فراخوانی کند، نداشته باشد، آنگاه مدل میتواند از کاربر بخواهد اطلاعات بیشتری یا شفافسازی را ارائه دهد.
مشتری باید با BidiGenerateContentToolResponse
پاسخ دهد.
محدودیت ها و الزامات
محدودیت ها و الزامات زیر را در Live API به خاطر داشته باشید.
رونویسی
Vertex AI در Firebase هنوز از رونویسی پشتیبانی نمی کند. به زودی دوباره بررسی کنید!
زبان ها
- زبانهای ورودی: فهرست کامل زبانهای ورودی پشتیبانیشده برای مدلهای Gemini را ببینید
- زبانهای خروجی: فهرست کامل زبانهای خروجی موجود را در صدای Chirp 3: HD ببینید
فرمت های صوتی
Live API از فرمت های صوتی زیر پشتیبانی می کند:
- فرمت صوتی ورودی: صدای خام 16 بیتی PCM با فرکانس 16 کیلوهرتز کمی اندین
- فرمت صدای خروجی: صدای خام 16 بیتی PCM با فرکانس 24 کیلوهرتز کمی endian
محدودیت های نرخ
محدودیت های نرخ زیر اعمال می شود:
- 10 جلسه همزمان در هر پروژه Firebase
- 4 میلیون توکن در دقیقه
طول جلسه
مدت زمان پیش فرض برای یک جلسه 30 دقیقه است. هنگامی که مدت زمان جلسه از حد مجاز بیشتر شود، اتصال قطع می شود.
مدل نیز با اندازه زمینه محدود شده است. ارسال قطعات بزرگ ورودی ممکن است منجر به خاتمه زودتر جلسه شود.
تشخیص فعالیت صوتی (VAD)
این مدل به طور خودکار تشخیص فعالیت صوتی (VAD) را در جریان ورودی صوتی پیوسته انجام می دهد. VAD به طور پیش فرض فعال است.
توکن شمارش
نمیتوانید از CountTokens
API با Live API استفاده کنید.
Gemini Live API تعاملات متنی و صوتی دوسویه کم تأخیر را با Gemini فعال میکند. با استفاده از Live API ، میتوانید تجربه مکالمات صوتی طبیعی و انسانمانند را در اختیار کاربران نهایی قرار دهید و با استفاده از دستورات نوشتاری یا صوتی، پاسخهای مدل را قطع کنید. این مدل می تواند متن و ورودی صوتی را پردازش کند (ویدئو به زودی!)، و می تواند متن و خروجی صدا را ارائه دهد.
میتوانید با دستورات و Live API در Vertex AI Studio نمونهسازی اولیه کنید.
Live API یک API حالت دار است که یک اتصال WebSocket برای ایجاد یک جلسه بین مشتری و سرور Gemini ایجاد می کند. برای جزئیات، به مستندات مرجع Live API مراجعه کنید.
قبل از شروع
اگر قبلاً این کار را نکردهاید، راهنمای شروع را تکمیل کنید، که نحوه راهاندازی پروژه Firebase را توضیح میدهد، برنامه خود را به Firebase متصل کنید، SDK را اضافه کنید، سرویس Vertex AI را راهاندازی کنید، و یک نمونه LiveModel
ایجاد کنید.
مطمئن شوید که حداقل از این نسخه های کتابخانه Firebase استفاده می کنید:
iOS+ : هنوز پشتیبانی نمی شود | Android : v16.3.0+ ( BoM : v33.12.0+) | وب : هنوز پشتیبانی نمی شود | فلوتر : نسخه 1.5.0+ (BoM: نسخه 3.9.0+)
مدل هایی که از این قابلیت پشتیبانی می کنند
Live API فقط توسط gemini-2.0-flash-live-preview-04-09
(نه gemini-2.0-flash
) پشتیبانی می شود.
از ویژگی های استاندارد Live API استفاده کنید
این بخش نحوه استفاده از ویژگیهای استاندارد Live API را توضیح میدهد، بهویژه برای پخش جریانی انواع ورودیها و خروجیها:
ارسال متن و دریافت متن
می توانید ورودی متن پخش شده را ارسال کنید و خروجی متن پخش شده را دریافت کنید. مطمئن شوید که یک نمونه liveModel
ایجاد کرده اید و حالت پاسخ را روی Text
تنظیم کنید.
سویفت
Live API هنوز برای برنامه های پلتفرم اپل پشتیبانی نمی شود، اما به زودی دوباره بررسی کنید!
Kotlin
// Initialize the Vertex AI service and create a `LiveModel` instance
val model = Firebase.vertexAI.liveModel(
// The Live API requires this specific model.
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 service and create a `LiveModel` instance
LiveGenerativeModel lm = FirebaseVertexAI.getInstance().liveModel(
// The Live API requires this specific model.
"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_vertexai/firebase_vertexai.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 service and create a `LiveModel` instance
final model = FirebaseVertexAI.instance.liveModel(
// The Live API requires this specific model.
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
}
نحوه انتخاب یک مدل و به صورت اختیاری مکان مناسب برای مورد استفاده و برنامه خود را بیاموزید.
ارسال صوت و دریافت صدا
می توانید ورودی صوتی پخش شده را ارسال کنید و خروجی صدای پخش شده را دریافت کنید. مطمئن شوید که یک نمونه LiveModel
ایجاد کرده اید و حالت پاسخ را روی Audio
تنظیم کنید.
با نحوه پیکربندی و سفارشی کردن صدای پاسخ آشنا شوید (در ادامه این صفحه).
سویفت
Live API هنوز برای برنامه های پلتفرم اپل پشتیبانی نمی شود، اما به زودی دوباره بررسی کنید!
Kotlin
// Initialize the Vertex AI service and create a `LiveModel` instance
val model = Firebase.vertexAI.liveModel(
// The Live API requires this specific model.
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 service and create a `LiveModel` instance
LiveGenerativeModel lm = FirebaseVertexAI.getInstance().liveModel(
// The Live API requires this specific model.
"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);
وب
Live API هنوز برای برنامه های وب پشتیبانی نمی شود، اما به زودی دوباره بررسی کنید!
Dart
import 'package:firebase_vertexai/firebase_vertexai.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 service and create a `LiveModel` instance
final model = FirebaseVertexAI.instance.liveModel(
// The Live API requires this specific model.
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
}
نحوه انتخاب یک مدل و به صورت اختیاری مکان مناسب برای مورد استفاده و برنامه خود را بیاموزید.
می توانید ورودی صوتی پخش شده را ارسال کنید و خروجی متن پخش شده را دریافت کنید. مطمئن شوید که یک نمونه LiveModel
ایجاد کرده اید و حالت پاسخ را روی Text
تنظیم کنید.
سویفت
Live API هنوز برای برنامه های پلتفرم اپل پشتیبانی نمی شود، اما به زودی دوباره بررسی کنید!
Kotlin
// Initialize the Vertex AI service and create a `LiveModel` instance
val model = Firebase.vertexAI.liveModel(
// The Live API requires this specific model.
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
TODO - snippet ExecutorService executor = Executors.newFixedThreadPool(1);
// Initialize the Vertex AI service and create a `LiveModel` instance
LiveGenerativeModel lm = FirebaseVertexAI.getInstance().liveModel(
// The Live API requires this specific model.
"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_vertexai/firebase_vertexai.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,
);
final model = FirebaseVertexAI.instance.liveModel(
model: 'gemini-2.0-flash-live-preview-04-09',
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');
}
}
نحوه انتخاب یک مدل و به صورت اختیاری مکان مناسب برای مورد استفاده و برنامه خود را بیاموزید.
می توانید ورودی متن پخش شده را ارسال کنید و خروجی صوتی پخش شده را دریافت کنید. مطمئن شوید که یک نمونه LiveModel
ایجاد کرده اید و حالت پاسخ را روی Audio
تنظیم کنید.
با نحوه پیکربندی و سفارشی کردن صدای پاسخ آشنا شوید (در ادامه این صفحه).
سویفت
Live API هنوز برای برنامه های پلتفرم اپل پشتیبانی نمی شود، اما به زودی دوباره بررسی کنید!
Kotlin
// Initialize the Vertex AI service and create a `LiveModel` instance
val model = Firebase.vertexAI.liveModel(
// The Live API requires this specific model.
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 service and create a `LiveModel` instance
LiveGenerativeModel lm = FirebaseVertexAI.getInstance().liveModel(
// The Live API requires this specific model.
"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_vertexai/firebase_vertexai.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,
);
final model = FirebaseVertexAI.instance.liveModel(
model: 'gemini-2.0-flash-live-preview-04-09',
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');
}
}
نحوه انتخاب یک مدل و به صورت اختیاری مکان مناسب برای مورد استفاده و برنامه خود را بیاموزید.
تجربیات جذاب و تعاملی بیشتری ایجاد کنید
این بخش نحوه ایجاد و مدیریت ویژگیهای جذاب یا تعاملی Live API را شرح میدهد.
صدای پاسخ را تغییر دهید
Live API از Chirp 3 برای پشتیبانی از پاسخ های گفتاری ترکیبی استفاده می کند. هنگام استفاده از Vertex AI در Firebase ، میتوانید صدا را با ۵ صدای HD و ۳۱ زبان ارسال کنید.
اگر صدایی را مشخص نکنید، پیشفرض Puck
است. همچنین، میتوانید مدل را طوری پیکربندی کنید که به یکی از صداهای زیر پاسخ دهد:
Aoede (مونث)Charon (مرد) | Fenrir (مرد)Kore (مونث) | Puck (مرد) |
برای اطلاع از نحوه صدای این صداها و فهرست کامل زبانهای موجود، به Chirp 3: صداهای HD مراجعه کنید.
برای تعیین یک صدا، نام صدا را در شی speechConfig
به عنوان بخشی از پیکربندی مدل تنظیم کنید:
سویفت
Live API هنوز برای برنامه های پلتفرم اپل پشتیبانی نمی شود، اما به زودی دوباره بررسی کنید!
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 هنوز برای برنامه های وب پشتیبانی نمی شود، اما به زودی دوباره بررسی کنید!
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),
),
);
// ...
برای بهترین نتایج در هنگام درخواست و الزام مدل به پاسخگویی به زبان غیر انگلیسی، موارد زیر را به عنوان بخشی از دستورالعملهای سیستم خود بگنجانید:
RESPOND IN LANGUAGE. YOU MUST RESPOND UNMISTAKABLY IN LANGUAGE.
زمینه را در طول جلسات و درخواست ها حفظ کنید
میتوانید از ساختار چت برای حفظ زمینه در جلسات و درخواستها استفاده کنید. توجه داشته باشید که این فقط برای ورودی متن و خروجی متن کار می کند.
این رویکرد برای زمینه های کوتاه بهترین است. می توانید تعاملات نوبت به نوبه خود را برای نشان دادن توالی دقیق رویدادها ارسال کنید. برای زمینههای طولانیتر، توصیه میکنیم یک خلاصه پیام واحد ارائه کنید تا پنجره زمینه برای تعاملات بعدی آزاد شود.
وقفه ها را مدیریت کنید
Vertex AI در Firebase هنوز از مدیریت وقفه پشتیبانی نمی کند. به زودی دوباره بررسی کنید!
استفاده از فراخوانی تابع (ابزار)
میتوانید ابزارهایی مانند توابع موجود را برای استفاده با Live API درست مانند روشهای تولید محتوای استاندارد تعریف کنید. این بخش برخی تفاوت های ظریف را در هنگام استفاده از Live API با فراخوانی تابع توضیح می دهد. برای توضیحات کامل و مثال هایی برای فراخوانی تابع، راهنمای فراخوانی تابع را ببینید.
از یک اعلان واحد، مدل می تواند چندین فراخوانی تابع و کدهای لازم برای زنجیره خروجی های آنها را ایجاد کند. این کد در محیط sandbox اجرا می شود و پیام های BidiGenerateContentToolCall
بعدی را ایجاد می کند. اجرا متوقف می شود تا زمانی که نتایج هر فراخوانی در دسترس باشد، که پردازش متوالی را تضمین می کند.
علاوه بر این، استفاده از Live API با فراخوانی تابع بسیار قدرتمند است زیرا مدل میتواند اطلاعات پیگیری یا شفافسازی را از کاربر درخواست کند. برای مثال، اگر مدل اطلاعات کافی برای ارائه مقدار پارامتر به تابعی که میخواهد فراخوانی کند، نداشته باشد، آنگاه مدل میتواند از کاربر بخواهد اطلاعات بیشتری یا شفافسازی را ارائه دهد.
مشتری باید با BidiGenerateContentToolResponse
پاسخ دهد.
محدودیت ها و الزامات
محدودیت ها و الزامات زیر را در Live API به خاطر داشته باشید.
رونویسی
Vertex AI در Firebase هنوز از رونویسی پشتیبانی نمی کند. به زودی دوباره بررسی کنید!
زبان ها
- زبانهای ورودی: فهرست کامل زبانهای ورودی پشتیبانیشده برای مدلهای Gemini را ببینید
- زبانهای خروجی: فهرست کامل زبانهای خروجی موجود را در صدای Chirp 3: HD ببینید
فرمت های صوتی
Live API از فرمت های صوتی زیر پشتیبانی می کند:
- فرمت صوتی ورودی: صدای خام 16 بیتی PCM با فرکانس 16 کیلوهرتز کمی اندین
- فرمت صدای خروجی: صدای خام 16 بیتی PCM با فرکانس 24 کیلوهرتز کمی endian
محدودیت های نرخ
محدودیت های نرخ زیر اعمال می شود:
- 10 جلسه همزمان در هر پروژه Firebase
- 4 میلیون توکن در دقیقه
طول جلسه
مدت زمان پیش فرض برای یک جلسه 30 دقیقه است. هنگامی که مدت زمان جلسه از حد مجاز بیشتر شود، اتصال قطع می شود.
مدل نیز با اندازه زمینه محدود شده است. ارسال قطعات بزرگ ورودی ممکن است منجر به خاتمه زودتر جلسه شود.
تشخیص فعالیت صوتی (VAD)
این مدل به طور خودکار تشخیص فعالیت صوتی (VAD) را در جریان ورودی صوتی پیوسته انجام می دهد. VAD به طور پیش فرض فعال است.
توکن شمارش
نمیتوانید از CountTokens
API با Live API استفاده کنید.