Bạn có thể yêu cầu mô hình TTS Gemini tạo đầu ra lời nói (âm thanh) từ một câu lệnh văn bản. Khi sử dụng Firebase AI Logic, bạn có thể đưa ra yêu cầu này ngay trong ứng dụng của mình.
Tính năng tạo chuyển văn bản sang lời nói (TTS) có thể kiểm soát được, nghĩa là bạn cung cấp văn bản chính xác để tổng hợp thành lời nói. Ngoài ra, bạn có thể sử dụng ngôn ngữ tự nhiên trong câu lệnh để định hướng phong cách, giọng điệu, tốc độ và tông giọng của bản âm thanh đầu ra. Bạn có thể coi TTS là ngược lại với tính năng chép lời (chuyển lời nói thành văn bản).
Tính năng này có thể dùng được với bất kỳ mô hình Gemini -tts nào, được tối ưu hoá để tạo lời nói chất lượng cao, độ trễ thấp.
Với tính năng này, bạn có thể làm những việc như:
Kể chuyện tương tác: Tạo sách nói sống động hoặc trò chơi nhập vai, trong đó mô hình chuyển đổi giọng nói cho các nhân vật khác nhau hoặc điều chỉnh giọng điệu (như thì thầm khi hồi hộp hoặc cười khi nghe chuyện cười) cho phù hợp với câu chuyện.
Học ngôn ngữ: Tạo hướng dẫn phát âm có thể đọc văn bản bằng giọng điệu cụ thể của vùng miền hoặc với tốc độ chậm hơn để giúp người học luyện phát âm những từ khó.
Trình đọc nội dung theo ngữ cảnh: Đọc to các tin bài, công thức nấu ăn hoặc bài đăng trên blog bằng giọng đọc và giọng điệu phù hợp với nội dung (chẳng hạn như giọng điệu nghiêm túc cho tin nổi bật hoặc giọng điệu ấm áp, kiên nhẫn cho hướng dẫn nấu ăn từng bước).
Hướng dẫn này trình bày cách tạo lời nói từ văn bản đầu vào bằng một hoặc nhiều người nói và cách truyền trực tuyến phản hồi âm thanh.
Chuyển đến mã cho một người nói Chuyển đến mã cho nhiều người nói Chuyển đến mã cho phản hồi được truyền trực tuyến
So sánh giữa TTS và Live API
Cả mô hình chuyển văn bản sang lời nói (TTS) và mô hình Live API đều là các mô hình tạo lời nói có độ trễ thấp, có thể được định cấu hình cho nhiều giọng nói và ngôn ngữ phản hồi. Tuy nhiên, chúng phục vụ các trường hợp sử dụng rất khác nhau.
Tạo tính năng chuyển văn bản sang lời nói (TTS) là một hoạt động tương tác một chiều, yêu cầu-phản hồi (văn bản vào, âm thanh ra). Mô hình này được thiết kế riêng cho những trường hợp cần đọc chính xác văn bản được cung cấp, đồng thời có khả năng kiểm soát chi tiết phong cách và âm thanh, chẳng hạn như đọc podcast, sách nói hoặc đọc to bài viết.
Thế hệ Live API hỗ trợ tính năng truyền trực tuyến hai chiều cho cuộc trò chuyện thoại theo thời gian thực (giọng nói vào, giọng nói ra). Mô hình này hoạt động hiệu quả trong các bối cảnh trò chuyện linh hoạt, trong đó mô hình quyết định lời nói phù hợp để trả về. Xin lưu ý rằng các mô hình Live API mới nhất cũng hỗ trợ dữ liệu đầu vào là video và hình ảnh.
Trước khi bắt đầu
|
Nhấp vào nhà cung cấp Gemini API của bạn để xem nội dung và mã dành riêng cho nhà cung cấp trên trang này. |
Nếu bạn chưa thực hiện, hãy hoàn tất
hướng dẫn bắt đầu sử dụng, trong đó mô tả cách
thiết lập dự án Firebase, kết nối ứng dụng với Firebase, thêm SDK,
khởi chạy dịch vụ phụ trợ cho nhà cung cấp Gemini API mà bạn chọn và
tạo một thực thể GenerativeModel.
Để thử nghiệm và lặp lại câu lệnh, bạn nên sử dụng Google AI Studio.
Các mô hình hỗ trợ tính năng này
gemini-3.1-flash-tts-preview
Tạo lời nói từ văn bản
Bạn có thể tạo lời nói từ văn bản được cung cấp bằng mô hình TTS Gemini.
Tạo lời nói bằng một người nói
|
Trước khi thử mẫu này, hãy hoàn tất phần Trước khi bắt đầu của hướng dẫn này để thiết lập dự án và ứng dụng của bạn. Trong phần đó, bạn cũng sẽ nhấp vào nút cho nhà cung cấp Gemini API mà bạn chọn để xem nội dung dành riêng cho nhà cung cấp trên trang này. |
Bạn có thể định cấu hình mô hình để xuất âm thanh bằng một giọng nói duy nhất.
Trong GenerationConfig, hãy thêm nội dung sau:
Đặt
responseModalitiesđể bao gồmAUDIO.Định cấu hình
SpeechConfigbằng các thành phần sau:(Bắt buộc) Tên giọng nói phản hồi (ví dụ:
Kore)(Không bắt buộc) Mã ngôn ngữ.
Nếu bạn không chỉ định ngôn ngữ, các mô hình TTS Gemini có thể tự động phát hiện ngôn ngữ trong câu lệnh.
Gọi generateContent bằng câu lệnh văn bản của bạn. Mô hình trả về
dữ liệu âm thanh PCM thô trong các phần phản hồi.
Swift
import FirebaseAILogic
// Initialize the Gemini Developer API backend service.
let ai = FirebaseAI.firebaseAI(backend: .googleAI())
// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
let config = GenerationConfig(
responseModalities: [.audio],
speechConfig: SpeechConfig(voiceName: "Kore", languageCode: "en-US")
)
// Create a `GenerativeModel` instance with a model that supports speech generation.
let model = ai.generativeModel(
modelName: "gemini-3.1-flash-tts-preview",
generationConfig: config
)
// Provide a text prompt.
let prompt = "Say cheerfully: Have a wonderful day!"
// Call `generateContent` to generate the speech output based on your text prompt.
let response = try await model.generateContent(prompt)
// Extract the audio data and handle it for downstream use. For example:
for part in response.inlineDataParts {
let data = part.data // Raw PCM audio bytes (24kHz, 1 channel, 16-bit)
let mimeType = part.mimeType // for example: "audio/pcm"
print("Received audio data with MIME type: \(mimeType)")
// To play back raw PCM audio bytes, you'll need to write your own `playRawPcm` function.
playRawPcm(data: data)
}
Kotlin
Đối với Kotlin, các phương thức trong SDK này là hàm tạm ngưng và cần được gọi từ phạm vi Coroutine.
// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
val config = generationConfig {
responseModalities = listOf(ResponseModality.AUDIO)
speechConfig = SpeechConfig(
voice = Voice("Kore"),
languageCode = "en-US"
)
}
// Initialize the Gemini Developer API backend service.
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
.generativeModel(
modelName = "gemini-3.1-flash-tts-preview",
generationConfig = config
)
// Provide a text prompt.
val prompt = "Say cheerfully: Have a wonderful day!"
// Call `generateContent` to generate the speech output based on your text prompt.
val response = model.generateContent(prompt)
// Extract the audio data and handle it for downstream use. For example:
val part = response.candidates.firstOrNull()?.content?.parts?.firstOrNull()
if (part is InlineDataPart) {
val pcmData = part.inlineData // Raw PCM bytes (24kHz, 1 channel, 16-bit)
val mimeType = part.mimeType // for example: "audio/pcm"
// To play back PCM audio data, you'll need to write your own `playAudio` function.
playAudio(pcmData)
}
Java
Đối với Java, các phương thức truyền trực tuyến trong SDK này sẽ trả về một loạiPublisher từ thư viện Reactive Streams.
// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
GenerationConfig config = new GenerationConfig.Builder()
.setResponseModalities(Collections.singletonList(ResponseModality.AUDIO))
.setSpeechConfig(new SpeechConfig(new Voice("Kore"), "en-US"))
.build();
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports speech generation.
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.generativeModel("gemini-3.1-flash-tts-preview", config);
// Use the GenerativeModelFutures Java compatibility layer.
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
// Provide a text prompt.
String prompt = "Say cheerfully: Have a wonderful day!";
Content content = new Content.Builder().addText(prompt).build();
Executor executor = Executors.newSingleThreadExecutor();
// Call `generateContent` to generate the speech output based on your text prompt.
// Extract the audio data and handle it for downstream use.
ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
Part part = result.getCandidates().get(0).getContent().getParts().get(0);
if (part instanceof InlineDataPart) {
byte[] pcmData = ((InlineDataPart) part).getInlineData();
String mimeType = ((InlineDataPart) part).getMimeType();
// To play back PCM audio data, you'll need to write your own `playAudio` function.
playAudio(pcmData);
}
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}, executor);
Web
import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend, ResponseModality } from "firebase/ai";
// TODO(developer): Replace with your app's Firebase configuration
const firebaseConfig = { /* ... */ };
const firebaseApp = initializeApp(firebaseConfig);
// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
const generationConfig = {
responseModalities: [ResponseModality.AUDIO],
speechConfig: {
voiceConfig: { prebuiltVoiceConfig: { voiceName: "Kore" } },
languageCode: "en-US"
}
};
// Create a `GenerativeModel` instance with a model that supports speech generation.
const model = getGenerativeModel(ai, {
model: "gemini-3.1-flash-tts-preview",
generationConfig
});
// Provide a text prompt.
const prompt = "Say cheerfully: Have a wonderful day!";
// Call `generateContent` to generate the speech output based on your text prompt.
const result = await model.generateContent(prompt);
const inlineDataParts = result.response.inlineDataParts();
// Extract the audio data and handle it for downstream use. For example:
if (inlineDataParts?.[0]) {
const pcmBase64 = inlineDataParts[0].inlineData.data;
// Decode base64 to ArrayBuffer
const pcmBuffer = Uint8Array.from(atob(pcmBase64), c => c.charCodeAt(0)).buffer;
// To play back a PCM buffer, you'll need to write your own `playAudio` function.
playAudio(pcmBuffer);
}
Dart
import 'package:firebase_ai/firebase_ai.dart';
// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
final config = GenerationConfig(
responseModalities: [ResponseModalities.audio],
speechConfig: SpeechConfig(voiceName: 'Kore', languageCode: 'en-US'),
);
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports speech generation.
final model = FirebaseAI.googleAI().generativeModel(
model: 'gemini-3.1-flash-tts-preview',
generationConfig: config,
);
// Provide a text prompt.
final prompt = 'Say cheerfully: Have a wonderful day!';
// Call `generateContent` to generate the speech output based on your text prompt.
final response = await model.generateContent([Content.text(prompt)]);
// Extract the audio data and handle it for downstream use. For example:
final part = response.candidates.first.content.parts.first;
if (part is InlineDataPart && part.mimeType.startsWith('audio/')) {
final Uint8List pcmData = part.bytes; // Raw PCM bytes (24kHz, 1 channel, 16-bit)
// To play back PCM audio data, you'll need to write your own `playAudio` function.
await playAudio(pcmData);
}
Unity
using Firebase.AI;
// Set `responseModalities` to include `Audio`.
// Configure a `SpeechConfig` with your chosen voice name and language code.
var config = new GenerationConfig(
responseModalities: new System.Collections.Generic.List<ResponseModality> { ResponseModality.Audio },
speechConfig: SpeechConfig.UsePrebuiltVoice("Kore", "en-US")
);
// Initialize the Gemini Developer API backend service.
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());
// Create a `GenerativeModel` instance with a model that supports speech generation.
var model = ai.GetGenerativeModel(
modelName: "gemini-3.1-flash-tts-preview",
generationConfig: config
);
// Provide a text prompt.
var prompt = "Say cheerfully: Have a wonderful day!";
// Call `GenerateContentAsync` to generate the speech output based on your text prompt.
var response = await model.GenerateContentAsync(prompt);
// Extract the audio data and handle it for downstream use. For example:
if (response.Candidates.Count > 0) {
foreach (var part in response.Candidates[0].Content.Parts) {
if (part is ModelContent.InlineDataPart inlineData) {
byte[] pcmData = inlineData.Data; // Raw PCM bytes (24kHz, 1 channel, 16-bit)
// To play back PCM audio data, you'll need to write your own `playAudio` function.
playAudio(pcmData);
}
}
}
Tạo lời nói với nhiều người nói
|
Trước khi thử mẫu này, hãy hoàn tất phần Trước khi bắt đầu của hướng dẫn này để thiết lập dự án và ứng dụng của bạn. Trong phần đó, bạn cũng sẽ nhấp vào nút cho nhà cung cấp Gemini API mà bạn chọn để xem nội dung dành riêng cho nhà cung cấp trên trang này. |
Bạn có thể định cấu hình mô hình để sử dụng các giọng nói khác nhau cho những người nói khác nhau trong văn bản. Điều này rất hữu ích khi tạo âm thanh cho các cuộc đối thoại hoặc trò chuyện.
Tạo một
MultiSpeakerVoiceConfigliên kết tên người nói (bạn sẽ sử dụng trong câu lệnh) với tên giọng nói phản hồi cụ thể (ví dụ:Kore).Cấu hình nhiều người nói hỗ trợ đúng 2 người nói.
Trong
GenerationConfig, hãy thêm nội dung sau:Đặt
responseModalitiesđể bao gồmAUDIO.Định cấu hình
SpeechConfigbằng các thành phần sau:(Bắt buộc) Truyền
MultiSpeakerVoiceConfigcủa bạn vào.(Không bắt buộc) Mã ngôn ngữ.
Nếu bạn không chỉ định ngôn ngữ, các mô hình TTS Gemini có thể tự động phát hiện ngôn ngữ trong câu lệnh.
Trong câu lệnh, hãy cho biết ai đang nói bằng cách sử dụng tên người nói làm tiền tố (ví dụ:
Joe: Hello. Jane: Hi.).
Gọi generateContent bằng câu lệnh văn bản của bạn. Mô hình trả về
dữ liệu âm thanh PCM thô trong các phần phản hồi.
Swift
import FirebaseAILogic
// Initialize the Gemini Developer API backend service.
let ai = FirebaseAI.firebaseAI(backend: .googleAI())
// Configure a `SpeechConfig` for multiple speakers, assigning a voice to each speaker.
let multiSpeechConfig = SpeechConfig(
multiSpeakerVoiceConfig: MultiSpeakerVoiceConfig(
speakerVoiceConfigs: [
SpeakerVoiceConfig(speaker: "Joe", voiceName: "Puck"),
SpeakerVoiceConfig(speaker: "Jane", voiceName: "Kore")
]
),
languageCode: "en-US"
)
// Set `responseModalities` to include `audio`.
let config = GenerationConfig(
responseModalities: [.audio],
speechConfig: multiSpeechConfig
)
// Create a `GenerativeModel` instance with a model that supports speech generation.
let model = ai.generativeModel(
modelName: "gemini-3.1-flash-tts-preview",
generationConfig: config
)
// Provide a text prompt that includes the names of the speakers.
let prompt = """
Joe: How's it going today Jane?
Jane: Not too bad, how about you?
"""
// Call `generateContent` to generate the speech output based on your text prompt.
let response = try await model.generateContent(prompt)
// Extract the audio data and handle it for downstream use. For example:
for part in response.inlineDataParts {
let data = part.data // Raw PCM audio bytes (24kHz, 1 channel, 16-bit)
let mimeType = part.mimeType // for example: "audio/pcm"
print("Received audio data with MIME type: \(mimeType)")
// To play back raw PCM audio bytes, you'll need to write your own `playRawPcm` function.
playRawPcm(data: data)
}
Kotlin
Đối với Kotlin, các phương thức trong SDK này là hàm tạm ngưng và cần được gọi từ phạm vi Coroutine.
// Configure a `SpeechConfig` for multiple speakers, assigning a voice to each speaker.
val multiSpeechConfig = SpeechConfig(
multiSpeakerVoiceConfig = MultiSpeakerVoiceConfig(
speakerVoiceConfigs = listOf(
SpeakerVoiceConfig(speaker = "Joe", voice = Voice("Puck")),
SpeakerVoiceConfig(speaker = "Jane", voice = Voice("Kore"))
)
),
languageCode = "en-US"
)
// Set `responseModalities` to include `AUDIO`.
val config = generationConfig {
responseModalities = listOf(ResponseModality.AUDIO)
speechConfig = multiSpeechConfig
}
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports speech generation.
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
.generativeModel(
modelName = "gemini-3.1-flash-tts-preview",
generationConfig = config
)
// Provide a text prompt that includes the names of the speakers.
val prompt = """
Joe: How's it going today Jane?
Jane: Not too bad, how about you?
"""
// Call `generateContent` to generate the speech output based on your text prompt.
val response = model.generateContent(prompt)
// Extract the audio data and handle it for downstream use. For example:
val part = response.candidates.firstOrNull()?.content?.parts?.firstOrNull()
if (part is InlineDataPart) {
val pcmData = part.inlineData // Raw PCM bytes (24kHz, 1 channel, 16-bit)
val mimeType = part.mimeType // for example: "audio/pcm"
// To play back PCM audio data, you'll need to write your own `playAudio` function.
playAudio(pcmData)
}
Java
Đối với Java, các phương thức truyền trực tuyến trong SDK này sẽ trả về một loạiPublisher từ thư viện Reactive Streams.
// Configure a `SpeechConfig` for multiple speakers, assigning a voice to each speaker.
MultiSpeakerVoiceConfig multiSpeakerVoiceConfig = new MultiSpeakerVoiceConfig(
Arrays.asList(
new SpeakerVoiceConfig("Joe", new Voice("Puck")),
new SpeakerVoiceConfig("Jane", new Voice("Kore"))
)
);
SpeechConfig multiSpeechConfig = new SpeechConfig(multiSpeakerVoiceConfig);
// Set `responseModalities` to include `AUDIO`.
GenerationConfig config = new GenerationConfig.Builder()
.setResponseModalities(Collections.singletonList(ResponseModality.AUDIO))
.setSpeechConfig(multiSpeechConfig)
.build();
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports speech generation.
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.generativeModel("gemini-3.1-flash-tts-preview", config);
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
// Provide a text prompt that includes the names of the speakers.
String prompt = "Joe: How's it going today Jane?\nJane: Not too bad, how about you?";
Content content = new Content.Builder().addText(prompt).build();
Executor executor = Executors.newSingleThreadExecutor();
// Call `generateContent` to generate the speech output based on your text prompt.
// Extract the audio data and handle it for downstream use.
ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
Part part = result.getCandidates().get(0).getContent().getParts().get(0);
if (part instanceof InlineDataPart) {
byte[] pcmData = ((InlineDataPart) part).getInlineData(); // Raw PCM bytes (24kHz, 1 channel, 16-bit)
String mimeType = ((InlineDataPart) part).getMimeType(); // for example: "audio/pcm"
// To play back PCM audio data, you'll need to write your own `playAudio` function.
playAudio(pcmData);
}
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}, executor);
Web
import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend, ResponseModality } from "firebase/ai";
// TODO(developer): Replace with your app's Firebase configuration
const firebaseConfig = { /* ... */ };
const firebaseApp = initializeApp(firebaseConfig);
// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` for multiple speakers, assigning a voice to each speaker.
const generationConfig = {
responseModalities: [ResponseModality.AUDIO],
speechConfig: {
multiSpeakerVoiceConfig: {
speakerVoiceConfigs: [
{ speaker: "Joe", voiceConfig: { prebuiltVoiceConfig: { voiceName: "Puck" } } },
{ speaker: "Jane", voiceConfig: { prebuiltVoiceConfig: { voiceName: "Kore" } } }
]
},
languageCode: "en-US"
}
};
// Create a `GenerativeModel` instance with a model that supports speech generation.
const model = getGenerativeModel(ai, {
model: "gemini-3.1-flash-tts-preview",
generationConfig
});
// Provide a text prompt that includes the names of the speakers.
const prompt = `
Joe: How's it going today Jane?
Jane: Not too bad, how about you?
`;
// Call `generateContent` to generate the speech output based on your text prompt.
const result = await model.generateContent(prompt);
const inlineDataParts = result.response.inlineDataParts();
// Extract the audio data and handle it for downstream use. For example:
if (inlineDataParts?.[0]) {
const pcmBase64 = inlineDataParts[0].inlineData.data; // Raw PCM bytes (24kHz, 1 channel, 16-bit)
const pcmBuffer = Uint8Array.from(atob(pcmBase64), c => c.charCodeAt(0)).buffer;
// To play back a PCM buffer, you'll need to write your own `playAudio` function.
playAudio(pcmBuffer);
}
Dart
import 'package:firebase_ai/firebase_ai.dart';
// Configure a `SpeechConfig` for multiple speakers, assigning a voice to each speaker.
final multiSpeechConfig = SpeechConfig.multiSpeaker(
multiSpeakerVoiceConfig: MultiSpeakerVoiceConfig(
speakerVoiceConfigs: [
SpeakerVoiceConfig(speaker: 'Joe', voiceName: 'Puck'),
SpeakerVoiceConfig(speaker: 'Jane', voiceName: 'Kore'),
],
),
languageCode: 'en-US',
);
// Set `responseModalities` to include `audio`.
final config = GenerationConfig(
responseModalities: [ResponseModalities.audio],
speechConfig: multiSpeechConfig,
);
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports speech generation.
final model = FirebaseAI.googleAI().generativeModel(
model: 'gemini-3.1-flash-tts-preview',
generationConfig: config,
);
// Provide a text prompt that includes the names of the speakers.
final prompt = '''
Joe: How's it going today Jane?
Jane: Not too bad, how about you?
''';
// Call `generateContent` to generate the speech output based on your text prompt.
final response = await model.generateContent([Content.text(prompt)]);
// Extract the audio data and handle it for downstream use. For example:
final part = response.candidates.first.content.parts.first;
if (part is InlineDataPart && part.mimeType.startsWith('audio/')) {
final Uint8List pcmData = part.bytes; // Raw PCM bytes (24kHz, 1 channel, 16-bit)
// To play back PCM audio data, you'll need to write your own `playAudio` function.
await playAudio(pcmData);
}
Unity
using Firebase.AI;
// Configure a `SpeechConfig` for multiple speakers, assigning a voice to each speaker.
var multiSpeakerVoiceConfig = new MultiSpeakerVoiceConfig(
new System.Collections.Generic.List<SpeakerVoiceConfig> {
SpeakerVoiceConfig.UsePrebuiltVoice("Joe", "Puck"),
SpeakerVoiceConfig.UsePrebuiltVoice("Jane", "Kore")
}
);
var multiSpeechConfig = SpeechConfig.UseMultiSpeakerVoice(multiSpeakerVoiceConfig);
// Set `responseModalities` to include `Audio`.
var config = new GenerationConfig(
responseModalities: new System.Collections.Generic.List<ResponseModality> { ResponseModality.Audio },
speechConfig: multiSpeechConfig
);
// Initialize the Gemini Developer API backend service.
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());
// Create a `GenerativeModel` instance with a model that supports speech generation.
var model = ai.GetGenerativeModel(
modelName: "gemini-3.1-flash-tts-preview",
generationConfig: config
);
// Provide a text prompt that includes the names of the speakers.
var prompt = "Joe: How's it going today Jane?\nJane: Not too bad, how about you?";
// Call `GenerateContentAsync` to generate the speech output based on your text prompt.
var response = await model.GenerateContentAsync(prompt);
// Extract the audio data and handle it for downstream use. For example:
if (response.Candidates.Count > 0) {
foreach (var part in response.Candidates[0].Content.Parts) {
if (part is ModelContent.InlineDataPart inlineData) {
byte[] pcmData = inlineData.Data; // Raw PCM bytes (24kHz, 1 channel, 16-bit)
// To play back PCM audio data, you'll need to write your own `playAudio` function.
playAudio(pcmData);
}
}
}
Truyền trực tuyến câu trả lời
|
Trước khi thử mẫu này, hãy hoàn tất phần Trước khi bắt đầu của hướng dẫn này để thiết lập dự án và ứng dụng của bạn. Trong phần đó, bạn cũng sẽ nhấp vào nút cho nhà cung cấp Gemini API mà bạn chọn để xem nội dung dành riêng cho nhà cung cấp trên trang này. |
Bạn có thể đạt được tốc độ tương tác nhanh hơn và độ trễ thấp hơn bằng cách truyền trực tuyến phản hồi âm thanh khi phản hồi đó được tạo, thay vì chờ toàn bộ tệp âm thanh hoàn tất.
Tính năng truyền trực tuyến lời nói được tạo hỗ trợ cả cấu hình một người nói và nhiều người nói. Tính năng này chỉ được hỗ trợ khi sử dụng các mô hình Gemini 3.x TTS.
Để truyền trực tuyến câu trả lời bằng giọng nói, hãy gọi generateContentStream thay vì generateContent và xử lý các đoạn khi chúng đến. Các ví dụ sau đây
cho thấy cách truyền trực tuyến câu trả lời của một người nói:
Swift
import FirebaseAILogic
// Initialize the Gemini Developer API backend service.
let ai = FirebaseAI.firebaseAI(backend: .googleAI())
// Set `responseModalities` to include `audio`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
let config = GenerationConfig(
responseModalities: [.audio],
speechConfig: SpeechConfig(voiceName: "Kore")
)
// Create a `GenerativeModel` instance with a model that supports speech generation.
let model = ai.generativeModel(
modelName: "gemini-3.1-flash-tts-preview",
generationConfig: config
)
// Provide a text prompt.
let prompt = "Tell me a story about a brave knight."
// Call `generateContentStream` to generate the speech output stream based on your text prompt.
let responseStream = try model.generateContentStream(prompt)
// Extract the audio data and handle it for downstream use. For example:
for try await chunk in responseStream {
for part in chunk.inlineDataParts {
let data = part.data // Raw PCM audio bytes (24kHz, 1 channel, 16-bit)
let mimeType = part.mimeType // for example: "audio/pcm"
// Append the audio chunk to your audio queue/buffer for playback.
appendAudioChunk(data)
}
}
Kotlin
Đối với Kotlin, các phương thức trong SDK này là hàm tạm ngưng và cần được gọi từ phạm vi Coroutine.
// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
val config = generationConfig {
responseModalities = listOf(ResponseModality.AUDIO)
speechConfig = SpeechConfig(voice = Voice("Kore"))
}
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports speech generation.
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
.generativeModel(
modelName = "gemini-3.1-flash-tts-preview",
generationConfig = config
)
// Provide a text prompt.
val prompt = "Tell me a story about a brave knight."
// Call `generateContentStream` to generate the speech output stream based on your text prompt.
// Extract the audio data and handle it for downstream use.
model.generateContentStream(prompt).collect { chunk ->
val part = chunk.candidates.firstOrNull()?.content?.parts?.firstOrNull()
if (part is InlineDataPart) {
val pcmChunk = part.inlineData // Raw PCM bytes (24kHz, 1 channel, 16-bit)
val mimeType = part.mimeType // for example: "audio/pcm"
// Append the audio chunk to your audio queue/buffer for playback.
appendAudioChunk(pcmChunk)
}
}
Java
Đối với Java, các phương thức truyền trực tuyến trong SDK này sẽ trả về một loạiPublisher từ thư viện Reactive Streams.
// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
GenerationConfig config = new GenerationConfig.Builder()
.setResponseModalities(Collections.singletonList(ResponseModality.AUDIO))
.setSpeechConfig(new SpeechConfig(new Voice("Kore")))
.build();
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports speech generation.
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.generativeModel("gemini-3.1-flash-tts-preview", config);
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
// Provide a text prompt.
String prompt = "Tell me a story about a brave knight.";
Content content = new Content.Builder().addText(prompt).build();
// Call `generateContentStream` to generate the speech output stream based on your text prompt.
Publisher<GenerateContentResponse> streamingResponse =
model.generateContentStream(content);
// Extract the audio data and handle it for downstream use.
streamingResponse.subscribe(new Subscriber<GenerateContentResponse>() {
@Override
public void onSubscribe(Subscription s) {
s.request(Long.MAX_VALUE);
}
@Override
public void onNext(GenerateContentResponse chunk) {
Part part = chunk.getCandidates().get(0).getContent().getParts().get(0);
if (part instanceof InlineDataPart) {
byte[] pcmChunk = ((InlineDataPart) part).getInlineData(); // Raw PCM bytes (24kHz, 1 channel, 16-bit)
String mimeType = ((InlineDataPart) part).getMimeType(); // for example: "audio/pcm"
// Append the audio chunk to your audio queue/buffer for playback.
appendAudioChunk(pcmChunk);
}
}
@Override
public void onComplete() {
// Audio stream complete.
}
@Override
public void onError(Throwable t) {
t.printStackTrace();
}
});
Web
import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend, ResponseModality } from "firebase/ai";
// TODO(developer): Replace with your app's Firebase configuration
const firebaseConfig = { /* ... */ };
const firebaseApp = initializeApp(firebaseConfig);
// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
const generationConfig = {
responseModalities: [ResponseModality.AUDIO],
speechConfig: {
voiceConfig: { prebuiltVoiceConfig: { voiceName: "Kore" } }
}
};
// Create a `GenerativeModel` instance with a model that supports speech generation.
const model = getGenerativeModel(ai, {
model: "gemini-3.1-flash-tts-preview",
generationConfig
});
// Provide a text prompt.
const prompt = "Tell me a story about a brave knight.";
// Call `generateContentStream` to generate the speech output stream based on your text prompt.
const result = await model.generateContentStream(prompt);
// Extract the audio data and handle it for downstream use. For example:
const playbackQueue = [];
for await (const chunk of result.stream) {
const inlineDataParts = chunk.inlineDataParts();
if (inlineDataParts?.[0]) {
const pcmBase64 = inlineDataParts[0].inlineData.data; // Raw PCM bytes (24kHz, 1 channel, 16-bit)
const pcmBuffer = Uint8Array.from(atob(pcmBase64), c => c.charCodeAt(0)).buffer;
// Append the audio chunk to your audio queue/buffer for playback.
playbackQueue.push(pcmBuffer);
}
}
// To play back an array of PCM buffers in sequence, you'll need to write your own `processPlaybackQueue` function.
processPlaybackQueue(playbackQueue);
Dart
import 'package:firebase_ai/firebase_ai.dart';
// Set `responseModalities` to include `audio`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
final config = GenerationConfig(
responseModalities: [ResponseModalities.audio],
speechConfig: SpeechConfig(voiceName: 'Kore'),
);
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports speech generation.
final model = FirebaseAI.googleAI().generativeModel(
model: 'gemini-3.1-flash-tts-preview',
generationConfig: config,
);
// Provide a text prompt.
final prompt = 'Tell me a story about a brave knight.';
// Call `generateContentStream` to generate the speech output stream based on your text prompt.
final responseStream = model.generateContentStream([Content.text(prompt)]);
// Extract the audio data and handle it for downstream use. For example:
await for (final chunk in responseStream) {
final part = chunk.candidates.first.content.parts.first;
if (part is InlineDataPart && part.mimeType.startsWith('audio/')) {
final Uint8List pcmChunk = part.bytes; // Raw PCM bytes (24kHz, 1 channel, 16-bit)
// Append the audio chunk to your audio queue/buffer for playback.
appendAudioChunk(pcmChunk);
}
}
Unity
using System.Collections.Generic;
using System.Linq;
using Firebase.AI;
// Initialize the Gemini Developer API backend service.
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());
// Set `ResponseModalities` to include `Audio`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
var config = new GenerationConfig(
responseModalities: new List<ResponseModality> { ResponseModality.Audio },
speechConfig: SpeechConfig.UsePrebuiltVoice("Kore")
);
// Create a `GenerativeModel` instance with a model that supports speech generation.
var model = ai.GetGenerativeModel(
modelName: "gemini-3.1-flash-tts-preview",
generationConfig: config
);
// Provide a text prompt.
var prompt = "Tell me a story about a brave knight.";
// Call `GenerateContentStreamAsync` to generate the speech output stream based on your text prompt.
var responseStream = model.GenerateContentStreamAsync(prompt);
// Extract the audio data and handle it for downstream use. For example:
await foreach (var response in responseStream)
{
var audioParts = response.Candidates.FirstOrDefault().Content.Parts
.OfType<ModelContent.InlineDataPart>();
foreach (var part in audioParts)
{
byte[] pcmChunk = part.Data; // Raw PCM bytes (24kHz, 1 channel, 16-bit)
// Append the audio chunk to your audio queue/buffer for playback.
appendAudioChunk(pcmChunk);
}
}
Kiểm soát lời nói đầu ra bằng câu lệnh
Bạn có thể tác động đến giọng điệu, tốc độ và phong cách của lời nói được tạo bằng cách sử dụng các kỹ thuật đặt câu lệnh cụ thể.
Các tiểu mục sau đây về cấu trúc câu lệnh và thẻ âm thanh mô tả hướng dẫn cấp cao. Để biết hướng dẫn chi tiết, hãy tham khảo hướng dẫn viết câu lệnh này.
Cấu trúc câu lệnh
Để có kết quả tốt nhất, hãy cấu trúc câu lệnh của bạn bằng các thành phần sau:
Audio Profile: Mô tả tính cách, đặc điểm nhận dạng cốt lõi và nguyên mẫu của người nói (ví dụ:A warm, professional narrator).Scene: Mô tả môi trường và cảm xúc (ví dụ:In a quiet libraryhoặcAmidst a noisy crowd).Director's Notes: Mô tả cảm xúc, nhịp độ, phong cách và giọng điệu (ví dụ:Speak slowly and with mystery).Sample Context: Cung cấp cho mô hình một điểm bắt đầu (ví dụ:The speaker is greeting a close friend).Bản chép lời: Văn bản thực tế sẽ được đọc. Để có hiệu suất tốt nhất, hãy đảm bảo giọng điệu và bối cảnh của văn bản phù hợp với hồ sơ giọng nói và ghi chú của đạo diễn.
Ví dụ về câu lệnh:
[Audio Profile: A young, energetic voice]
[Scene: A lively sports broadcast]
[Director's Notes: Speak fast, with high energy and excitement]
[Sample Context: The game just ended with a last-second touchdown]
Welcome back fans! What an incredible game we're witnessing today!
Thẻ âm thanh
Bạn có thể chèn trực tiếp các thẻ định dạng vào câu lệnh văn bản để hướng dẫn mô hình thực hiện.
Thẻ âm thanh chỉ được hỗ trợ khi sử dụng các mô hình Gemini 3.x TTS.
Sau đây là một số thẻ thường dùng:
[whispers]: Nói thì thầm[laughs]: Để thêm tiếng cười[giggles]: Để thêm tiếng cười khúc khích[sighs]: Để thêm tiếng thở dài[gasp]: Để thêm tiếng thở hổn hển[shouting]: La hét[excited]: Nói một cách hào hứng[serious]: Nói chuyện nghiêm túc[sighs whispers]: Cảm xúc kết hợp (bạn có thể kết hợp các thẻ)
Hãy lưu ý những điều sau khi sử dụng thẻ âm thanh:
Không có danh sách đầy đủ: Không có danh sách cố định về các thẻ được hỗ trợ. Bạn có thể thử nghiệm với nhiều cảm xúc và biểu cảm khác nhau (như
[bored],[sarcastically]hoặc thậm chí là[like dracula]) để xem kết quả thay đổi như thế nào.Câu lệnh văn bản không phải bằng tiếng Anh: Nếu câu lệnh văn bản của bạn không phải bằng tiếng Anh, bạn vẫn nên sử dụng thẻ âm thanh bằng tiếng Anh để có kết quả tốt nhất.
Ví dụ về câu lệnh:
I have a secret to tell you. [whispers] I found the hidden treasure. [laughs] I can't believe it!
Giới hạn và yêu cầu
Hãy lưu ý những hạn chế và yêu cầu sau đây khi sử dụng tính năng tạo lời nói:
Cấu hình nhiều người nói hỗ trợ đúng 2 người nói.
Các tính năng sau chỉ được hỗ trợ khi sử dụng các mô hình Gemini 3.x TTS: truyền trực tuyến, thẻ âm thanh và các ngôn ngữ khác được phát hiện tự động.
Các quy tắc ràng buộc cho gemini-3.1-flash-tts-preview
- Giọng nói không nhất quán: Kết quả của mô hình có thể không phải lúc nào cũng khớp chính xác với người nói đã chọn nếu giọng điệu và bối cảnh của câu lệnh không phù hợp với hồ sơ của người nói (ví dụ: giọng nam trầm cố gắng nói như một cô gái trẻ). Đảm bảo bối cảnh của câu lệnh phù hợp với giọng nói.
- Kết quả đầu ra dài hơn: Chất lượng và tính nhất quán của giọng nói có thể bị ảnh hưởng đối với âm thanh dài hơn vài phút. Bạn nên chia câu lệnh văn bản dài thành các phần nhỏ hơn.
- Đôi khi trả về mã thông báo văn bản: Đôi khi, mô hình trả về mã thông báo văn bản thay vì mã thông báo âm thanh, khiến yêu cầu không thành công và gặp lỗi
500. Vì điều này xảy ra ngẫu nhiên trong một tỷ lệ nhỏ các yêu cầu, nên bạn cần triển khai logic thử lại trong ứng dụng của mình. - Trình phân loại từ chối sai: Câu lệnh mơ hồ có thể khiến trình phân loại tổng hợp lời nói không hoạt động, dẫn đến việc yêu cầu bị từ chối (
PROHIBITED_CONTENT) hoặc khiến mô hình đọc to hướng dẫn về phong cách của bạn. Để tránh điều này, hãy sử dụng câu lệnh có cấu trúc với chỉ dẫn mở đầu rõ ràng (nhưAudio ProfilevàDirector's Notes) ở đầu câu lệnh.
Giọng nói và ngôn ngữ được hỗ trợ
Các mô hình TTS Gemini nhận dữ liệu đầu vào dạng văn bản và tạo ra dữ liệu đầu ra dạng âm thanh, vì vậy, phản hồi chính là lời nói được tổng hợp. Các tiểu mục sau đây liệt kê các giọng nói và ngôn ngữ được hỗ trợ mà các mô hình TTS Gemini có thể "nói" (hoặc phản hồi).
Các giọng nói này hỗ trợ đa ngôn ngữ, tức là bạn có thể dùng cùng một giọng nói để tạo lời nói bằng bất kỳ ngôn ngữ nào được hỗ trợ. Ví dụ: bạn có thể đặt giọng nói thành Kore và gửi một tập hợp câu lệnh văn bản bằng tiếng Tây Ban Nha, tiếng Hindi và tiếng Việt. Tất cả câu trả lời sẽ được phát bằng giọng nói Kore, nhưng bằng từng ngôn ngữ khác nhau.
Tên giọng nói
Các mô hình TTS Gemini hỗ trợ 30 giọng nói HD tổng hợp khác nhau, mỗi giọng nói có những đặc điểm riêng biệt. Bạn có thể xem danh sách các lựa chọn giọng nói cho câu trả lời và nghe bản minh hoạ của từng giọng nói bằng cách mở rộng phần bên dưới.
Ngôn ngữ
Các mô hình TTS Gemini có thể tự động phát hiện các ngôn ngữ sau trong câu lệnh văn bản của bạn. Lời nói được tạo sẽ sử dụng ngôn ngữ đó.
Xin lưu ý rằng bạn có thể tuỳ ý đặt mã ngôn ngữ một cách rõ ràng trong cấu hình lời nói.
Ngôn ngữ được tất cả các mô hình tạo âm thanh hỗ trợ
| Ngôn ngữ | Mã BCP-47 | Ngôn ngữ | Mã BCP-47 |
|---|---|---|---|
| Tiếng Ả Rập (Ai Cập) | ar-EG | Tiếng Đức (Đức) | de-DE |
| Tiếng Anh (Mỹ) | en-US | Tiếng Tây Ban Nha (Mỹ) | es-US |
| Tiếng Pháp (Pháp) | fr-FR | Tiếng Hindi (Ấn Độ) | hi-IN |
| Tiếng Indonesia (Indonesia) | id-ID | Tiếng Ý (Ý) | it-IT |
| Tiếng Nhật (Nhật Bản) | ja-JP | Tiếng Hàn (Hàn Quốc) | ko-KR |
| Tiếng Bồ Đào Nha (Brazil) | pt-BR | Tiếng Nga (Nga) | ru-RU |
| Tiếng Hà Lan (Hà Lan) | nl-NL | Tiếng Ba Lan (Ba Lan) | pl-PL |
| Tiếng Thái (Thái Lan) | th-TH | Tiếng Thổ Nhĩ Kỳ (Thổ Nhĩ Kỳ) | tr-TR |
| Tiếng Việt (Việt Nam) | vi-VN | Tiếng Rumani (Rumani) | ro-RO |
| Tiếng Ukraina (Ukraina) | uk-UA | Tiếng Bengali (Bangladesh) | bn-BD |
| Tiếng Anh (Ấn Độ) | Gói en-IN và hi-IN | Tiếng Marathi (Ấn Độ) | mr-IN |
| Tiếng Tamil (Ấn Độ) | ta-IN | Tiếng Telugu (Ấn Độ) | te-IN |
Các ngôn ngữ khác được các mô hình 3.x tạo âm thanh hỗ trợ
| Ngôn ngữ | Mã BCP-47 | Ngôn ngữ | Mã BCP-47 |
|---|---|---|---|
| Tiếng Hà Lan ở Nam Phi | af | Tiếng Philippines | fil |
| Tiếng Albania | sq | Tiếng Phần Lan | fi |
| Tiếng Amhara | sáng | Tiếng Galicia | gl |
| Tiếng Armenia | hy | Tiếng Gruzia | ka |
| Tiếng Azerbaijan | az | Tiếng Hy Lạp | el |
| Tiếng Basque | eu | Tiếng Gujarat | gu |
| Tiếng Belarus | be | Tiếng Creole ở Haiti | ht |
| Tiếng Bungary | bg | Tiếng Do Thái | he |
| Tiếng Miến Điện | của tôi | Tiếng Hungary | hu |
| Tiếng Catalan | ca | Tiếng Iceland | là |
| Tiếng Cebuano | ceb | Tiếng Java | jv |
| Tiếng Trung, tiếng Quan thoại | cmn | Tiếng Kannada | kn |
| Tiếng Croatia | giờ | Tiếng Konkani | kok |
| Tiếng Séc | cs | Tiếng Lào | lo |
| Tiếng Đan Mạch | da | Tiếng Latinh | la |
| Tiếng Estonia | et | Tiếng Latvia | lv |
| Tiếng Lithuania | lt | Tiếng Luxembourg | lb |
| Tiếng Macedonia | mk | Tiếng Maithili | mai |
| Tiếng Malagasy | mg | Tiếng Malay | ms |
| Tiếng Malayalam | ml | Tiếng Mông Cổ | mn |
| Tiếng Nepal | ne | Tiếng Na Uy, Bokmål | nb |
| Tiếng Na Uy, Nynorsk | nn | Tiếng Odia | hoặc |
| Tiếng Pashto | ps | Tiếng Ba Tư | fa |
| Tiếng Punjab | pa | Tiếng Serbia | sr |
| Tiếng Sindh | sd | Tiếng Sinhala | si |
| Tiếng Slovak | sk | Tiếng Slovenia | sl |
| Tiếng Swahili | sw | Tiếng Thuỵ Điển | sv |
| Tiếng Urdu | ur |
(Không bắt buộc) Đặt mã ngôn ngữ một cách rõ ràng
Nếu bạn không chỉ định mã ngôn ngữ trong cấu hình lời nói, mô hình sẽ tự động phát hiện ngôn ngữ trong câu lệnh văn bản của bạn.
Tuy nhiên, bạn có thể tuỳ ý đặt ngôn ngữ một cách rõ ràng (bằng cách sử dụng tham số languageCode trong cấu hình lời nói). Để làm việc này, bạn phải sử dụng một trong các mã ngôn ngữ BCP-47 được hỗ trợ sau đây:
- Tiếng Ả Rập:
ar-XA - Tiếng Bengal:
bn-IN - Tiếng Trung (Quan thoại):
cmn-CN - Tiếng Hà Lan:
nl-NL - Tiếng Anh:
en-US,en-GB,en-AU,en-IN - Tiếng Pháp:
fr-FR,fr-CA - Tiếng Đức:
de-DE - Tiếng Gujarat:
gu-IN - Tiếng Hindi:
hi-IN - Tiếng Indonesia:
id-ID - Tiếng Ý:
it-IT - Tiếng Nhật:
ja-JP - Tiếng Kannada:
kn-IN - Tiếng Hàn:
ko-KR - Tiếng Malayalam:
ml-IN - Tiếng Marathi:
mr-IN - Tiếng Ba Lan:
pl-PL - Tiếng Bồ Đào Nha:
pt-BR - Tiếng Nga:
ru-RU - Tiếng Tây Ban Nha:
es-US,es-ES - Tiếng Tamil:
ta-IN - Tiếng Telugu:
te-IN - Tiếng Thái:
th-TH - Tiếng Thổ Nhĩ Kỳ:
tr-TR - Tiếng Việt:
vi-VN
Bạn có thể làm gì nữa?
- Tìm hiểu cách đếm mã thông báo trước khi gửi câu lệnh dài đến mô hình.
-
Bắt đầu nghĩ đến việc chuẩn bị phát hành công khai (xem danh sách kiểm tra phát hành công khai):
- Thực thi Firebase App Check càng sớm càng tốt để giúp bảo vệ Gemini API khỏi hành vi sai trái của các ứng dụng khách trái phép.
- Sử dụng Firebase Remote Config hoặc mẫu câu lệnh phía máy chủ để có thể thay đổi cấu hình theo yêu cầu cho tính năng AI của bạn (chẳng hạn như tên mô hình) mà không cần phát hành phiên bản mới của ứng dụng.
Thử các chức năng khác
- Xây dựng cuộc trò chuyện nhiều lượt (trò chuyện).
- Tạo văn bản do AI tạo từ câu lệnh chỉ có văn bản.
- Tạo kết quả có cấu trúc (như JSON) từ cả câu lệnh dạng văn bản và đa phương thức.
- Tạo và chỉnh sửa hình ảnh bằng cả câu lệnh dạng văn bản và câu lệnh đa phương thức.
- Truyền dữ liệu đầu vào và đầu ra (bao gồm cả âm thanh) bằng Gemini Live API.
-
Sử dụng các công cụ (như gọi hàm và Grounding bằng
Google Search hoặcGoogle Maps ) để kết nối mô hình Gemini với các phần khác của ứng dụng cũng như các hệ thống và thông tin bên ngoài.
Tìm hiểu cách kiểm soát việc tạo nội dung
- Tìm hiểu về thiết kế câu lệnh, bao gồm cả các phương pháp hay nhất, chiến lược và câu lệnh mẫu.
- Định cấu hình các tham số của mô hình như số lượng mã thông báo đầu ra tối đa, xác suất mã thông báo đầu ra lặp lại, v.v.
- Sử dụng chế độ cài đặt an toàn để điều chỉnh khả năng nhận được câu trả lời có thể bị coi là gây hại.
Tìm hiểu thêm về các mô hình được hỗ trợ
Tìm hiểu về các mô hình có sẵn cho nhiều trường hợp sử dụng cũng như hạn mức và giá của các mô hình đó.Gửi ý kiến phản hồi về trải nghiệm của bạn với Firebase AI Logic