Gemini Live API امکان تعامل متنی و صوتی دوطرفه با تأخیر کم را با Gemini فراهم میکند. با استفاده از Live API ، میتوانید تجربه مکالمات صوتی طبیعی و شبیه به انسان را برای کاربران نهایی فراهم کنید و بتوانید پاسخهای مدل را با استفاده از دستورات متنی یا صوتی قطع کنید. این مدل میتواند ورودی متن و صدا (بهزودی ویدیو!) را پردازش کند و خروجی متن و صدا ارائه دهد.
شما میتوانید با استفاده از دستورالعملها و Live API در Google AI Studio یا Vertex AI Studio نمونهسازی اولیه انجام دهید.
Live API یک API با وضعیت (stateful API) است که یک اتصال WebSocket برای ایجاد یک جلسه بین کلاینت و سرور Gemini ایجاد میکند. برای جزئیات بیشتر، به مستندات مرجع Live API ( Gemini Developer API |Vertex AI Gemini API ) مراجعه کنید.
قبل از اینکه شروع کنی
برای مشاهده محتوا و کد مخصوص ارائهدهنده در این صفحه، روی ارائهدهنده API Gemini خود کلیک کنید. |
اگر هنوز این کار را نکردهاید، راهنمای شروع به کار را تکمیل کنید، که نحوه راهاندازی پروژه Firebase، اتصال برنامه به Firebase، افزودن SDK، راهاندازی سرویس backend برای ارائهدهنده API انتخابی Gemini و ایجاد یک نمونه LiveModel را شرح میدهد.
مدلهایی که از این قابلیت پشتیبانی میکنند
مدلهایی که از Live API پشتیبانی میکنند، به ارائهدهندهی API Gemini انتخابی شما بستگی دارند.
رابط برنامهنویسی کاربردی (API) توسعهدهندگان جمینی
-
gemini-live-2.5-flash(GA خصوصی * ) -
gemini-live-2.5-flash-preview -
gemini-2.0-flash-live-001 -
gemini-2.0-flash-live-preview-04-09
-
Vertex AI Gemini API
-
gemini-live-2.5-flash(GA خصوصی * ) -
gemini-2.0-flash-live-preview-04-09(فقط درus-central1قابل دسترسی است)
-
توجه داشته باشید که برای نام مدلهای ۲.۵ برای Live API ، بخش live بلافاصله پس از بخش gemini قرار میگیرد.
* برای درخواست دسترسی با نماینده تیم حساب Google Cloud خود تماس بگیرید.
از ویژگیهای استاندارد Live API استفاده کنید
این بخش نحوه استفاده از ویژگیهای استاندارد Live API ، به ویژه برای پخش انواع مختلف ورودیها و خروجیها را شرح میدهد:
تولید متن جریانی از ورودی متن جریانی
| قبل از امتحان کردن این نمونه، بخش «قبل از شروع» این راهنما را برای راهاندازی پروژه و برنامه خود تکمیل کنید. در آن بخش، شما همچنین میتوانید روی دکمهای برای ارائهدهندهی API Gemini انتخابی خود کلیک کنید تا محتوای خاص ارائهدهنده را در این صفحه مشاهده کنید . |
شما میتوانید ورودی متن استریمشده ارسال و خروجی متن استریمشده دریافت کنید. حتماً یک نمونه liveModel ایجاد کنید و حالت پاسخ را روی Text تنظیم کنید.
سویفت
import FirebaseAILogic
// Initialize the Gemini Developer API backend service
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
let model = FirebaseAI.firebaseAI(backend: .googleAI()).liveModel(
modelName: "gemini-2.0-flash-live-preview-04-09",
// Configure the model to respond with text
generationConfig: LiveGenerationConfig(
responseModalities: [.text]
)
)
do {
let session = try await model.connect()
// Provide a text prompt
let text = "tell a short story"
await session.sendTextRealtime(text)
var outputText = ""
for try await message in session.responses {
if case let .content(content) = message.payload {
content.modelTurn?.parts.forEach { part in
if let part = part as? TextPart {
outputText += part.text
}
}
// Optional: if you don't require to send more requests.
if content.isTurnComplete {
await session.close()
}
}
}
// Output received from the server.
print(outputText)
} catch {
fatalError(error.localizedDescription)
}
Kotlin
// Initialize the Gemini Developer API backend service
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).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.turnComplete) {
// 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 Gemini Developer API backend service
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
LiveGenerativeModel lm = FirebaseAI.getInstance(GenerativeBackend.googleAI()).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
// Initialize the Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Create a `LiveGenerativeModel` instance with the flash-live model (only model that supports the Live API)
const model = getLiveGenerativeModel(ai, {
model: "gemini-2.0-flash-live-preview-04-09",
// Configure the model to respond with text
generationConfig: {
responseModalities: [ResponseModality.TEXT],
},
});
const session = await model.connect();
// Provide a text prompt
const prompt = "tell a short story";
session.send(prompt);
// Collect text from model's turn
let text = "";
const messages = session.receive();
for await (const message of messages) {
switch (message.type) {
case "serverContent":
if (message.turnComplete) {
console.log(text);
} else {
const parts = message.modelTurn?.parts;
if (parts) {
text += parts.map((part) => part.text).join("");
}
}
break;
case "toolCall":
// Ignore
case "toolCallCancellation":
// Ignore
}
}
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 Gemini Developer API backend service
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
final model = FirebaseAI.googleAI().liveGenerativeModel(
model: 'gemini-2.0-flash-live-preview-04-09',
// Configure the model to respond with text
liveGenerationConfig: LiveGenerationConfig(responseModalities: [ResponseModalities.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 Gemini Developer API backend service
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
var model = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()).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 تنظیم کنید.
یاد بگیرید که چگونه صدای پاسخ را پیکربندی و سفارشی کنید (بعداً در همین صفحه).
سویفت
import FirebaseAILogic
// Initialize the Gemini Developer API backend service
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
let model = FirebaseAI.firebaseAI(backend: .googleAI()).liveModel(
modelName: "gemini-2.0-flash-live-preview-04-09",
// Configure the model to respond with audio
generationConfig: LiveGenerationConfig(
responseModalities: [.audio]
)
)
do {
let session = try await model.connect()
// Load the audio file, or tap a microphone
guard let audioFile = NSDataAsset(name: "audio.pcm") else {
fatalError("Failed to load audio file")
}
// Provide the audio data
await session.sendAudioRealtime(audioFile.data)
var outputText = ""
for try await message in session.responses {
if case let .content(content) = message.payload {
content.modelTurn?.parts.forEach { part in
if let part = part as? InlineDataPart, part.mimeType.starts(with: "audio/pcm") {
// Handle 16bit pcm audio data at 24khz
playAudio(part.data)
}
}
// Optional: if you don't require to send more requests.
if content.isTurnComplete {
await session.close()
}
}
}
} catch {
fatalError(error.localizedDescription)
}
Kotlin
// Initialize the Gemini Developer API backend service
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).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 Gemini Developer API backend service
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
LiveGenerativeModel lm = FirebaseAI.getInstance(GenerativeBackend.googleAI()).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
// Initialize the Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Create a `LiveGenerativeModel` instance with the flash-live model (only model that supports the Live API)
const model = getLiveGenerativeModel(ai, {
model: "gemini-2.0-flash-live-preview-04-09",
// Configure the model to respond with audio
generationConfig: {
responseModalities: [ResponseModality.AUDIO],
},
});
const session = await model.connect();
// Start the audio conversation
const audioConversationController = await startAudioConversation(session);
// ... Later, to stop the audio conversation
// await audioConversationController.stop()
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 Gemini Developer API backend service
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
final model = FirebaseAI.googleAI().liveGenerativeModel(
model: 'gemini-2.0-flash-live-preview-04-09',
// Configure the model to respond with audio
liveGenerationConfig: LiveGenerationConfig(responseModalities: [ResponseModalities.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 Gemini Developer API backend service
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
var model = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()).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 تنظیم کنید.
سویفت
import FirebaseAILogic
// Initialize the Gemini Developer API backend service
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
let model = FirebaseAI.firebaseAI(backend: .googleAI()).liveModel(
modelName: "gemini-2.0-flash-live-preview-04-09",
// Configure the model to respond with text
generationConfig: LiveGenerationConfig(
responseModalities: [.text]
)
)
do {
let session = try await model.connect()
// Load the audio file, or tap a microphone
guard let audioFile = NSDataAsset(name: "audio.pcm") else {
fatalError("Failed to load audio file")
}
// Provide the audio data
await session.sendAudioRealtime(audioFile.data)
var outputText = ""
for try await message in session.responses {
if case let .content(content) = message.payload {
content.modelTurn?.parts.forEach { part in
if let part = part as? TextPart {
outputText += part.text
}
}
// Optional: if you don't require to send more requests.
if content.isTurnComplete {
await session.close()
}
}
}
// Output received from the server.
print(outputText)
} catch {
fatalError(error.localizedDescription)
}
Kotlin
// Initialize the Gemini Developer API backend service
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).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 Gemini Developer API backend service
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
LiveGenerativeModel lm = FirebaseAI.getInstance(GenerativeBackend.googleAI()).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
// Initialize the Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Create a `LiveGenerativeModel` instance with the flash-live model (only model that supports the Live API)
const model = getLiveGenerativeModel(ai, {
model: "gemini-2.0-flash-live-preview-04-09",
// Configure the model to respond with text
generationConfig: {
responseModalities: [ResponseModality.TEXT],
},
});
const session = await model.connect();
// TODO(developer): Collect audio data (16-bit 16kHz PCM)
// const audioData = ...
// Send audio
const audioPart = {
inlineData: { data: audioData, mimeType: "audio/pcm" },
};
session.send([audioPart]);
// Collect text from model's turn
let text = "";
const messages = session.receive();
for await (const message of messages) {
switch (message.type) {
case "serverContent":
if (message.turnComplete) {
console.log(text);
} else {
const parts = message.modelTurn?.parts;
if (parts) {
text += parts.map((part) => part.text).join("");
}
}
break;
case "toolCall":
// Ignore
case "toolCallCancellation":
// Ignore
}
}
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 Gemini Developer API backend service
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
final model = FirebaseAI.googleAI().liveGenerativeModel(
model: 'gemini-2.0-flash-live-preview-04-09',
// Configure the model to respond with text
liveGenerationConfig: LiveGenerationConfig(responseModalities: ResponseModalities.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 Gemini Developer API backend service
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
var model = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()).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 تنظیم کنید.
یاد بگیرید که چگونه صدای پاسخ را پیکربندی و سفارشی کنید (بعداً در همین صفحه).
سویفت
import FirebaseAILogic
// Initialize the Gemini Developer API backend service
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
let model = FirebaseAI.firebaseAI(backend: .googleAI()).liveModel(
modelName: "gemini-2.0-flash-live-preview-04-09",
// Configure the model to respond with audio
generationConfig: LiveGenerationConfig(
responseModalities: [.audio]
)
)
do {
let session = try await model.connect()
// Provide a text prompt
let text = "tell a short story"
await session.sendTextRealtime(text)
var outputText = ""
for try await message in session.responses {
if case let .content(content) = message.payload {
content.modelTurn?.parts.forEach { part in
if let part = part as? InlineDataPart, part.mimeType.starts(with: "audio/pcm") {
// Handle 16bit pcm audio data at 24khz
playAudio(part.data)
}
}
// Optional: if you don't require to send more requests.
if content.isTurnComplete {
await session.close()
}
}
}
} catch {
fatalError(error.localizedDescription)
}
Kotlin
// Initialize the Gemini Developer API backend service
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).liveModel(
modelName = "gemini-2.0-flash-live-preview-04-09",
// Configure the model to respond with audio
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.turnComplete) {
// 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 Gemini Developer API backend service
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
LiveGenerativeModel lm = FirebaseAI.getInstance(GenerativeBackend.googleAI()).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
// Initialize the Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Create a `LiveGenerativeModel` instance with the flash-live model (only model that supports the Live API)
const model = getLiveGenerativeModel(ai, {
model: "gemini-2.0-flash-live-preview-04-09",
// Configure the model to respond with audio
generationConfig: {
responseModalities: [ResponseModality.AUDIO],
},
});
const session = await model.connect();
// Provide a text prompt
const prompt = "tell a short story";
session.send(prompt);
// Handle the model's audio output
const messages = session.receive();
for await (const message of messages) {
switch (message.type) {
case "serverContent":
if (message.turnComplete) {
// TODO(developer): Handle turn completion
} else if (message.interrupted) {
// TODO(developer): Handle the interruption
break;
} else if (message.modelTurn) {
const parts = message.modelTurn?.parts;
parts?.forEach((part) => {
if (part.inlineData) {
// TODO(developer): Play the audio chunk
}
});
}
break;
case "toolCall":
// Ignore
case "toolCallCancellation":
// Ignore
}
}
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 Gemini Developer API backend service
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
final model = FirebaseAI.googleAI().liveGenerativeModel(
model: 'gemini-2.0-flash-live-preview-04-09',
// Configure the model to respond with audio
liveGenerationConfig: LiveGenerationConfig(responseModalities: ResponseModalities.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 Gemini Developer API backend service
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
var model = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()).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 ارسال کنید. برای لیست کامل و دموهایی از اینکه هر صدا چگونه به نظر میرسد، به Chirp 3: HD voices مراجعه کنید.
برای مشخص کردن یک صدا، نام صدا را در شیء speechConfig به عنوان بخشی از پیکربندی مدل تنظیم کنید. اگر صدایی مشخص نکنید، پیشفرض Puck است.
| قبل از امتحان کردن این نمونه، بخش «قبل از شروع» این راهنما را برای راهاندازی پروژه و برنامه خود تکمیل کنید. در آن بخش، شما همچنین میتوانید روی دکمهای برای ارائهدهندهی API Gemini انتخابی خود کلیک کنید تا محتوای خاص ارائهدهنده را در این صفحه مشاهده کنید . |
سویفت
import FirebaseAILogic
// ...
let model = FirebaseAI.firebaseAI(backend: .googleAI()).liveModel(
modelName: "gemini-2.0-flash-live-preview-04-09",
// Configure the model to use a specific voice for its audio response
generationConfig: LiveGenerationConfig(
responseModalities: [.audio],
speech: SpeechConfig(voiceName: "VOICE_NAME")
)
)
// ...
Kotlin
// ...
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).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 = Voice("VOICE_NAME"))
}
)
// ...
Java
// ...
LiveModel model = FirebaseAI.getInstance(GenerativeBackend.googleAI()).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(new Voice("VOICE_NAME")))
.build()
);
// ...
Web
// Initialize the Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Create a `LiveModel` instance with the flash-live model (only model that supports the Live API)
const model = getLiveGenerativeModel(ai, {
model: "gemini-2.0-flash-live-preview-04-09",
// Configure the model to use a specific voice for its audio response
generationConfig: {
responseModalities: [ResponseModality.AUDIO],
speechConfig: {
voiceConfig: {
prebuiltVoiceConfig: { voiceName: "VOICE_NAME" },
},
},
},
});
Dart
// ...
final model = FirebaseAI.googleAI().liveGenerativeModel(
model: 'gemini-2.0-flash-live-preview-04-09',
// Configure the model to use a specific voice for its audio response
liveGenerationConfig: LiveGenerationConfig(
responseModalities: ResponseModalities.audio,
speechConfig: SpeechConfig(voiceName: 'VOICE_NAME'),
),
);
// ...
وحدت
var model = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()).GetLiveModel(
modelName: "gemini-2.0-flash-live-preview-04-09",
liveGenerationConfig: new LiveGenerationConfig(
responseModalities: new[] { ResponseModality.Audio },
speechConfig: SpeechConfig.UsePrebuiltVoice("VOICE_NAME"))
);
برای بهترین نتیجه هنگام درخواست و الزام مدل به پاسخگویی به زبانی غیر از انگلیسی، موارد زیر را به عنوان بخشی از دستورالعملهای سیستم خود لحاظ کنید:
RESPOND IN LANGUAGE. YOU MUST RESPOND UNMISTAKABLY IN LANGUAGE.
حفظ زمینه در جلسات و درخواستها
شما میتوانید از یک ساختار چت برای حفظ زمینه در طول جلسات و درخواستها استفاده کنید. توجه داشته باشید که این فقط برای ورودی و خروجی متن کار میکند.
این رویکرد برای متنهای کوتاه بهترین گزینه است؛ میتوانید تعاملات نوبت به نوبت را برای نمایش توالی دقیق رویدادها ارسال کنید. برای متنهای طولانیتر، توصیه میکنیم یک خلاصه پیام واحد ارائه دهید تا پنجره متن برای تعاملات بعدی آزاد شود.
مدیریت وقفهها
منطق هوش مصنوعی فایربیس هنوز از مدیریت وقفهها پشتیبانی نمیکند . به زودی دوباره بررسی کنید!
استفاده از فراخوانی تابع (ابزارها)
شما میتوانید ابزارهایی مانند توابع موجود را برای استفاده با Live API تعریف کنید، درست مانند روشهای استاندارد تولید محتوا. این بخش برخی از نکات ظریف هنگام استفاده از Live API با فراخوانی تابع را شرح میدهد. برای توضیحات کامل و مثالهایی برای فراخوانی تابع، به راهنمای فراخوانی تابع مراجعه کنید.
از یک اعلان واحد، مدل میتواند چندین فراخوانی تابع و کد لازم برای زنجیرهسازی خروجیهای آنها را تولید کند. این کد در یک محیط sandbox اجرا میشود و پیامهای BidiGenerateContentToolCall بعدی را تولید میکند. اجرا تا زمانی که نتایج هر فراخوانی تابع در دسترس نباشد، متوقف میشود که پردازش متوالی را تضمین میکند.
علاوه بر این، استفاده از Live API با فراخوانی تابع به طور ویژه قدرتمند است زیرا مدل میتواند از کاربر درخواست پیگیری یا توضیح اطلاعات کند. به عنوان مثال، اگر مدل اطلاعات کافی برای ارائه مقدار پارامتر به تابعی که میخواهد فراخوانی کند، نداشته باشد، میتواند از کاربر بخواهد اطلاعات بیشتر یا توضیح بیشتری ارائه دهد.
کلاینت باید با BidiGenerateContentToolResponse پاسخ دهد.
محدودیتها و الزامات
محدودیتها و الزامات زیر را در مورد Live API در نظر داشته باشید.
رونویسی
منطق هوش مصنوعی فایربیس هنوز از رونویسی پشتیبانی نمیکند . به زودی دوباره بررسی کنید!
زبانها
- زبانهای ورودی: لیست کامل زبانهای ورودی پشتیبانیشده برای مدلهای Gemini را ببینید
- زبانهای خروجی: لیست کامل زبانهای خروجی موجود در Chirp 3: HD voices را ببینید
فرمتهای صوتی
Live API از فرمتهای صوتی زیر پشتیبانی میکند:
- فرمت صدای ورودی: صدای خام PCM با نرخ ۱۶ بیت و فرکانس ۱۶ کیلوهرتز (little-endian)
- فرمت صدای خروجی: صدای خام PCM با نرخ 16 بیت و فرکانس 24 کیلوهرتز (little-endian)
محدودیتهای نرخ
Live API برای هر دو جلسه همزمان در هر پروژه Firebase و همچنین توکن در هر دقیقه (TPM) محدودیتهای سرعت دارد.
رابط برنامهنویسی کاربردی توسعهدهندگان جمینی :
- محدودیتها بر اساس «رده استفاده» API توسعهدهنده Gemini پروژه شما متفاوت است (به مستندات محدودیتهای نرخ آنها مراجعه کنید)
API مربوط به Vertex AI Gemini :
- ۵۰۰۰ جلسه همزمان در هر پروژه Firebase
- ۴ میلیون توکن در دقیقه
طول جلسه
مدت زمان پیشفرض برای یک جلسه ۱۰ دقیقه است. وقتی مدت زمان جلسه از حد مجاز فراتر رود، اتصال قطع میشود.
این مدل همچنین توسط اندازه متن محدود شده است. ارسال بخشهای بزرگ ورودی ممکن است منجر به خاتمه زودهنگام جلسه شود.
تشخیص فعالیت صوتی (VAD)
این مدل به طور خودکار تشخیص فعالیت صوتی (VAD) را روی یک جریان ورودی صوتی پیوسته انجام میدهد. VAD به طور پیشفرض فعال است.
شمارش توکن
شما نمیتوانید از API CountTokens با Live API استفاده کنید.
درباره تجربه خود با Firebase AI Logic بازخورد دهید