使用 Firebase AI Logic SDK 开始使用 Gemini API

本指南介绍了如何使用所选平台的 Firebase AI Logic 客户端 SDK 直接从应用中开始调用 Gemini API

您还可以使用本指南开始使用 Firebase AI Logic SDK 访问 Imagen 模型

前提条件

Swift

本指南假定您熟悉如何使用 Xcode 为 Apple 平台(如 iOS)开发应用。

  • 确保您的开发环境和 Apple 平台应用满足以下要求:

    • Xcode 16.2 或更高版本
    • 您的应用以 iOS 15 或更高版本或 macOS 12 或更高版本为目标平台
  • (可选)查看示例应用。

    下载快速入门应用

    您可以快速试用 SDK,查看各种使用情形的完整实现,或者在没有自己的 Apple 平台应用时使用示例应用。如需使用示例应用,您需要将其关联到 Firebase 项目

Kotlin

本指南假定您熟悉如何使用 Android Studio 为 Android 开发应用。

  • 确保您的开发环境和 Android 应用满足以下要求:

    • Android Studio(最新版本)
    • 您的应用以 API 级别 21 或更高级别为目标平台
  • (可选)查看示例应用。

    下载示例应用

    您可以快速试用该 SDK,查看各种使用情形的完整实现,或者在没有自己的 Android 应用时使用示例应用。如需使用示例应用,您需要将其关联到 Firebase 项目

Java

本指南假定您熟悉如何使用 Android Studio 为 Android 开发应用。

  • 确保您的开发环境和 Android 应用满足以下要求:

    • Android Studio(最新版本)
    • 您的应用以 API 级别 21 或更高级别为目标平台
  • (可选)查看示例应用。

    下载示例应用

    您可以快速试用该 SDK,查看各种使用情形的完整实现,或者在没有自己的 Android 应用时使用示例应用。如需使用示例应用,您需要将其关联到 Firebase 项目

Web

本指南假定您熟悉如何使用 JavaScript 开发 Web 应用。本指南与框架无关。

  • 确保您的开发环境和 Web 应用满足以下要求:

    • (可选)Node.js
    • 新式网络浏览器
  • (可选)查看示例应用。

    下载示例应用

    您可以快速试用该 SDK,查看各种用例的完整实现,或者在没有自己的 Web 应用时使用示例应用。如需使用示例应用,您需要将其关联到 Firebase 项目

Dart

本指南假定您熟悉如何使用 Flutter 开发应用。

  • 确保您的开发环境和 Flutter 应用满足以下要求:

    • Dart 3.2.0 及更高版本
  • (可选)查看示例应用。

    下载示例应用

    您可以快速试用该 SDK,查看各种使用情形的完整实现,或者在没有自己的 Flutter 应用时使用示例应用。如需使用示例应用,您需要将其关联到 Firebase 项目

Unity

本指南假定您熟悉如何使用 Unity 开发游戏。

  • 确保您的开发环境和 Unity 游戏满足以下要求:

    • Unity 编辑器 2021 LTS 或更高版本
  • (可选)查看示例应用。

    下载示例应用

    您可以快速试用 SDK,查看各种用例的完整实现,或者在没有自己的 Unity 游戏时使用示例应用。 如需使用示例应用,您需要将其连接到 Firebase 项目

第 1 步:设置 Firebase 项目并连接应用

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

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

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

  4. 选择要与 Firebase AI Logic SDK 搭配使用的“Gemini API”提供方。Gemini Developer API 建议首次使用该功能的用户选择此选项。如果您愿意,可以随时添加结算信息或设置 Vertex AI Gemini API

    • Gemini Developer API - 结算可选(可使用免费的 Spark 定价方案,日后可根据需要升级)
      控制台将在您的项目中启用必需的 API 并创建 Gemini API 密钥。
      请勿将此 Gemini API 密钥添加到应用的代码库中。 了解详情。

    • Vertex AI Gemini API - 需要结算信息(需要采用随用随付的 Blaze 定价方案)
      控制台将帮助您设置结算信息并启用项目中的必需 API。

  5. 如果控制台的工作流程中出现提示,请按照屏幕上的说明注册您的应用并将其连接到 Firebase。

  6. 继续执行本指南中的下一步,将 SDK 添加到您的应用。

第 2 步:添加 SDK

设置好 Firebase 项目并将应用与 Firebase 相关联(请参阅上一步)后,您现在可以将 Firebase AI Logic SDK 添加到应用中。

Swift

使用 Swift Package Manager 安装和管理 Firebase 依赖项。

Firebase AI Logic 库提供对 API 的访问权限,以便与 GeminiImagen 模型进行交互。该库包含在 Firebase SDK for Apple 平台 (firebase-ios-sdk) 中。

如果您已在使用 Firebase,请确保您的 Firebase 软件包是 v11.13.0 或更高版本。

  1. 在 Xcode 中打开您的应用项目,然后依次点击 File(文件)> Add Package Dependencies(添加软件包依赖项)

  2. 出现提示时,添加 Firebase Apple 平台 SDK 代码库:

    https://github.com/firebase/firebase-ios-sdk
    
  3. 选择最新的 SDK 版本。

  4. 选择 FirebaseAI 库。

完成之后,Xcode 将会自动开始在后台解析和下载您的依赖项。

Kotlin

Firebase AI Logic Android 版 SDK (firebase-ai) 提供用于与 GeminiImagen 模型互动的 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.16.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) 提供用于与 GeminiImagen 模型互动的 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.16.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 的访问权限,以便与 GeminiImagen 模型进行交互。该库包含在 Firebase JavaScript SDK for Web 中。

  1. 使用 npm 安装适用于 Web 的 Firebase JS SDK:

    npm install firebase
    
  2. 在您的应用中初始化 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 的访问权限,以便与 GeminiImagen 模型进行交互。

  1. 在您的 Flutter 项目目录中,运行以下命令以安装核心插件和 Firebase AI Logic 插件:

    flutter pub add firebase_core firebase_ai
    
  2. 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';
    
  3. 同样在 lib/main.dart 文件中,使用配置文件导出的 DefaultFirebaseOptions 对象初始化 Firebase:

    await Firebase.initializeApp(
      options: DefaultFirebaseOptions.currentPlatform,
    );
    
  4. 重新构建 Flutter 应用:

    flutter run
    

Unity

  1. 下载 Firebase Unity SDK,然后将此 SDK 提取到合适的位置。

    Firebase Unity SDK 不局限于特定平台。

  2. 在您打开的 Unity 项目中,依次转到 Assets > Import Package > Custom Package

  3. 从提取的 SDK 中,选择 FirebaseAI 软件包。

  4. 在“Import Unity Package”窗口中,点击 Import

  5. 返回 Firebase 控制台,在设置工作流中,点击下一步

第 3 步:初始化服务并创建模型实例

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

在向 Gemini 模型发送提示之前,请为所选的 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.5-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.5-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.5-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.5-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.5-flash');

Unity


using Firebase;
using Firebase.AI;

// Initialize the Gemini Developer API backend service
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());

// Create a `GenerativeModel` instance with a model that supports your use case
var model = ai.GetGenerativeModel(modelName: "gemini-2.5-flash");

请注意,根据您使用的功能,您可能并不总是需要创建 GenerativeModel 实例

此外,在完成本入门指南后,您还可以了解如何为您的应用场景和应用选择模型

第 4 步:向模型发送提示请求

您现在可以向 Gemini 模型发送提示请求了。

您可以使用 generateContent() 根据包含文本的提示生成文本:

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.5-flash")

// Provide a prompt that contains text
let prompt = "Write a story about a magic backpack."

// To generate text output, call generateContent with the text input
let response = try await model.generateContent(prompt)
print(response.text ?? "No text in response.")

Kotlin

对于 Kotlin,此 SDK 中的方法是挂起函数,需要从协程范围调用。

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

// Provide a prompt that contains text
val prompt = "Write a story about a magic backpack."

// To generate text output, call generateContent with the text input
val response = generativeModel.generateContent(prompt)
print(response.text)

Java

对于 Java,此 SDK 中的方法会返回 ListenableFuture

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

// Provide a prompt that contains text
Content prompt = new Content.Builder()
    .addText("Write a story about a magic backpack.")
    .build();

// To generate text output, call generateContent with the text input
ListenableFuture<GenerateContentResponse> response = model.generateContent(prompt);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
    @Override
    public void onSuccess(GenerateContentResponse result) {
        String resultText = result.getText();
        System.out.println(resultText);
    }

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
}, executor);

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.5-flash" });

// Wrap in an async function so you can use await
async function run() {
  // Provide a prompt that contains text
  const prompt = "Write a story about a magic backpack."

  // To generate text output, call generateContent with the text input
  const result = await model.generateContent(prompt);

  const response = result.response;
  const text = response.text();
  console.log(text);
}

run();

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.5-flash');

// Provide a prompt that contains text
final prompt = [Content.text('Write a story about a magic backpack.')];

// To generate text output, call generateContent with the text input
final response = await model.generateContent(prompt);
print(response.text);

Unity


using Firebase;
using Firebase.AI;

// Initialize the Gemini Developer API backend service
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());

// Create a `GenerativeModel` instance with a model that supports your use case
var model = ai.GetGenerativeModel(modelName: "gemini-2.5-flash");

// Provide a prompt that contains text
var prompt = "Write a story about a magic backpack.";

// To generate text output, call GenerateContentAsync with the text input
var response = await model.GenerateContentAsync(prompt);
UnityEngine.Debug.Log(response.Text ?? "No text in response.");

您还可以做些什么?

详细了解支持的型号

了解适用于各种应用场景的模型及其配额价格

试用其他功能

了解如何控制内容生成

  • 了解提示设计,包括最佳实践、策略和示例提示。
  • 配置模型参数,例如温度和输出 token 数上限(对于 Gemini)或宽高比和人物生成(对于 Imagen)。
  • 使用安全设置来调整获得可能被视为有害的回答的可能性。
您还可以尝试使用提示和模型配置,甚至可以使用 Google AI Studio 获取生成的代码段。


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