為什麼要遷移至 Firebase AI Logic SDK?
您可能試過其他行動或網頁用戶端 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 金鑰直接加入行動或網頁應用程式的程式碼集。API 金鑰會留在伺服器上,不會暴露給不肖分子。Gemini
專為行動和網頁應用程式打造的生態系統
Firebase 是 Google 的行動和網頁應用程式開發平台,使用 Firebase AI Logic表示您的應用程式位於以全端應用程式和開發人員需求為主的生態系統中。例如:
使用 Firebase Remote Config 動態設定執行階段設定,或在應用程式中替換值 (例如模型名稱和版本),不必發布新版應用程式。
使用 Cloud Storage for Firebase 在多模態要求中加入大型檔案 (如果您使用 Vertex AI Gemini API)。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 控制台的「Firebase AI Logic」頁面。
按一下「開始使用」,即可啟動導覽工作流程,協助您為專案設定必要 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 和 Imagen 模型互動。這個程式庫已納入 Firebase Apple 平台 SDK (firebase-ios-sdk
)。
如果您已使用 Firebase,請確認 Firebase 套件為 11.13.0 以上版本。
在 Xcode 中保持開啟應用程式專案,然後依序點選「File」(檔案) 和「Add Package Dependencies」(新增 Package 依附元件)。
系統提示時,請新增 Firebase Apple 平台 SDK 存放區:
https://github.com/firebase/firebase-ios-sdk
選取最新版 SDK。
選取
FirebaseAI
程式庫。
完成後,Xcode 會自動開始在背景中解析並下載依附元件。
Kotlin
Firebase AI Logic Android 適用的 SDK (firebase-ai
) 提供 API 存取權,可與 Gemini 和 Imagen 模型互動。
在模組 (應用程式層級) Gradle 檔案 (例如 <project>/<app-module>/build.gradle.kts
) 中,加入 Android 適用的 Firebase AI Logic 程式庫依附元件。建議使用 Firebase Android BoM 控制程式庫版本。
dependencies { // ... other androidx dependencies // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:33.15.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") }
使用 Firebase Android BoM,應用程式就會一律使用相容的 Firebase Android 程式庫版本。
Java
Firebase AI Logic Android 適用的 SDK (firebase-ai
) 提供 API 存取權,可與 Gemini 和 Imagen 模型互動。
在模組 (應用程式層級) Gradle 檔案 (例如 <project>/<app-module>/build.gradle.kts
) 中,加入 Android 適用的 Firebase AI Logic 程式庫依附元件。建議使用 Firebase Android BoM 控制程式庫版本。
如果是 Java,則需要新增兩個額外程式庫。
dependencies { // ... other androidx dependencies // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:33.15.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") }
使用 Firebase Android BoM,應用程式就會一律使用相容的 Firebase Android 程式庫版本。
Web
Firebase AI Logic 程式庫提供 API,可與 Gemini 和 Imagen 模型互動。這個程式庫是 Firebase JavaScript SDK for Web 的一部分。
使用 npm 安裝適用於網頁的 Firebase JS SDK:
npm install firebase
在應用程式中初始化 Firebase:
import { initializeApp } from "firebase/app"; // 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
) 可存取與 Gemini 和 Imagen 模型互動的 API。
在 Flutter 專案目錄中執行下列指令,安裝核心外掛程式和 Firebase AI Logic 外掛程式:
flutter pub add firebase_core && flutter pub add firebase_ai
在
lib/main.dart
檔案中,匯入 Firebase 核心外掛程式、Firebase AI Logic 外掛程式,以及您先前產生的設定檔:import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_ai/firebase_ai.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
套件。按一下清單底部的
-
按鈕,然後按一下「移除」確認操作。
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 FirebaseAI // 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-2.5-flash")
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-2.5-flash")
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-2.5-flash"); // 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-2.5-flash" });
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-2.5-flash');
Unity
Google AI 用戶端 SDK 不支援 Unity。
請注意,視您使用的功能而定,您可能不一定會建立 GenerativeModel
執行個體。
- 如要存取 Imagen 模型,請建立
ImagenModel
執行個體。
步驟 4:根據使用的功能更新程式碼
本步驟說明您可能需要進行的變更,視您使用的功能而定。
Firebase AI Logic 用戶端 SDK 不支援執行程式碼。如果使用這項功能,請務必在應用程式中配合調整。
請查看下列清單,瞭解程式碼中可能需要進行哪些變更,才能遷移至 Firebase AI Logic 用戶端 SDK。
所有語言和平台都必須提供
函式呼叫
如果您已實作這項功能,則需要更新定義結構定義的方式。建議您詳閱更新後的函式呼叫指南,瞭解如何編寫函式宣告。使用
responseSchema
生成結構化輸出內容 (例如 JSON) 如果您已實作這項功能,則需要更新結構定義方式。建議您參閱新的結構化輸出指南,瞭解如何編寫 JSON 結構定義。逾時
- 將要求的預設逾時時間變更為 180 秒。
視平台或語言而定
Swift
列舉
將大部分
enum
型別換成具有靜態變數的struct
。這項變更可讓您更靈活地以回溯相容的方式演進 API。使用switch
陳述式時,現在必須加入default:
情況,涵蓋不明或未處理的值,包括日後新增至 SDK 的值。已將
BlockThreshold
列舉重新命名為HarmBlockThreshold
,這個型別現在是struct
。從下列列舉中移除
unknown
和unspecified
案例 (現在為struct
):HarmCategory
、HarmBlockThreshold
、HarmProbability
、BlockReason
和FinishReason
。將列舉
ModelContent.Part
替換為名為Part
的通訊協定,以便以回溯相容的方式新增類型。如要瞭解這項異動的詳細資訊,請參閱「內容部分」一節。
內容部分
已移除
ThrowingPartsRepresentable
協定,並簡化ModelContent
的初始值,避免偶爾發生編譯器錯誤。如果圖片編碼不正確,在generateContent
中使用時仍會擲回錯誤。已將
ModelContent.Part
案例替換為以下struct
型別, 並符合Part
通訊協定:.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 從 JavaScript 適用的 Google AI 用戶端 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
,並將static
data
函式重新命名為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 的使用體驗意見回饋