Để truy cập vào các mô hình Gemini Pro và Flash, nhà phát triển Android nên sử dụng Gemini Developer API thông qua Logic AI của Firebase. Dịch vụ này cho phép bạn bắt đầu sử dụng mà không cần thẻ tín dụng và cung cấp một cấp miễn phí hào phóng. Sau khi xác thực việc tích hợp với một cơ sở người dùng nhỏ, bạn có thể mở rộng quy mô bằng cách chuyển sang cấp có tính phí.
Bắt đầu
Trước khi tương tác trực tiếp với API Gemini từ ứng dụng, trước tiên, bạn cần làm một số việc, bao gồm làm quen với lời nhắc cũng như thiết lập Firebase và ứng dụng để sử dụng SDK.
Thử nghiệm với câu lệnh
Việc thử nghiệm với câu lệnh có thể giúp bạn tìm ra cách diễn đạt, nội dung và định dạng phù hợp nhất cho ứng dụng Android. Google AI Studio là một IDE mà bạn có thể sử dụng để tạo nguyên mẫu và thiết kế câu lệnh cho các trường hợp sử dụng của ứng dụng.
Việc tạo câu lệnh phù hợp cho trường hợp sử dụng của bạn mang tính nghệ thuật hơn là khoa học, vì vậy, việc thử nghiệm là rất quan trọng. Bạn có thể tìm hiểu thêm về lời nhắc trong tài liệu về Firebase.
Khi bạn hài lòng với câu lệnh, hãy nhấp vào nút "<>" để nhận các đoạn mã mà bạn có thể thêm vào mã của mình.
Thiết lập dự án Firebase và kết nối ứng dụng với Firebase
Khi bạn đã sẵn sàng gọi API từ ứng dụng, hãy làm theo hướng dẫn trong "Bước 1" của Hướng dẫn bắt đầu sử dụng Logic AI của Firebase để thiết lập Firebase và SDK trong ứng dụng.
Thêm phần phụ thuộc Gradle
Thêm phần phụ thuộc Gradle sau vào mô-đun ứng dụng:
Kotlin
dependencies {
// ... other androidx dependencies
// Import the BoM for the Firebase platform
implementation(platform("com.google.firebase:firebase-bom:33.13.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")
}
Java
dependencies {
// Import the BoM for the Firebase platform
implementation(platform("com.google.firebase:firebase-bom:33.13.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")
// Required for one-shot operations (to use `ListenableFuture` from Guava
// Android)
implementation("com.google.guava:guava:31.0.1-android")
// Required for streaming operations (to use `Publisher` from Reactive
// Streams)
implementation("org.reactivestreams:reactive-streams:1.0.4")
}
Khởi chạy mô hình tạo sinh
Bắt đầu bằng cách tạo bản sao GenerativeModel
và chỉ định tên mô hình:
Kotlin
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
.generativeModel("gemini-2.0-flash")
Java
GenerativeModel firebaseAI = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.generativeModel("gemini-2.0-flash");
GenerativeModelFutures model = GenerativeModelFutures.from(firebaseAI);
Tìm hiểu thêm về các mô hình hiện có để sử dụng với API Developer Gemini. Bạn cũng có thể tìm hiểu thêm về cách định cấu hình các tham số mô hình.
Tương tác với API dành cho nhà phát triển Gemini từ ứng dụng của bạn
Giờ đây, khi đã thiết lập Firebase và ứng dụng để sử dụng SDK, bạn đã sẵn sàng tương tác với API dành cho nhà phát triển Gemini từ ứng dụng của mình.
Tạo văn bản
Để tạo câu trả lời dạng văn bản, hãy gọi generateContent()
bằng câu lệnh của bạn.
Kotlin
scope.launch {
val response = model.generateContent("Write a story about a magic backpack.")
}
Java
Content prompt = new Content.Builder()
.addText("Write a story about a magic backpack.")
.build();
ListenableFuture<GenerateContentResponse> response = model.generateContent(prompt);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
String resultText = result.getText();
[...]
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}, executor);
Tạo văn bản từ hình ảnh và nội dung nghe nhìn khác
Bạn cũng có thể tạo văn bản từ một câu lệnh bao gồm văn bản cùng với hình ảnh hoặc nội dung nghe nhìn khác. Khi gọi generateContent()
, bạn có thể truyền nội dung nghe nhìn dưới dạng dữ liệu cùng dòng.
Ví dụ: để sử dụng bitmap, hãy sử dụng loại nội dung image
:
Kotlin
scope.launch {
val response = model.generateContent(
content {
image(bitmap)
text("what is the object in the picture?")
}
)
}
Java
Content content = new Content.Builder()
.addImage(bitmap)
.addText("what is the object in the picture?")
.build();
ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
String resultText = result.getText();
[...]
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}, executor);
Để truyền tệp âm thanh, hãy sử dụng loại nội dung inlineData
:
Kotlin
val contentResolver = applicationContext.contentResolver
val inputStream = contentResolver.openInputStream(audioUri).use { stream ->
stream?.let {
val bytes = stream.readBytes()
val prompt = content {
inlineData(bytes, "audio/mpeg") // Specify the appropriate audio MIME type
text("Transcribe this audio recording.")
}
val response = model.generateContent(prompt)
}
}
Java
ContentResolver resolver = getApplicationContext().getContentResolver();
try (InputStream stream = resolver.openInputStream(audioUri)) {
File audioFile = new File(new URI(audioUri.toString()));
int audioSize = (int) audioFile.length();
byte audioBytes = new byte[audioSize];
if (stream != null) {
stream.read(audioBytes, 0, audioBytes.length);
stream.close();
// Provide a prompt that includes audio specified earlier and text
Content prompt = new Content.Builder()
.addInlineData(audioBytes, "audio/mpeg") // Specify the appropriate audio MIME type
.addText("Transcribe what's said in this audio recording.")
.build();
// To generate text output, call `generateContent` with the prompt
ListenableFuture<GenerateContentResponse> response = model.generateContent(prompt);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
String text = result.getText();
Log.d(TAG, (text == null) ? "" : text);
}
@Override
public void onFailure(Throwable t) {
Log.e(TAG, "Failed to generate a response", t);
}
}, executor);
} else {
Log.e(TAG, "Error getting input stream for file.");
// Handle the error appropriately
}
} catch (IOException e) {
Log.e(TAG, "Failed to read the audio file", e);
} catch (URISyntaxException e) {
Log.e(TAG, "Invalid audio file", e);
}
Để cung cấp tệp video, hãy tiếp tục sử dụng loại nội dung inlineData
:
Kotlin
val contentResolver = applicationContext.contentResolver
contentResolver.openInputStream(videoUri).use { stream ->
stream?.let {
val bytes = stream.readBytes()
val prompt = content {
inlineData(bytes, "video/mp4") // Specify the appropriate video MIME type
text("Describe the content of this video")
}
val response = model.generateContent(prompt)
}
}
Java
ContentResolver resolver = getApplicationContext().getContentResolver();
try (InputStream stream = resolver.openInputStream(videoUri)) {
File videoFile = new File(new URI(videoUri.toString()));
int videoSize = (int) videoFile.length();
byte[] videoBytes = new byte[videoSize];
if (stream != null) {
stream.read(videoBytes, 0, videoBytes.length);
stream.close();
// Provide a prompt that includes video specified earlier and text
Content prompt = new Content.Builder()
.addInlineData(videoBytes, "video/mp4")
.addText("Describe the content of this video")
.build();
// To generate text output, call generateContent with the prompt
ListenableFuture<GenerateContentResponse> response = model.generateContent(prompt);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
String resultText = result.getText();
System.out.println(resultText);
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}, executor);
}
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
Tương tự, bạn cũng có thể truyền tài liệu PDF (application/pdf
) và văn bản thuần tuý (text/plain
) bằng cách truyền Loại MIME tương ứng dưới dạng tham số.
Cuộc trò chuyện nhiều lượt
Bạn cũng có thể hỗ trợ các cuộc trò chuyện nhiều lượt. Khởi tạo cuộc trò chuyện bằng hàm startChat()
. Bạn có thể cung cấp cho mô hình một nhật ký thông báo (không bắt buộc). Sau đó, hãy gọi hàm sendMessage()
để gửi tin nhắn trò chuyện.
Kotlin
val chat = model.startChat(
history = listOf(
content(role = "user") { text("Hello, I have 2 dogs in my house.") },
content(role = "model") { text("Great to meet you. What would you like to know?") }
)
)
scope.launch {
val response = chat.sendMessage("How many paws are in my house?")
}
Java
Content.Builder userContentBuilder = new Content.Builder();
userContentBuilder.setRole("user");
userContentBuilder.addText("Hello, I have 2 dogs in my house.");
Content userContent = userContentBuilder.build();
Content.Builder modelContentBuilder = new Content.Builder();
modelContentBuilder.setRole("model");
modelContentBuilder.addText("Great to meet you. What would you like to know?");
Content modelContent = userContentBuilder.build();
List<Content> history = Arrays.asList(userContent, modelContent);
// Initialize the chat
ChatFutures chat = model.startChat(history);
// Create a new user message
Content.Builder messageBuilder = new Content.Builder();
messageBuilder.setRole("user");
messageBuilder.addText("How many paws are in my house?");
Content message = messageBuilder.build();
// Send the message
ListenableFuture<GenerateContentResponse> response = chat.sendMessage(message);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
String resultText = result.getText();
System.out.println(resultText);
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}, executor);
Hãy xem tài liệu về Firebase để biết thêm thông tin chi tiết.
Các bước tiếp theo
- Xem lại ứng dụng mẫu Firebase trong phần Android Quickstart (Khởi động nhanh Android) và Danh mục mẫu AI cho Android trên GitHub.
- Chuẩn bị ứng dụng để phát hành công khai, bao gồm cả việc thiết lập tính năng Kiểm tra ứng dụng Firebase để bảo vệ Gemini API khỏi hành vi sử dụng sai cách của các ứng dụng không được uỷ quyền.
- Tìm hiểu thêm về Logic AI của Firebase trong tài liệu về Firebase.