如果您是 Gemini API 的新手,建議 Android 開發人員使用 Gemini Developer API 做為 API 供應商。不過,如果您有特定的資料位置需求,或是已嵌入 Vertex AI 或 Google Cloud 環境,則可以使用 Vertex AI Gemini API。
從 Vertex AI in Firebase 遷移
如果您一開始是使用 Firebase 中的 Vertex AI 整合 Gemini Flash 和 Pro 模型,可以將 Vertex AI 遷移為 API 供應工具,並繼續使用該工具。如需詳細的遷移指南,請參閱 Firebase 說明文件。
開始使用
在直接從應用程式與 Vertex AI Gemini API 互動前,您可以先在 Vertex AI Studio 中試驗提示。
設定 Firebase 專案,並將應用程式連結至 Firebase
準備好從應用程式呼叫 Vertex AI Gemini API 後,請按照「步驟 1」Firebase AI 邏輯入門指南中的操作說明,在應用程式中設定 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);
您可以在 Firebase 說明文件中進一步瞭解可用於 Gemini Developer API 的可用模型。您也可以瞭解如何設定模型參數。
產生文字
如要產生文字回應,請使用提示呼叫 generateContent()
。
Kotlin
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 說明文件。