为何要迁移以使用 Firebase AI Logic SDK?
您可能尝试过一组替代的移动或 Web 客户端 SDK,这些 SDK 可让您访问 Gemini Developer API。
这些客户端 SDK 未集成到强大的 Firebase 生态系统中,而该生态系统可为移动应用和 Web 应用提供关键服务。现在,这些 SDK 已被弃用,取而代之的是 Firebase AI Logic 客户端 SDK,您可以通过这些 SDK 访问 Gemini Developer API。
移动应用和 Web 应用的安全功能
对于移动应用和 Web 应用,安全性至关重要,需要特别考虑,因为您的代码(包括对 Gemini API 的调用)是在不受保护的环境中运行的。您可以使用 Firebase App Check 来保护 API 免遭未经授权的客户端滥用。
当您将 Firebase App Check 与 Firebase AI Logic 搭配使用时,绝不会将 Gemini Developer API 的 Gemini API 密钥直接添加到移动应用或 Web 应用的代码库中。相反,Gemini API 密钥会保留在服务器上,不会暴露给恶意方。
专为移动应用和 Web 应用打造的生态系统
Firebase 是 Google 的移动和 Web 应用开发平台。使用 Firebase AI Logic 意味着您的应用处于一个专注于满足全栈应用和开发者需求的生态系统中。例如:
使用 Firebase Remote Config 动态设置运行时配置或替换应用中的值(例如模型名称和版本),而无需发布新应用版本。
使用 Cloud Storage for Firebase 可在多模态请求中包含大型文件(如果您使用 Vertex AI Gemini API)。Cloud Storage 客户端 SDK 可帮助您处理文件上传和下载(即使在网络状况不佳的情况下),并为最终用户的数据提供更高的安全性。如需了解详情,请参阅我们的有关使用 Cloud Storage for Firebase 的解决方案指南。
使用专为移动应用和 Web 应用构建的数据库 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 SDK for Apple 平台 (firebase-ios-sdk
) 中。
如果您已在使用 Firebase,请确保您的 Firebase 软件包是 v11.13.0 或更高版本。
在 Xcode 中打开您的应用项目,然后依次点击 File(文件)> Add Package Dependencies(添加软件包依赖项)。
出现提示时,添加 Firebase Apple 平台 SDK 代码库:
https://github.com/firebase/firebase-ios-sdk
选择最新的 SDK 版本。
选择
FirebaseAI
库。
完成之后,Xcode 将会自动开始在后台解析和下载您的依赖项。
Kotlin
Firebase AI Logic Android 版 SDK (firebase-ai
) 提供用于与 Gemini 和 Imagen 模型互动的 API。
在您的模块(应用级)Gradle 文件(例如 <project>/<app-module>/build.gradle.kts
)中,添加 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
) 提供用于与 Gemini 和 Imagen 模型互动的 API。
在您的模块(应用级)Gradle 文件(例如 <project>/<app-module>/build.gradle.kts
)中,添加 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 安装适用于 Web 的 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
) 提供对 API 的访问权限,以便与 Gemini 和 Imagen 模型进行交互。
在您的 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:
case 来涵盖未知或未处理的值,包括未来添加到 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
字段更改为可以为空。
- 将
时长类
- 移除了 Kotlin 的
Duration
类的所有用法,并将其替换为long
。此变更可提供更好的 Java 互操作性。
- 移除了 Kotlin 的
引用元数据
- 将之前在
CitationMetadata
中声明的所有字段封装到一个名为Citation
的新类中。您可以在CitationMetadata
中名为citations
的列表中找到引用。此变更可更好地统一各个平台上的类型。
- 将之前在
统计 token 数量
- 将
totalBillableCharacters
字段更改为可以为空。
- 将
应计费的字符总数
- 将
CountTokensResponse
中的totalBillableCharacters
属性更改为可选,以反映未发送任何字符的情况。
- 将
实例化模型
- 将
requestOptions
参数移至参数列表末尾,以便与其他平台保持一致。
- 将
Java
枚举
将
enum
类和sealed
类替换为常规类。此项更改可让 API 以向后兼容的方式发展,从而提高灵活性。已将
BlockThreshold
枚举重命名为HarmBlockThreshold
。从以下枚举中移除了值:
HarmBlockThreshold
、HarmProbability
、HarmSeverity
、BlockReason
和FinishReason
。
Blob 方法
- 重命名了所有名称中包含
Blob
的方法,改为使用InlineData
。
- 重命名了所有名称中包含
安全设置
- 将
method
字段更改为可以为空。
- 将
时长类
- 移除了 Kotlin 的
Duration
类的所有用法,并将其替换为long
。此变更可提供更好的 Java 互操作性。
- 移除了 Kotlin 的
引用元数据
- 将之前在
CitationMetadata
中声明的所有字段封装到一个名为Citation
的新类中。您可以在CitationMetadata
中名为citations
的列表中找到引用。此变更可更好地统一各个平台上的类型。
- 将之前在
统计 token 数量
- 将
totalBillableCharacters
字段更改为可以为空。
- 将
应计费的字符总数
- 将
CountTokensResponse
中的totalBillableCharacters
属性更改为可选,以反映未发送任何字符的情况。
- 将
实例化模型
- 将
requestOptions
参数移至参数列表末尾,以便与其他平台保持一致。
- 将
Web
请注意,自 Firebase AI Logic 客户端 SDK 从 Google AI 客户端 SDK 分支出来以来,Google AI 客户端 SDK for JavaScript 已经历了许多变化。以下列表列出了一些潜在的更改,您在迁移到 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
,以便与其他平台保持一致。
- 将
请求选项
- 移除了
RequestOptions
,因为timeout
无法正常运行。我们会在不久的将来重新添加此功能,但会将其移至GenerativeModel
类型,以与其他平台保持一致。
- 移除了
停止序列
- 将
GenerationConfig
中的stopSequences
参数更改为可选参数,并将其默认值设为null
,而不是空数组。
- 将
引用
- 在
CitationMetadata
中,将citationSources
属性重命名为citations
。为了与其他平台保持一致,CitationSource
类型已重命名为Citation
。
- 在
不必要的公开类型、方法和属性
- 移除了以下无意中公开的类型、方法和属性:
defaultTimeout
、CountTokensResponseFields
、parseCountTokensResponse
、parseEmbedContentResponse
、parseGenerateContentResponse
、parseContent
、BatchEmbedContentsResponse
、ContentEmbedding
、EmbedContentRequest
和EmbedContentResponse
。
- 移除了以下无意中公开的类型、方法和属性:
统计 token 数量
- 从
countTokens
函数中移除了不再需要的额外字段。只需要contents
。
- 从
实例化模型
- 将
systemInstruction
参数移至参数列表末尾,以便与其他平台保持一致。
- 将
嵌入功能
- 从模型中移除了不受支持的嵌入功能(
embedContent
和batchEmbedContents
)。
- 从模型中移除了不受支持的嵌入功能(
Unity
Google AI 客户端 SDK 不支持 Unity。
就您使用 Firebase AI Logic 的体验提供反馈