从 Vertex AI in Firebase SDK 的预览版迁移到 Firebase AI Logic SDK


Firebase AI Logic 及其客户端 SDK 以前称为“Vertex AI in Firebase”。为了更好地反映我们拓展的服务和功能(例如,我们现在支持 Gemini Developer API!),我们将服务重命名并重新打包为 Firebase AI Logic

如需直接从移动应用或 Web 应用安全地访问 Google 的生成式 AI 模型,您现在可以选择“Gemini API”提供程序,即长期可用的 Vertex AI Gemini API,或现在的 Gemini Developer API。这意味着,您现在可以选择使用 Gemini Developer API,它提供免费层级,并提供合理的速率限制和配额。

迁移到 Firebase AI Logic SDK 的步骤概览

  • 第 1 步:为您的应用和用例选择最合适的“Gemini API”提供商。

  • 第 2 步:启用所需的 API。

  • 第 3 步:更新应用中使用的库。

  • 第 4 步:更新应用中的初始化。

  • 第 5 步:根据您使用的功能更新代码。

第 1 步:为您的应用选择最佳“Gemini API”提供商

在此次迁移中,您可以选择“Gemini API”提供商:

  • 旧版“Vertex AI in Firebase”SDK 只能使用 Vertex AI Gemini API

  • 借助新的 Firebase AI Logic SDK,您可以选择要直接从移动应用或 Web 应用调用哪个“Gemini API”提供程序,即 Gemini Developer APIVertex AI Gemini API

查看使用这两种 Gemini API 提供程序之间的差异,尤其是在支持的功能、价格和速率限制方面。举个例子,Gemini Developer API 不支持使用 Cloud Storage 网址提供文件,但如果您想利用其免费层级和合理配额,它可能是一个不错的选择。

第 2 步:启用所需的 API

确保您的 Firebase 项目中启用了所有所需的 API,以便使用您选择的“Gemini API”提供程序。

请注意,您可以在项目中同时启用这两个 API 提供程序。

  1. 登录 Firebase 控制台,然后选择您的 Firebase 项目。

  2. Firebase 控制台中,前往 Firebase AI Logic 页面

  3. 点击开始以启动引导式工作流,该工作流可帮助您为项目设置所需的 API 和资源。

  4. 选择要与 Firebase AI Logic SDK 搭配使用的“Gemini API”提供方。您可以随时根据需要设置和使用其他 API 提供方。

    • Gemini Developer API - 结算系统(可选)(适用于免费的 Spark 定价方案)
      控制台的工作流程将启用所需的 API,并在您的项目中创建 Gemini API 密钥。
      将此 Gemini API 密钥添加到应用的代码库中。 了解详情

    • Vertex AI Gemini API - 需要结算(需要采用随用随付 Blaze 定价方案)
      控制台的工作流程将在您的项目中启用所需的 API。

  5. 请继续阅读本迁移指南,了解如何更新应用中的库和初始化。

第 3 步:更新应用中使用的库

更新应用的代码库以使用 Firebase AI Logic 库。

Swift

  1. 在 Xcode 中,打开您的应用项目,然后使用以下任一选项将 Firebase 软件包更新到 v11.13.0 或更高版本:

    • 方法 1:更新所有软件包:依次选择 File > Packages > Update to Latest Package Versions

    • 方法 2:单独更新 Firebase:前往名为软件包依赖项的部分,找到 Firebase 软件包。右键点击 Firebase 软件包,然后选择 Update Package

  2. 确保 Firebase 软件包现在显示 v11.13.0 或更高版本。如果不符合,请验证您指定的软件包要求是否允许更新到 v11.13.0 或更高版本。

  3. 在项目编辑器中选择应用的目标,然后前往 Frameworks, Libraries, and Embedded Content(框架、库和嵌入内容)部分。

  4. 添加新库:选择 + 按钮,然后从 Firebase 软件包中添加 FirebaseAI

  5. 完成应用迁移(请参阅本指南的其余部分)后,请务必移除旧库:
    选择 FirebaseVertexAI-Preview,然后按 按钮。

Kotlin

  1. 在您的模块(应用级)Gradle 文件(通常是 <project>/<app-module>/build.gradle.kts<project>/<app-module>/build.gradle)中,将旧依赖项(如适用)替换为以下内容。

    请注意,在删除旧依赖项之前,迁移应用的代码库(请参阅本指南的其余部分)可能更容易。

    // BEFORE
    dependencies {
      implementation("com.google.firebase:firebase-vertexai:16.0.0-betaXX")
    }
    
    
    // AFTER
    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")
    }
  2. 将您的 Android 项目与 Gradle 文件同步。

请注意,如果您选择不使用 Firebase Android BoM,只需为 firebase-ai 库添加依赖项,并接受 Android Studio 建议的最新版本即可。

Java

  1. 在您的模块(应用级)Gradle 文件(通常是 <project>/<app-module>/build.gradle.kts<project>/<app-module>/build.gradle)中,将旧依赖项(如适用)替换为以下内容。

    请注意,在删除旧依赖项之前,迁移应用的代码库(请参阅本指南的其余部分)可能更容易。

    // BEFORE
    dependencies {
      implementation("com.google.firebase:firebase-vertexai:16.0.0-betaXX")
    }
    
    
    // AFTER
    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")
    }
  2. 将您的 Android 项目与 Gradle 文件同步。

请注意,如果您选择不使用 Firebase Android BoM,只需为 firebase-ai 库添加依赖项,并接受 Android Studio 建议的最新版本即可。

Web

  1. 使用 npm 获取最新版 Firebase JS SDK for Web:

    npm i firebase@latest

    yarn add firebase@latest
  2. 在导入该库的所有位置,请更新导入语句,改用 firebase/ai

    请注意,在删除旧导入内容之前,迁移应用的代码库(请参阅本指南的其余部分)可能更容易。

    // BEFORE
    import { initializeApp } from "firebase/app";
    import { getVertexAI, getGenerativeModel } from "firebase/vertexai-preview";
    
    
    // AFTER
    import { initializeApp } from "firebase/app";
    import { getAI, getGenerativeModel } from "firebase/ai";

Dart

  1. 更新为在 pubspec.yaml 文件中使用 firebase_ai 软件包,方法是在 Flutter 项目目录中运行以下命令:

    flutter pub add firebase_ai
  2. 重新构建您的 Flutter 项目:

    flutter run
  3. 完成应用迁移(请参阅本指南的其余部分)后,请务必删除旧软件包:

    flutter pub remove firebase_vertexai

Unity

Vertex AI in Firebase”不支持 Unity。

了解如何开始使用适用于 Unity 的 Firebase AI Logic SDK

第 4 步:更新应用中的初始化

点击您的 Gemini API 提供商,在本页面上查看特定于提供商的内容和代码。

更新为所选 API 提供方初始化服务并创建 GenerativeModel 实例的方式。

Swift


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


// 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


// 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


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


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

Vertex AI in Firebase”不支持 Unity。

了解如何开始使用适用于 Unity 的 Firebase AI Logic SDK

请注意,您可能并不总是需要创建 GenerativeModel 实例,具体取决于您使用的 capability

第 5 步:根据您使用的功能更新代码

此步骤介绍了您可能需要根据所使用的功能进行的更改。

  • 如果您使用的是 Cloud Storage 网址, 并且在此次迁移中改用 Gemini Developer API,则必须更新多模态请求,以将文件作为内嵌数据包含在内(或针对视频使用 YouTube 网址)。

  • 我们对“Vertex AI in Firebase”SDK 的 GA 版本进行了几项更改。若要使用 Firebase AI Logic SDK,也需要进行相同的更改。请查看以下列表,了解您可能需要在代码中进行哪些更改,以便使用 Firebase AI Logic SDK。

对于所有语言和平台都是必填字段

  • 函数调用
    如果您在 GA 之前实现了此功能,则需要更新架构定义方式。建议您查看更新后的函数调用指南,了解如何编写函数声明。

  • 使用 responseSchema 生成结构化输出(例如 JSON)
    如果您在 GA 发布之前实现了此功能,则需要更新架构定义方式。我们建议您查看新的结构化输出指南,了解如何编写 JSON 架构。

  • 超时

    • 将请求的默认超时设置更改为 180 秒。

根据平台或语言而定

Swift

  • 枚举

    • 将大多数 enum 类型替换成了包含静态变量的 struct。此更改让您能够更灵活地以向后兼容的方式改进 API。现在,使用 switch 语句时,您必须添加 default: 情况来涵盖未知或未处理的值,包括将来添加到 SDK 中的新值。

    • BlockThreshold 枚举重命名为 HarmBlockThreshold;此类型现在是 struct

    • 从以下枚举(现在是 struct)中移除了 unknownunspecified 情况:HarmCategoryHarmBlockThresholdHarmProbabilityBlockReasonFinishReason

    • 将枚举 ModelContent.Part 替换为名为 Part 的协议,以允许以向后兼容的方式添加新类型。内容部分部分对此变更进行了更详细的介绍。

  • 内容部分

    • 移除了 ThrowingPartsRepresentable 协议,并简化了 ModelContent 的初始化程序,以避免偶尔出现编译器错误。未正确编码的图片在 generateContent 中使用时仍会抛出错误。

    • ModelContent.Part 情况替换为符合 Part 协议的以下 struct 类型:

      • .textTextPart
      • .dataInlineDataPart
      • .fileDataFileDataPart
      • .functionCallFunctionCallPart
      • .functionResponseFunctionResponsePart
  • 危害类别

    • 更改了 HarmCategory,使其不再嵌套在 SafetySetting 类型中。如果您将其称为 SafetySetting.HarmCategory,则可以将其替换为 HarmCategory
  • 安全反馈

    • 移除了 SafetyFeedback 类型,因为它未在任何响应中使用。
  • 引用元数据

    • CitationMetadata 中的 citationSources 属性重命名为 citations
  • 应计费字符总数

    • CountTokensResponse 中的 totalBillableCharacters 属性更改为可选属性,以反映未发送任何字符的情况。
  • 候选回答

    • CandidateResponse 重命名为 Candidate,以与其他平台保持一致。
  • 生成配置

    • GenerationConfig 的公开属性更改为 internal。它们仍然可以在初始化程序中进行配置。

Kotlin

  • 枚举

    • enum 类和 sealed 类替换为常规类。此更改让您能够更灵活地以向后兼容的方式改进 API。

    • BlockThreshold 枚举重命名为 HarmBlockThreshold

    • 从以下枚举中移除了值:HarmBlockThresholdHarmProbabilityHarmSeverityBlockReasonFinishReason

  • Blob 方法

    • 重命名了名称中包含 Blob 的所有方法,改为使用 InlineData
  • 安全设置

    • method 字段更改为了可为空字段。
  • 时长类

    • 移除了 Kotlin 的 Duration 类的所有用法,并将其替换为 long。此变更可提高与 Java 的互操作性。
  • 引用元数据

    • 将之前在 CitationMetadata 中声明的所有字段封装到名为 Citation 的新类中。您可以在 CitationMetadata 中名为 citations 的列表中找到引文。此变更有助于更好地在各个平台上对齐类型。
  • 统计词元数

    • totalBillableCharacters 字段更改为了可为空字段。
  • 应计费字符总数

    • CountTokensResponse 中的 totalBillableCharacters 属性更改为可选属性,以反映未发送任何字符的情况。
  • 实例化模型

    • requestOptions 参数移到了参数列表的末尾,以与其他平台保持一致。
  • Live API

    • 移除了枚举类 ResponseModalityUNSPECIFIED 值。请改为使用 null

    • LiveGenerationConfig.setResponseModalities 重命名为了 LiveGenerationConfig.setResponseModality

    • 移除了 LiveContentResponse.Status 类,改为将状态字段嵌套为 LiveContentResponse 的属性。

    • 移除了 LiveContentResponse 类,改为提供了与模型响应匹配的 LiveServerMessage 子类。

    • LiveModelFutures.connect 更改为返回 ListenableFuture<LiveSessionFutures>,而不是 ListenableFuture<LiveSession>

Java

  • 枚举

    • enum 类和 sealed 类替换为常规类。此更改让您能够更灵活地以向后兼容的方式改进 API。

    • BlockThreshold 枚举重命名为 HarmBlockThreshold

    • 从以下枚举中移除了值:HarmBlockThresholdHarmProbabilityHarmSeverityBlockReasonFinishReason

  • Blob 方法

    • 重命名了名称中包含 Blob 的所有方法,改为使用 InlineData
  • 安全设置

    • method 字段更改为了可为空字段。
  • 时长类

    • 移除了 Kotlin 的 Duration 类的所有用法,并将其替换为 long。此变更可提高与 Java 的互操作性。
  • 引用元数据

    • 将之前在 CitationMetadata 中声明的所有字段封装到名为 Citation 的新类中。您可以在 CitationMetadata 中名为 citations 的列表中找到引文。此变更有助于更好地在各个平台上对齐类型。
  • 统计词元数

    • totalBillableCharacters 字段更改为了可为空字段。
  • 应计费字符总数

    • CountTokensResponse 中的 totalBillableCharacters 属性更改为可选属性,以反映未发送任何字符的情况。
  • 实例化模型

    • requestOptions 参数移到了参数列表的末尾,以与其他平台保持一致。
  • Live API

    • 移除了枚举类 ResponseModalityUNSPECIFIED 值。请改为使用 null

    • LiveGenerationConfig.setResponseModalities 重命名为了 LiveGenerationConfig.setResponseModality

    • 移除了 LiveContentResponse.Status 类,改为将状态字段嵌套为 LiveContentResponse 的属性。

    • 移除了 LiveContentResponse 类,改为提供了与模型响应匹配的 LiveServerMessage 子类。

    • LiveModelFutures.connect 更改为返回 ListenableFuture<LiveSessionFutures>,而不是 ListenableFuture<LiveSession>

  • 更改了各种 Java 构建器方法,使其现在正确返回其类的实例,而不是 void

Web

  • 枚举

    • 从以下枚举中移除了值:HarmCategoryBlockThresholdHarmProbabilityHarmSeverityBlockReasonFinishReason
  • 屏蔽原因

    • PromptFeedback 中的 blockReason 更改为可选。

仅当您开始使用 Gemini Developer API(而非 Vertex AI Gemini API)时,才需要进行更改:

  • 安全设置

    • 移除了不受支持的 SafetySetting.method 的用法。
  • 内嵌数据

    • 移除了不受支持的 InlineDataPart.videoMetadata 的用法。

Dart

  • 枚举

    • 从以下枚举中移除了值:HarmCategoryHarmProbabilityBlockReasonFinishReason
  • 数据部分

    • DataPart 重命名为 InlineDataPart,并将 static data 函数重命名为 inlineData,以便与其他平台保持一致。
  • 请求选项

    • 移除了 RequestOptions,因为 timeout 无法正常运行。我们将在不久的将来重新添加此类型,但会将其移至 GenerativeModel 类型,以与其他平台保持一致。
  • 停止序列

    • GenerationConfig 中的 stopSequences 参数更改为可选参数,并将其默认值更改为 null(而非空数组)。
  • 引用

    • CitationMetadata 中的 citationSources 属性重命名为 citationsCitationSource 类型已重命名为 Citation,以与其他平台保持一致。
  • 不必要的公共类型、方法和属性

    • 移除了以下无意中公开的类型、方法和属性:defaultTimeoutCountTokensResponseFieldsparseCountTokensResponseparseEmbedContentResponseparseGenerateContentResponseparseContentBatchEmbedContentsResponseContentEmbeddingEmbedContentRequestEmbedContentResponse
  • 统计词元数

    • countTokens 函数中移除了不再需要的额外字段。只需 contents 即可。
  • 实例化模型

    • systemInstruction 参数移到了参数列表的末尾,以与其他平台保持一致。
  • 嵌入功能

    • 从模型中移除了不受支持的嵌入功能 (embedContentbatchEmbedContents)。

Unity

Vertex AI in Firebase”不支持 Unity。

了解如何开始使用适用于 Unity 的 Firebase AI Logic SDK

与迁移相关的可能错误

在迁移到 GA 版 Firebase AI Logic 时,如果您尚未完成本迁移指南中所述的所有必要更改,可能会遇到错误。

403 错误:Requests to this API firebasevertexai.googleapis.com ... are blocked.

如果您收到内容为 Requests to this API firebasevertexai.googleapis.com ... are blocked. 的 403 错误,通常表示 Firebase 配置文件或对象中的 Firebase API 密钥的许可名单中没有您尝试使用的商品的必需 API。

请确保您的应用使用的 Firebase API 密钥包含密钥“API 限制”许可名单中的所有必需 API对于 Firebase AI Logic,您的 Firebase API 密钥的许可名单中至少需要包含 Firebase AI Logic API。当您Firebase 控制台中启用所需的 API 时,此 API 应已自动添加到您的 API 密钥的许可名单中。

您可以在 Google Cloud 控制台的 API 和服务 > 凭据面板中查看所有 API 密钥。


就您使用 Firebase AI Logic 的体验提供反馈