為什麼要改用 Firebase AI Logic SDK?
您可能已試用過另一組行動或網頁用戶端 SDK,可讓您存取 Gemini Developer API。
這些用戶端 SDK 並未整合至強大的 Firebase 生態系統,該生態系統為行動和網頁應用程式提供重要服務。這些 API 現已淘汰,建議改用 Firebase AI Logic 用戶端 SDK,以便存取 Gemini Developer API。
行動和網頁應用程式的安全防護功能
對於行動和網頁應用程式,安全性至關重要,需要特別考量,因為您的程式碼 (包括對 Gemini API 的呼叫) 是在未受保護的環境中執行。您可以使用 Firebase App Check,防止未經授權的用戶端濫用 API。
搭配使用 Firebase App Check 和 Firebase AI Logic 時,請勿將 Gemini Developer API 的 Gemini API 金鑰直接加入行動或網頁應用程式的程式碼集。Gemini API 金鑰會留在伺服器上,不會暴露給惡意行為人。
專為行動和網頁應用程式打造的生態系統
Firebase 是 Google 的行動和網頁應用程式開發平台,使用 Firebase AI Logic,代表應用程式處於專注於全端應用程式和開發人員需求的生態系統中。例如:
使用 Firebase Remote Config,動態設定執行階段設定,或替換應用程式中的值 (例如模型名稱和版本),不必發布新的應用程式版本。
使用 Cloud Storage for Firebase 在多模態要求中加入大型檔案 (如果使用 Agent Platform Gemini API (formerly Vertex AI))。Cloud Storage 用戶端 SDK 可協助您處理檔案上傳和下載作業 (即使網路狀況不佳),並為使用者資料提供更完善的安全性。如要進一步瞭解 如何使用 Cloud Storage for Firebase,請參閱解決方案指南。
使用專為行動和網頁應用程式建構的資料庫 SDK (例如 Cloud Firestore) 管理結構化資料。
遷移至 Firebase AI Logic SDK
遷移至 Firebase AI Logic SDK 的步驟總覽:
步驟 1:設定新的或現有的 Firebase 專案,並將應用程式連結至 Firebase。
步驟 2:在應用程式中加入 Firebase AI Logic SDK。
步驟 3:更新應用程式中的匯入和初始化作業。
步驟 4:根據使用的功能更新程式碼。
步驟 1:設定 Firebase 專案並連結應用程式
登入 Firebase 控制台,然後選取 Firebase 專案。
在 Firebase 控制台,依序前往「AI Services」(AI 服務) > 「AI Logic」。
按一下「Get started」(開始使用),啟動引導式工作流程,協助您設定專案所需的 API 和資源。
選取 Gemini Developer API。之後隨時可以視需要設定及使用其他 API 供應商。
控制台會啟用必要的 API,並在專案中建立新的專屬 Gemini API 金鑰。
請勿將這個新的 Gemini API 金鑰加入應用程式的程式碼集。 瞭解詳情。如果控制台的工作流程中出現提示,請按照畫面上的指示註冊應用程式,並連結至 Firebase。
請繼續參閱本遷移指南,更新應用程式中的程式庫和初始化。
步驟 2:在應用程式中加入 Firebase AI Logic SDK
設定 Firebase 專案並將應用程式連結至 Firebase 後 (請參閱上一步),即可在應用程式中加入 Firebase AI Logic SDK。
Swift
使用 Swift Package Manager 安裝及管理 Firebase 依附元件。如有需要,請參閱其他安裝選項。
Firebase AI Logic 程式庫提供 API 存取權,可與 Gemini 模型互動。這個程式庫包含在 Apple 平台專用 Firebase SDK (firebase-ios-sdk) 中。
如果您已使用 Firebase,請確認 Firebase 套件為 12.5.0 以上版本。
在 Xcode 中保持開啟應用程式專案,然後依序點選「File」(檔案) 和「Add Package Dependencies」(新增套件依附元件)。
系統提示時,請新增 Firebase Apple 平台 SDK 存放區:
https://github.com/firebase/firebase-ios-sdk選取最新版 SDK。
選取
FirebaseAILogic程式庫和FirebaseAppCheck程式庫。
完成後,Xcode 就會自動開始在背景中解析並下載依附元件。
Kotlin
Firebase AI Logic Android SDK (firebase-ai) 提供 API 存取權,可與 Gemini 模型互動。
在模組 (應用程式層級) Gradle 檔案 (例如 <project>/<app-module>/build.gradle.kts) 中,新增 Android Firebase AI Logic 和 App Check 程式庫的依附元件。建議使用 Firebase Android BoM 控制程式庫版本。
dependencies { // ... other androidx dependencies // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:35.2.0")) // Add the dependencies for the Firebase AI Logic and App Check libraries // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-ai") implementation("com.google.firebase:firebase-appcheck-debug") }
只要使用 Firebase Android BoM,應用程式就會一律使用相容的 Firebase Android 程式庫版本。
Java
Firebase AI Logic Android SDK (firebase-ai) 提供 API 存取權,可與 Gemini 模型互動。
在模組 (應用程式層級) Gradle 檔案 (例如 <project>/<app-module>/build.gradle.kts) 中,新增 Android 適用的 Firebase AI Logic 和 App Check 程式庫依附元件。建議使用 Firebase Android BoM 控制程式庫版本。
如果是 Java,則需要額外新增兩個程式庫。
dependencies { // ... other androidx dependencies // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:35.2.0")) // Add the dependencies for the Firebase AI Logic and App Check libraries // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-ai") implementation("com.google.firebase:firebase-appcheck-debug") // 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") }
只要使用 Firebase Android BoM,應用程式就會一律使用相容的 Firebase Android 程式庫版本。
Web
Firebase AI Logic 程式庫提供 API 存取權,可與 Gemini 模型互動。這個程式庫包含在 Firebase JavaScript SDK for Web 中。
使用 npm 安裝 Firebase JS SDK for Web:
npm install firebase在應用程式中初始化 Firebase:
import { initializeApp } from "firebase/app"; import { initializeAppCheck, DebugProvider } from "firebase/app-check"; // TODO(developer) Replace the following with your app's Firebase configuration // See: https://firebase.google.com/docs/web/learn-more#config-object const firebaseConfig = { // ... }; // Initialize FirebaseApp const firebaseApp = initializeApp(firebaseConfig);
Dart
Flutter 的 Firebase AI Logic 外掛程式 (firebase_ai) 可讓您存取 API,與 Gemini 模型互動。
在 Flutter 專案目錄中,執行下列指令來安裝 Firebase AI Logic 和 App Check 外掛程式:
flutter pub add firebase_ai firebase_app_check在
lib/main.dart檔案中,匯入 Firebase AI Logic 和 App Check 外掛程式:import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_ai/firebase_ai.dart'; import 'package:firebase_app_check/firebase_app_check.dart'; import 'firebase_options.dart';此外,請確認您已在
lib/main.dart檔案中,使用設定檔匯出的DefaultFirebaseOptions物件初始化 Firebase:await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, );重建 Flutter 應用程式:
flutter run
Unity
Google AI 用戶端 SDK 不支援 Unity。
從應用程式中移除舊版 SDK
完成應用程式遷移後 (請參閱本指南的其餘部分),請務必刪除舊程式庫。
Swift
移除舊程式庫:
在 Xcode 中開啟應用程式專案,然後前往「Packages Dependencies」窗格。
從套件依附元件清單中選取
generative-ai-swift套件。按一下清單底部的
-按鈕,然後按一下「Remove」(移除) 確認操作。
Kotlin
dependencies {
implementation("com.google.ai.client.generativeai:generativeai:VERSION")
}
Java
dependencies {
implementation("com.google.ai.client.generativeai:generativeai:VERSION")
}
Web
// BEFORE
import { initializeApp } from "firebase/app";
import { GoogleGenerativeAI } from "@google/generative-ai";
Dart
刪除舊套件:
flutter pub remove google_generative_ai
Unity
Google AI 用戶端 SDK 不支援 Unity。
步驟 3:更新應用程式中的匯入和初始化作業
更新匯入項目、Gemini Developer API 後端服務的初始化方式,以及 GenerativeModel 執行個體的建立方式。
Swift
// BEFOREimport GoogleGenerativeAI let model = GenerativeModel(name: "MODEL_NAME", apiKey: APIKey.default)// AFTER import FirebaseAILogic // Initialize the Gemini Developer API backend service let ai = FirebaseAI.firebaseAI(backend: .googleAI()) // Create a `GenerativeModel` instance with a model that supports your use case let model = ai.generativeModel(modelName: "gemini-4-hydrogen")
Kotlin
// BEFOREimport com.google.ai.client.generativeai.Chat import com.google.ai.client.generativeai.type.Content import com.google.ai.client.generativeai.java.GenerativeModuleFutures...val generativeModel = GenerativeModel(modelName = "MODEL_NAME", // Access your API key as a Build Configuration variable apiKey = BuildConfig.apiKey )// AFTER import com.google.firebase.Firebase import com.google.firebase.ai.ai import com.google.firebase.ai.type.GenerativeBackend ... // Initialize the Gemini Developer API backend service. // Create a `GenerativeModel` instance with a model that supports your use case. val model = Firebase.ai(backend = GenerativeBackend.googleAI()) .generativeModel("gemini-4-hydrogen")
Java
// BEFOREimport com.google.ai.client.generativeai.Chat; import com.google.ai.client.generativeai.type.Content; import com.google.ai.client.generativeai.java.GenerativeModuleFutures;...GenerativeModel gm = new GenerativeModel("MODEL_NAME", // Access your API key as a Build Configuration variable BuildConfig.apiKey ); GenerativeModelFutures model = GenerativeModelFutures.from(gm);// AFTER import com.google.firebase.ai.FirebaseAI; import com.google.firebase.ai.GenerativeModel; import com.google.firebase.ai.java.GenerativeModelFutures; import com.google.firebase.ai.type.GenerativeBackend; ... // Initialize the Gemini Developer API backend service. // Create a `GenerativeModel` instance with a model that supports your use case. GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI()) .generativeModel("gemini-4-hydrogen"); // Use the GenerativeModelFutures Java compatibility layer which offers // support for ListenableFuture and Publisher APIs GenerativeModelFutures model = GenerativeModelFutures.from(ai);
Web
// BEFOREimport { GoogleGenerativeAI } from "@google/generative-ai"; // Fetch your API_KEY and access your API const API_KEY = "..."; const genAI = new GoogleGenerativeAI(API_KEY);...const model = genAI.getGenerativeModel({ model: "MODEL_NAME"});// AFTER import { initializeApp } from "firebase/app"; import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai"; // TODO(developer): Replace the following with your app's Firebase configuration // See: https://firebase.google.com/docs/web/learn-more#config-object const firebaseConfig = { // ... }; // Initialize FirebaseApp const firebaseApp = initializeApp(firebaseConfig); // Initialize the Gemini Developer API backend service. const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() }); // Create a `GenerativeModel` instance with a model that supports your use case. const model = getGenerativeModel(ai, { model: "gemini-4-hydrogen" });
Dart
// BEFOREimport 'package:google_generative_ai/google_generative_ai.dart'; final apiKey = Platform.environment['API_KEY']; if (apiKey == null) { print('No \$API_KEY environment variable'); exit(1); } final model = GenerativeModel(model: 'MODEL_NAME', apiKey: apiKey);// AFTER import 'package:firebase_ai/firebase_ai.dart'; import 'package:firebase_core/firebase_core.dart'; import 'firebase_options.dart'; // Initialize FirebaseApp await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); // Initialize the Gemini Developer API backend service // Create a `GenerativeModel` instance with a model that supports your use case final model = FirebaseAI.googleAI().generativeModel(model: 'gemini-4-hydrogen');
Unity
Google AI 用戶端 SDK 不支援 Unity。
請注意,視您使用的功能而定,您不一定會建立 GenerativeModel 執行個體。如要使用 Gemini Live API 串流輸入和輸出內容,請建立 LiveModel 執行個體。
步驟 4:根據使用的功能更新程式碼
本步驟說明可能需要進行的變更,具體取決於您使用的功能。
Firebase AI Logic 用戶端 SDK 不支援執行程式碼。如果您使用這項功能,請務必在應用程式中進行調整。
請查看下列清單,瞭解在遷移至 Firebase AI Logic 用戶端 SDK 時,可能需要對程式碼進行哪些變更。
所有語言和平台都必須提供
呼叫函式
如果您已實作這項功能,則必須更新結構定義的定義方式。建議您參閱更新後的函式呼叫指南,瞭解如何編寫函式宣告。使用
responseSchema生成結構化輸出內容 (例如 JSON)
如果您已導入這項功能,則需要更新結構定義的定義方式。建議您參閱新的結構化輸出內容指南,瞭解如何編寫 JSON 結構定義。逾時
- 將要求的預設逾時時間變更為 180 秒。
視平台或語言而定
Swift
列舉
將大部分
enum類型替換為具有靜態變數的struct。這項變更可讓 API 以回溯相容的方式更靈活地演進。使用switch陳述式時,現在必須加入default:案例,涵蓋未知或未處理的值,包括日後新增至 SDK 的新值。將
BlockThreshold列舉重新命名為HarmBlockThreshold;這個類型現在是struct。從下列列舉 (現為
struct) 中移除unknown和unspecified案例:HarmCategory、HarmBlockThreshold、HarmProbability、BlockReason和FinishReason。將列舉
ModelContent.Part替換為名為Part的通訊協定,以便以回溯相容的方式新增類型。如要進一步瞭解這項異動,請參閱「內容部分」一節。
內容部分
移除
ThrowingPartsRepresentable通訊協定,並簡化ModelContent的初始化工具,避免偶爾發生編譯器錯誤。如果圖片未正確編碼,在generateContent中使用時仍會擲回錯誤。將
ModelContent.Part案例替換為符合Part通訊協定的下列struct類型:.text至TextPart.data至InlineDataPart.fileData至FileDataPart.functionCall至FunctionCallPart.functionResponse至FunctionResponsePart
危害類別
- 已將
HarmCategory變更為不再以巢狀結構嵌入SafetySetting類型。如果您將其稱為SafetySetting.HarmCategory,則可以替換為HarmCategory。
- 已將
安全相關意見回饋
- 已移除
SafetyFeedback類型,因為任何回應中都沒有使用該類型。
- 已移除
引用中繼資料
- 在
CitationMetadata中,將citationSources屬性重新命名為citations。
- 在
計費字元總數
- 將
CountTokensResponse中的totalBillableCharacters屬性變更為選用,以反映未傳送任何字元的情況。
- 將
候選回覆
- 將
CandidateResponse重新命名為Candidate,以便與其他平台保持一致。
- 將
生成設定
- 將
GenerationConfig的公開屬性變更為internal。這些設定都可以在初始化器中調整。
- 將
Kotlin
列舉
將
enum類別和sealed類別替換為一般類別。這項變更可讓您以回溯相容的方式,更靈活地發展 API。將
BlockThreshold列舉重新命名為HarmBlockThreshold。從下列列舉中移除值:
HarmBlockThreshold、HarmProbability、HarmSeverity、BlockReason和FinishReason。
Blob 方法
- 重新命名名稱中包含
Blob的所有方法,改用InlineData。
- 重新命名名稱中包含
安全性設定
- 將
method欄位變更為可為空值。
- 將
Duration 類別
- 移除 Kotlin
Duration類別的所有用途,並改用long。這項變更可提升與 Java 的互通性。
- 移除 Kotlin
引用中繼資料
- 將先前在
CitationMetadata中宣告的所有欄位包裝到名為Citation的新類別中。您可以在CitationMetadata的citations清單中找到引用內容。這項變更可讓各平台的類型更一致。
- 將先前在
計算詞元數
- 將
totalBillableCharacters欄位變更為可為空值。
- 將
計費字元總數
- 將
CountTokensResponse中的totalBillableCharacters屬性變更為選用,以反映未傳送任何字元的情況。
- 將
例項化模型
- 將
requestOptions參數移至參數清單結尾,以便與其他平台保持一致。
- 將
Java
列舉
將
enum類別和sealed類別替換為一般類別。這項變更可讓您以回溯相容的方式,更靈活地發展 API。將
BlockThreshold列舉重新命名為HarmBlockThreshold。從下列列舉中移除值:
HarmBlockThreshold、HarmProbability、HarmSeverity、BlockReason和FinishReason。
Blob 方法
- 重新命名名稱中包含
Blob的所有方法,改用InlineData。
- 重新命名名稱中包含
安全性設定
- 將
method欄位變更為可為空值。
- 將
Duration 類別
- 移除 Kotlin
Duration類別的所有用途,並改用long。這項變更可提升與 Java 的互通性。
- 移除 Kotlin
引用中繼資料
- 將先前在
CitationMetadata中宣告的所有欄位包裝到名為Citation的新類別中。您可以在CitationMetadata的citations清單中找到引用內容。這項變更可讓各平台的類型更一致。
- 將先前在
計算詞元數
- 將
totalBillableCharacters欄位變更為可為空值。
- 將
計費字元總數
- 將
CountTokensResponse中的totalBillableCharacters屬性變更為選用,以反映未傳送任何字元的情況。
- 將
例項化模型
- 將
requestOptions參數移至參數清單結尾,以便與其他平台保持一致。
- 將
Web
請注意,自 Firebase AI Logic 用戶端 SDK 從 Google AI JavaScript 用戶端 SDK 分支以來,後者已歷經多次變更。以下列出遷移至 Firebase AI Logic 用戶端 SDK 時,可能需要考量的幾項變更。
列舉
- 已從下列列舉中移除值:
HarmCategory、BlockThreshold、HarmProbability、HarmSeverity、BlockReason和FinishReason。
- 已從下列列舉中移除值:
封鎖原因
- 將
PromptFeedback中的blockReason變更為選用。
- 將
搜尋建立基準
- Firebase AI Logic SDK 尚未支援這項功能,因此已移除所有相關用途。
錯誤
- 移除
GoogleGenerativeAIError的所有用法,並視需要改用AIError。
- 移除
Dart
列舉
- 從下列列舉中移除值:
HarmCategory、HarmProbability、BlockReason和FinishReason。
- 從下列列舉中移除值:
資料部分
- 將
DataPart重新命名為InlineDataPart,並將staticdata函式重新命名為inlineData,以便與其他平台保持一致。
- 將
要求選項
- 由於
timeout無法運作,因此已移除RequestOptions。我們會在不久後重新加入,但會移至GenerativeModel類型,以便與其他平台保持一致。
- 由於
停止序列
- 將
GenerationConfig中的stopSequences參數變更為選用,並預設為null,而非空陣列。
- 將
引用資料
- 在
CitationMetadata中,將citationSources屬性重新命名為citations。CitationSource類型已重新命名為Citation,以便與其他平台保持一致。
- 在
不必要的公開類型、方法和屬性
- 移除下列意外公開的類型、方法和屬性:
defaultTimeout、CountTokensResponseFields、parseCountTokensResponse、parseEmbedContentResponse、parseGenerateContentResponse、parseContent、BatchEmbedContentsResponse、ContentEmbedding、EmbedContentRequest和EmbedContentResponse。
- 移除下列意外公開的類型、方法和屬性:
計算詞元數
- 從
countTokens函式中移除不再需要的額外欄位。只需contents。
- 從
例項化模型
- 將
systemInstruction參數移至參數清單結尾,以便與其他平台保持一致。
- 將
嵌入功能
- 從模型中移除不支援的嵌入功能 (
embedContent和batchEmbedContents)。
- 從模型中移除不支援的嵌入功能 (
Unity
Google AI 用戶端 SDK 不支援 Unity。
提供 Firebase AI Logic 使用體驗的意見回饋