为何迁移到使用 Firebase AI Logic SDK?
您可能尝试过一组其他移动或 Web 客户端 SDK,这些 SDK 可让您访问 Gemini Developer API。
这些客户端 SDK 未集成到为移动应用和 Web 应用提供关键服务的强大 Firebase 生态系统中。它们现已废弃,取而代之的是 Firebase AI Logic 客户端 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 库提供了用于与 Gemini 和 Imagen 模型交互的 API。该库包含在适用于 Apple 平台的 Firebase SDK (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 SDK for Android (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.14.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 SDK for Android (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.14.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 库提供了用于与 Gemini 和 Imagen 模型交互的 API。该库包含在 Firebase JavaScript SDK for Web 中。
使用 npm 安装 Firebase JS SDK for Web:
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.0-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.0-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.0-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.0-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.0-flash');
Unity
Google AI 客户端 SDK 不支持 Unity。
请注意,您可能并不总是需要创建 GenerativeModel
实例,具体取决于您使用的 capability。
- 如需访问 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
。从以下枚举(现在是
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
的列表中找到引文。此变更有助于更好地在各个平台上对齐类型。
- 将之前在
统计词元数
- 将
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
的列表中找到引文。此变更有助于更好地在各个平台上对齐类型。
- 将之前在
统计词元数
- 将
totalBillableCharacters
字段更改为了可为空字段。
- 将
应计费字符总数
- 将
CountTokensResponse
中的totalBillableCharacters
属性更改为可选属性,以反映未发送任何字符的情况。
- 将
实例化模型
- 将
requestOptions
参数移到了参数列表的末尾,以与其他平台保持一致。
- 将
Web
请注意,自 Firebase AI Logic 客户端 SDK 从 Google AI 客户端 SDK 分支以来,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
,以便与其他平台保持一致。
- 将
请求选项
- 移除了
RequestOptions
,因为timeout
无法正常运行。我们将在不久的将来重新添加此类型,但会将其移至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 的体验提供反馈