如果您是 Gemini API 的新手,建議 Android 開發人員使用 Gemini Developer API 做為 API 供應商。但如果您有特定的資料位置規定,或是已嵌入 Vertex AI 或 Google Cloud 環境,則可以使用 Vertex AI Gemini API。
從 Vertex AI in Firebase 遷移
如果您原本是使用 Vertex AI in Firebase 整合 Gemini Flash 和 Pro 模型,可以遷移至 Vertex AI 並繼續做為 API 提供者使用。如需詳細的遷移指南,請參閱 Firebase 說明文件。
開始使用
直接從應用程式與 Vertex AI Gemini API 互動前,您可以在 Vertex AI Studio 中試用提示。
設定 Firebase 專案,並將應用程式連結至 Firebase
準備好從應用程式呼叫 Vertex AI Gemini API 後,請按照 Firebase AI Logic 入門指南的「步驟 1」操作,在應用程式中設定 Firebase 和 SDK。
新增 Gradle 依附元件
將下列 Gradle 依附元件新增至應用程式模組:
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")
}
初始化生成式模型
首先,請例項化 GenerativeModel
並指定模型名稱:
Kotlin
val model = Firebase.ai(backend = GenerativeBackend.vertexAI())
.generativeModel("gemini-2.0-flash")
Java
GenerativeModel firebaseAI = FirebaseAI.getInstance(GenerativeBackend.vertexAI())
.generativeModel("gemini-2.0-flash");
GenerativeModelFutures model = GenerativeModelFutures.from(firebaseAI);
如要進一步瞭解可搭配 Gemini Developer API 使用的模型,請參閱 Firebase 說明文件。您也可以瞭解如何設定模型參數。
生成文字
如要生成文字回覆,請使用提示呼叫 generateContent()
。
Kotlin
// Note: generateContent() is a suspend function, which integrates well
// with existing Kotlin code.
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);
與 Gemini Developer API 類似,您也可以在文字提示中傳遞圖片、音訊、影片和檔案 (請參閱「從應用程式與 Gemini Developer API 互動」)。
如要進一步瞭解 Firebase AI Logic SDK,請參閱 Firebase 說明文件。