Đối với những ứng dụng cần hỗ trợ giọng nói theo thời gian thực và có độ trễ thấp, chẳng hạn như chatbot hoặc tương tác tác nhân, Gemini Live API cung cấp một cách tối ưu hoá để truyền trực tuyến cả dữ liệu đầu vào và dữ liệu đầu ra cho mô hình Gemini. Bằng cách sử dụng Firebase AI Logic, bạn có thể gọi Gemini Live API trực tiếp từ ứng dụng Android mà không cần tích hợp phần phụ trợ. Hướng dẫn này sẽ chỉ cho bạn cách sử dụng Gemini Live API trong ứng dụng Android bằng Firebase AI Logic.
Bắt đầu
Trước khi bắt đầu, hãy đảm bảo ứng dụng của bạn nhắm đến API cấp 23 trở lên.
Nếu chưa có, hãy thiết lập một dự án Firebase và kết nối ứng dụng của bạn với Firebase. Để biết thông tin chi tiết, hãy xem tài liệu về Firebase AI Logic.
Thiết lập dự án Android
Thêm phần phụ thuộc thư viện Firebase AI Logic vào tệp ở cấp ứng dụng
build.gradle.kts hoặc build.gradle. Sử dụng BoM
trên Android cho Firebase để quản lý các phiên bản thư viện.
dependencies {
// Import the Firebase BoM
implementation(platform("com.google.firebase:firebase-bom:34.11.0"))
// Add the dependency for the Firebase AI Logic library
// When using the BoM, you don't specify versions in Firebase library dependencies
implementation("com.google.firebase:firebase-ai")
}
Sau khi thêm phần phụ thuộc, hãy đồng bộ hoá dự án Android với Gradle.
Tích hợp Firebase AI Logic và khởi chạy mô hình tạo sinh
Thêm quyền RECORD_AUDIO vào tệp AndroidManifest.xml của ứng dụng:
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Khởi chạy dịch vụ phụ trợ Gemini Developer API và truy cập vào LiveModel.
Sử dụng một mô hình hỗ trợ Live API, chẳng hạn như gemini-2.5-flash-native-audio-preview-12-2025.
Hãy xem tài liệu về Firebase để biết các mô hình hiện có.
Để chỉ định một giọng nói, hãy đặt tên giọng nói trong đối tượng
speechConfig như một phần của cấu hình mô hình. Nếu bạn không chỉ định một giọng nói, thì giá trị mặc định sẽ là Puck.
Kotlin
// Initialize the `LiveModel`
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).liveModel(
modelName = "gemini-2.5-flash-native-audio-preview-12-2025",
generationConfig = liveGenerationConfig {
responseModality = ResponseModality.AUDIO
speechConfig = SpeechConfig(voice = Voice("FENRIR"))
})
Java
// Initialize the `LiveModel`
LiveGenerativeModel model = FirebaseAI
.getInstance(GenerativeBackend.googleAI())
.liveModel(
"gemini-2.5-flash-native-audio-preview-12-2025",
new LiveGenerationConfig.Builder()
.setResponseModality(ResponseModality.AUDIO)
.setSpeechConfig(new SpeechConfig(new Voice("FENRIR"))
).build(),
null,
null
);
Bạn có thể tuỳ ý xác định một nhân vật hoặc vai trò mà mô hình đóng bằng cách đặt hướng dẫn hệ thống:
Kotlin
val systemInstruction = content {
text("You are a helpful assistant, you main role is [...]")}
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).liveModel(
modelName = "gemini-2.5-flash-native-audio-preview-12-2025",
generationConfig = liveGenerationConfig {
responseModality = ResponseModality.AUDIO
speechConfig = SpeechConfig(voice= Voice("FENRIR"))
},
systemInstruction = systemInstruction,
)
Java
Content systemInstruction = new Content.Builder()
.addText("You are a helpful assistant, you main role is [...]")
.build();
LiveGenerativeModel model = FirebaseAI
.getInstance(GenerativeBackend.googleAI())
.liveModel(
"gemini-2.5-flash-native-audio-preview-12-2025",
new LiveGenerationConfig.Builder()
.setResponseModality(ResponseModality.AUDIO)
.setSpeechConfig(new SpeechConfig(new Voice("FENRIR"))
).build(),
tools, // null if you don't want to use function calling
systemInstruction
);
Bạn có thể chuyên biệt hoá thêm cuộc trò chuyện với mô hình bằng cách sử dụng hướng dẫn hệ thống để cung cấp bối cảnh dành riêng cho ứng dụng của bạn (ví dụ: nhật ký hoạt động trong ứng dụng của người dùng).
Khởi chạy phiên Live API
Sau khi tạo thực thể LiveModel, hãy gọi model.connect() để tạo đối tượng LiveSession và thiết lập kết nối liên tục với mô hình bằng tính năng truyền trực tuyến có độ trễ thấp. LiveSession cho phép bạn tương tác với mô hình bằng cách bắt đầu và dừng phiên giọng nói, đồng thời gửi và nhận văn bản.
Sau đó, bạn có thể gọi startAudioConversation() để bắt đầu cuộc trò chuyện với mô hình:
Kotlin
val session = model.connect()
session.startAudioConversation()
Java
LiveModelFutures model = LiveModelFutures.from(liveModel);
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);
Trong cuộc trò chuyện với mô hình, hãy lưu ý rằng mô hình này không xử lý các trường hợp gián đoạn. Ngoài ra, Live API là hai chiều nên bạn sử dụng cùng một kết nối để gửi và nhận nội dung.
Bạn cũng có thể sử dụng Gemini Live API để tạo âm thanh từ nhiều phương thức nhập:
- Gửi dữ liệu đầu vào bằng văn bản.
- Gửi dữ liệu đầu vào bằng video (xem ứng dụng bắt đầu nhanh của Firebase)
Gọi hàm: kết nối Gemini Live API với ứng dụng
Để tiến thêm một bước, bạn cũng có thể cho phép mô hình tương tác trực tiếp với logic của ứng dụng bằng cách gọi hàm.
Gọi hàm (hoặc gọi công cụ) là một tính năng của các cách triển khai AI tạo sinh, cho phép mô hình gọi hàm theo sáng kiến riêng để thực hiện các hành động. Nếu hàm có dữ liệu đầu ra, mô hình sẽ thêm dữ liệu đó vào ngữ cảnh của mình và sử dụng cho các thế hệ tiếp theo.
Để triển khai tính năng gọi hàm trong ứng dụng, hãy bắt đầu bằng cách tạo đối tượng FunctionDeclaration cho mỗi hàm mà bạn muốn hiển thị cho mô hình.
Ví dụ: để hiển thị hàm addList nối một chuỗi vào danh sách chuỗi cho Gemini, hãy bắt đầu bằng cách tạo biến FunctionDeclaration có tên và nội dung mô tả ngắn bằng tiếng Anh đơn giản về hàm và tham số của hàm đó:
Kotlin
val itemList = mutableListOf<String>()
fun addList(item: String){
itemList.add(item)
}
val addListFunctionDeclaration = FunctionDeclaration(
name = "addList",
description = "Function adding an item the list",
parameters = mapOf("item" to Schema.string("A short string
describing the item to add to the list"))
)
Java
HashMap<String, Schema> addListParams = new HashMap<String, Schema>(1);
addListParams.put("item", Schema.str("A short string describing the item to add to the list"));
addListParams.put("item", Schema.str("A short string describing the item to add to the list"));
FunctionDeclaration addListFunctionDeclaration = new FunctionDeclaration(
"addList",
"Function adding an item the list",
addListParams,
Collections.emptyList()
);
Sau đó, hãy truyền FunctionDeclaration này dưới dạng Tool cho mô hình khi bạn tạo thực thể:
Kotlin
val addListTool = Tool.functionDeclarations(listOf(addListFunctionDeclaration))
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).liveModel(
modelName = "gemini-2.5-flash-native-audio-preview-12-2025",
generationConfig = liveGenerationConfig {
responseModality = ResponseModality.AUDIO
speechConfig = SpeechConfig(voice= Voice("FENRIR"))
},
systemInstruction = systemInstruction,
tools = listOf(addListTool)
)
Java
LiveGenerativeModel model = FirebaseAI.getInstance(
GenerativeBackend.googleAI()).liveModel(
"gemini-2.5-flash-native-audio-preview-12-2025",
new LiveGenerationConfig.Builder()
.setResponseModalities(ResponseModality.AUDIO)
.setSpeechConfig(new SpeechConfig(new Voice("FENRIR")))
.build(),
List.of(Tool.functionDeclarations(List.of(addListFunctionDeclaration))),
null,
systemInstruction
);
Cuối cùng, hãy triển khai hàm trình xử lý để xử lý lệnh gọi công cụ mà mô hình thực hiện và truyền lại phản hồi. Hàm trình xử lý này được cung cấp cho LiveSession khi bạn gọi startAudioConversation, lấy tham số FunctionCallPart và trả về FunctionResponsePart:
Kotlin
session.startAudioConversation(::functionCallHandler)
// ...
fun functionCallHandler(functionCall: FunctionCallPart): FunctionResponsePart {
return when (functionCall.name) {
"addList" -> {
// Extract function parameter from functionCallPart
val itemName = functionCall.args["item"]!!.jsonPrimitive.content
// Call function with parameter
addList(itemName)
// Confirm the function call to the model
val response = JsonObject(
mapOf(
"success" to JsonPrimitive(true),
"message" to JsonPrimitive("Item $itemName added to the todo list")
)
)
FunctionResponsePart(functionCall.name, response)
}
else -> {
val response = JsonObject(
mapOf(
"error" to JsonPrimitive("Unknown function: ${functionCall.name}")
)
)
FunctionResponsePart(functionCall.name, response)
}
}
}
Java
Futures.addCallback(sessionFuture, new FutureCallback<LiveSessionFutures>() {
@RequiresPermission(Manifest.permission.RECORD_AUDIO)
@Override
@OptIn(markerClass = PublicPreviewAPI.class)
public void onSuccess(LiveSessionFutures ses) {
ses.startAudioConversation(::handleFunctionCallFuture);
}
@Override
public void onFailure(Throwable t) {
// Handle exceptions
}
}, executor);
// ...
ListenableFuture<JsonObject> handleFunctionCallFuture = Futures.transform(response, result -> {
for (FunctionCallPart functionCall : result.getFunctionCalls()) {
if (functionCall.getName().equals("addList")) {
Map<String, JsonElement> args = functionCall.getArgs();
String item =
JsonElementKt.getContentOrNull(
JsonElementKt.getJsonPrimitive(
locationJsonObject.get("item")));
return addList(item);
}
}
return null;
}, Executors.newSingleThreadExecutor());
Các bước tiếp theo
- Dùng thử Gemini Live API trong ứng dụng mẫu danh mục AI trên Android.
- Đọc thêm về Gemini Live API trong tài liệu về Firebase AI Logic .
- Tìm hiểu thêm về các mô hình Gemini hiện có.
- Tìm hiểu thêm về tính năng gọi hàm.
- Khám phá các chiến lược thiết kế câu lệnh.