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

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

前提条件

Swift

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

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

  • Xcode 26.2 或更高版本
  • 您的应用以 iOS 15 或更高版本或 macOS 12 或更高版本为目标平台

Kotlin

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

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

  • Android Studio(最新版本)
  • 您的应用以 API 级别 21 或更高级别为目标平台

Java

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

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

  • Android Studio(最新版本)
  • 您的应用以 API 级别 21 或更高级别为目标平台

Web

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

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

  • (可选)Node.js
  • 现代网络浏览器

Dart

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

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

  • Dart 3.2.0+

Unity

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

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

  • Unity 编辑器 2021 LTS 或更高版本

查看实用资源

Swift

试用快速入门应用

使用快速入门应用可快速试用 SDK,并查看各种使用情形的完整实现。如果您没有自己的 Apple 平台应用,也可以使用快速入门应用。如需使用快速入门应用,您需要将其关联到 Firebase 项目

前往快速入门应用

观看视频教程

此视频演示了如何通过构建一个实际的 AI 赋能型膳食规划应用来开始使用 Firebase AI Logic,该应用可根据文本提示生成食谱。

您还可以下载并探索视频中应用的代码库。

查看视频中应用的代码库



Kotlin

试用快速入门应用

使用快速入门应用可快速试用 SDK,并查看各种使用情形的完整实现。如果您没有自己的 Android 应用,也可以使用快速入门应用。如要使用快速入门应用,您需要将其关联到 Firebase 项目

前往快速入门应用

观看视频教程

此视频演示了如何通过构建一个实际的 AI 赋能型膳食规划应用来开始使用 Firebase AI Logic,该应用可根据文本提示生成食谱。

您还可以下载并探索视频中应用的代码库。

查看视频中应用的代码库



Java

试用快速入门应用

使用快速入门应用可快速试用 SDK,并查看各种使用情形的完整实现。如果您没有自己的 Android 应用,也可以使用快速入门应用。如要使用快速入门应用,您需要将其关联到 Firebase 项目

前往快速入门应用

观看视频教程

此视频演示了如何通过构建一个由 AI 赋能的实际膳食规划应用(该应用可根据文本提示生成食谱)来开始使用 Firebase AI Logic*

您还可以下载并探索视频中应用的代码库。

查看视频中应用的代码库

* 此视频及其应用采用 Kotlin 编写,但仍可帮助 Java 开发者了解有关如何开始使用 Firebase AI Logic 的基础知识。

Web

试用快速入门应用

使用快速入门应用可快速试用 SDK,并查看各种使用情形的完整实现。如果您没有自己的 Web 应用,也可以使用快速入门应用。若要使用快速入门应用,您需要将其关联到 Firebase 项目

前往快速入门应用

Dart

试用快速入门应用

使用快速入门应用可快速试用 SDK,并查看各种使用情形的完整实现。如果您没有自己的 Flutter 应用,也可以使用快速入门应用。如要使用快速入门应用,您需要将其关联到 Firebase 项目

前往快速入门应用

观看视频教程

此视频演示了如何通过构建一个实际的 AI 赋能型膳食规划应用来开始使用 Firebase AI Logic,该应用可根据文本提示生成食谱。

您还可以下载并探索视频中应用的代码库。

查看视频中应用的代码库



Unity

试用快速入门应用

使用快速入门应用可快速试用 SDK,并查看各种使用情形的完整实现。如果您没有自己的 Unity 游戏,也可以使用快速入门应用。如需使用快速入门应用,您需要将其关联到 Firebase 项目

前往快速入门应用

第 1 步:设置 Firebase 项目并启用 API

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

  2. Firebase 控制台中,依次前往 AI 服务 > AI 逻辑

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

  4. 如果系统提示,请按照屏幕上的说明注册您的应用,并将 Firebase 配置添加到您的应用。

  5. 当系统要求您选择“Gemini API 提供方”时,我们建议您选择 Gemini Developer API,这样您就可以快速免费开始使用。

    您以后可以随时设置 Vertex AI Gemini API(以及其结算要求)。

  6. 继续执行工作流,为 Firebase AI Logic 设置所需的 API 和关联服务。

    从 2026 年 7 月初开始,此工作流程阶段将自动针对 AI Logic 强制执行 Firebase App Check,这是一项关键服务,可帮助保护 Gemini API(当其直接从您的应用访问时)。在开始使用时(请参阅本指南后面的步骤),您需要在强制执行 App Check 时为本地开发配置 App Check 调试提供程序

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

第 2 步:添加所需的 SDK

设置好 Firebase 项目并启用必需的 API(请参阅上一步)后,您现在可以将必需的 SDK 添加到应用中。

Swift

使用 Swift Package Manager 安装和管理 Firebase 依赖项。 如有需要,请了解其他安装选项

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

如果您已在使用 Firebase,请确保您的 Firebase 软件包为 v12.5.0 或更高版本。

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

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

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

  4. 选择 FirebaseAILogic 库和 FirebaseAppCheck 库。

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

Kotlin

适用于 Android 的 Firebase AI Logic SDK (firebase-ai) 提供用于与 Gemini 模型互动的 API。

在您的模块(应用级)Gradle 文件(例如 <project>/<app-module>/build.gradle.kts)中,添加 Firebase AI Logic Android 库的依赖项。 我们建议使用 Firebase Android BoM 来实现库版本控制。

dependencies {
  // ... other androidx dependencies

  // Import the BoM for the Firebase platform
  implementation(platform("com.google.firebase:firebase-bom:34.15.0"))

  // Add the dependencies for the Firebase AI Logic and App Check libraries
  // When using the BoM, you don't specify versions in Firebase library dependencies
  implementation("com.google.firebase:firebase-ai")
  implementation("com.google.firebase:firebase-appcheck-debug")
}

借助 Firebase Android BoM,可确保您的应用使用的始终是 Firebase Android 库的兼容版本。

Java

适用于 Android 的 Firebase AI Logic SDK (firebase-ai) 提供用于与 Gemini 模型互动的 API。

在您的模块(应用级)Gradle 文件(例如 <project>/<app-module>/build.gradle.kts)中,添加 Firebase AI Logic Android 库的依赖项。 我们建议使用 Firebase Android BoM 来实现库版本控制。

对于 Java,您需要添加两个额外的库。

dependencies {
  // ... other androidx dependencies

  // Import the BoM for the Firebase platform
  implementation(platform("com.google.firebase:firebase-bom:34.15.0"))

  // Add the dependencies for the Firebase AI Logic and App Check libraries
  // When using the BoM, you don't specify versions in Firebase library dependencies
  implementation("com.google.firebase:firebase-ai")
  implementation("com.google.firebase:firebase-appcheck-debug")

  // 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 模型进行交互。该库包含在 Firebase JavaScript SDK for Web 中。

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

    npm install firebase
    
  2. 在您的应用中初始化 Firebase:

    import { initializeApp } from "firebase/app";
    import { initializeAppCheck, DebugProvider } from "firebase/app-check";
    
    // 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 模型进行交互。

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

    flutter pub add firebase_ai firebase_app_check
    
  2. lib/main.dart 文件中,导入 Firebase AI LogicApp Check 插件:

    import 'package:firebase_core/firebase_core.dart';
    import 'package:firebase_ai/firebase_ai.dart';
    import 'package:firebase_app_check/firebase_app_check.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 软件包和 FirebaseAppCheck 软件包。

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

第 3 步:为本地开发配置 App Check 调试提供程序

自 2026 年 7 月初起,在 Play 管理中心内为 AI Logic 提供的引导式设置工作流程中,系统会自动强制执行 Firebase App Check,以保护 Gemini API。对于本地开发,您需要配置 App Check 调试提供程序,以便在绕过证明的同时,仍能保持 App Check 的强制执行。

Swift

如需在模拟器中以交互方式运行应用时(例如在本地开发期间)使用调试提供方,请执行以下操作:

  1. 在 Xcode 项目中,导入 FirebaseAppCheck 并使用调试提供方工厂 配置 Firebase 之前初始化 App Check

    import SwiftUI
    import FirebaseCore
    import FirebaseAppCheck
    
    @main
    struct YourApp: App {
      init() {
        let providerFactory = AppCheckDebugProviderFactory()
        AppCheck.setAppCheckProviderFactory(providerFactory)
        FirebaseApp.configure()
      }
    
      var body: some Scene {
        WindowGroup {
          NavigationView {
            ContentView()
          }
        }
      }
    }
    
  2. 获取调试令牌:

    1. 在模拟器中或在测试设备上启动应用。

    2. 打开 Xcode 控制台,然后查找 App Check 调试令牌。 例如:

      <Warning> [AppCheckCore][I-GAC004001] App Check debug token: '123a4567-b89c-12d3-e456-789012345678'.
      
    3. 复制令牌(例如 123a4567-b89c-12d3-e456-789012345678)。

  3. App Check 注册调试令牌:

    1. Firebase 控制台中,依次前往安全性 > App Check > 应用标签页

    2. 找到您的应用,点击溢出菜单 (),然后选择管理调试令牌

    3. 按照屏幕上的说明注册调试令牌。

如需详细了解调试提供程序(包括如何获取新的调试令牌),请参阅官方 App Check 文档

Kotlin

如需在模拟器中以交互方式运行应用时(例如在本地开发期间)使用调试提供程序,请执行以下操作:

  1. 在调试 build 中,将 App Check 配置为使用调试提供方工厂:

    Firebase.initialize(context = this)
    Firebase.appCheck.installAppCheckProviderFactory(
        DebugAppCheckProviderFactory.getInstance(),
    )
  2. 获取调试令牌:

    1. 在模拟器中或在测试设备上运行应用。

    2. 在日志中查找 App Check 调试令牌。例如:

      D DebugAppCheckProvider: Enter this debug secret into the allow list
      in the Firebase Console for your project: 123a4567-b89c-12d3-e456-789012345678
      
    3. 复制令牌(例如 123a4567-b89c-12d3-e456-789012345678)。

  3. App Check 注册调试令牌:

    1. Firebase 控制台中,依次前往安全性 > App Check > 应用标签页

    2. 找到您的应用,点击溢出菜单 (),然后选择管理调试令牌

    3. 按照屏幕上的说明注册调试令牌。

如需详细了解调试提供程序(包括如何获取新的调试令牌),请参阅官方 App Check 文档

Java

如需在模拟器中以交互方式运行应用时(例如在本地开发期间)使用调试提供程序,请执行以下操作:

  1. 在调试 build 中,将 App Check 配置为使用调试提供方工厂:

    FirebaseApp.initializeApp(/*context=*/ this);
    FirebaseAppCheck firebaseAppCheck = FirebaseAppCheck.getInstance();
    firebaseAppCheck.installAppCheckProviderFactory(
            DebugAppCheckProviderFactory.getInstance());
  2. 获取调试令牌:

    1. 在模拟器中或在测试设备上运行应用。

    2. 在日志中查找 App Check 调试令牌。例如:

      D DebugAppCheckProvider: Enter this debug secret into the allow list
      in the Firebase Console for your project: 123a4567-b89c-12d3-e456-789012345678
      
    3. 复制令牌(例如 123a4567-b89c-12d3-e456-789012345678)。

  3. App Check 注册调试令牌:

    1. Firebase 控制台中,依次前往安全性 > App Check > 应用标签页

    2. 找到您的应用,点击溢出菜单 (),然后选择管理调试令牌

    3. 按照屏幕上的说明注册调试令牌。

如需详细了解调试提供程序(包括如何获取新的调试令牌),请参阅官方 App Check 文档

Web

如需在从 localhost 以交互方式运行应用时(例如在本地开发期间)使用调试提供程序,请执行以下操作:

  1. 在调试 build 中,请在初始化 App Check 之前将 self.FIREBASE_APPCHECK_DEBUG_TOKEN 设置为 true 以启用调试模式。例如:

    self.FIREBASE_APPCHECK_DEBUG_TOKEN = true;
    initializeAppCheck(app, { /* App Check options */ });
    
  2. 在本地访问 Web 应用,然后打开浏览器的开发者工具。在调试控制台中,您将看到一个调试令牌:

    AppCheck debug token: "123a4567-b89c-12d3-e456-789012345678".
    You will need to safelist it in the Firebase console for it to work.
    
  3. App Check 注册调试令牌:

    1. Firebase 控制台中,依次前往安全性 > App Check > 应用标签页

    2. 找到您的应用,点击溢出菜单 (),然后选择管理调试令牌

    3. 按照屏幕上的说明注册调试令牌。

如需详细了解调试提供程序(包括如何获取新的调试令牌),请参阅官方 App Check 文档

Dart

iOS+

如需在模拟器中以交互方式运行应用时(例如在本地开发期间)使用调试提供方,请执行以下操作:

  1. 在初始化 Firebase 应用后立即使用调试提供方激活 App Check

    import 'package:flutter/material.dart';
    import 'package:firebase_core/firebase_core.dart';
    
    // Import the firebase_app_check plugin
    import 'package:firebase_app_check/firebase_app_check.dart';
    
    Future<void> main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp();
      await FirebaseAppCheck.instance.activate(
        // Set appleProvider to `AppleProvider.debug`
        appleProvider: AppleProvider.debug,
      );
      runApp(App());
    }
    
  2. 在 Xcode 项目中启用调试日志记录:

    1. 打开 Product(产品)> Scheme(方案)> Edit scheme(修改方案)
    2. 从左侧菜单中选择 Run(运行),然后选择 Arguments(实参)标签页。
    3. Arguments Passed on Launch(启动参数)部分,添加 -FIRDebugEnabled
  3. 获取调试令牌:

    1. 使用 Xcode 打开 ios/Runner.xcworkspace,然后在模拟器或测试设备上运行您的应用。

    2. 打开 Xcode 控制台,然后查找 App Check 调试令牌。 例如:

      <Warning> [AppCheckCore][I-GAC004001] App Check debug token: '123a4567-b89c-12d3-e456-789012345678'.
      
    3. 复制令牌(例如 123a4567-b89c-12d3-e456-789012345678)。

  4. App Check 注册调试令牌:

    1. Firebase 控制台中,依次前往安全性 > App Check > 应用标签页

    2. 找到您的应用,点击溢出菜单 (),然后选择管理调试令牌

    3. 按照屏幕上的说明注册调试令牌。

Android

如需在模拟器中以交互方式运行应用时(例如在本地开发期间)使用调试提供程序,请执行以下操作:

  1. 在初始化 Firebase 应用后立即使用调试提供方激活 App Check

    import 'package:flutter/material.dart';
    import 'package:firebase_core/firebase_core.dart';
    
    // Import the firebase_app_check plugin
    import 'package:firebase_app_check/firebase_app_check.dart';
    
    Future<void> main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp();
      await FirebaseAppCheck.instance.activate(
        // Set androidProvider to `AndroidProvider.debug`
        androidProvider: AndroidProvider.debug,
      );
      runApp(App());
    }
    
  2. 获取调试令牌:

    1. 在模拟器中或在测试设备上运行应用。

    2. 在日志中查找 App Check 调试令牌。例如:

      D DebugAppCheckProvider: Enter this debug secret into the allow list
      in the Firebase Console for your project: 123a4567-b89c-12d3-e456-789012345678
      
    3. 复制令牌(例如 123a4567-b89c-12d3-e456-789012345678)。

  3. App Check 注册调试令牌:

    1. Firebase 控制台中,依次前往安全性 > App Check > 应用标签页

    2. 找到您的应用,点击溢出菜单 (),然后选择管理调试令牌

    3. 按照屏幕上的说明注册调试令牌。

Web

如需在从 localhost 以交互方式运行应用时(例如在本地开发期间)使用调试提供方,请执行以下操作:

  1. web/index.html 文件中,将 self.FIREBASE_APPCHECK_DEBUG_TOKEN 设置为 true,以启用调试模式:

    <body>
      <script>
        self.FIREBASE_APPCHECK_DEBUG_TOKEN = true;
      </script>
    
      ...
    
    </body>
    
  2. 在本地运行您的 Web 应用,然后打开浏览器的开发者工具。在调试控制台中,您将看到一个调试令牌:

    AppCheck debug token: "123a4567-b89c-12d3-e456-789012345678".
    You will need to safelist it in the Firebase console for it to work.
    

    此令牌存储在您的浏览器本地,每当您在同一计算机上的同一浏览器中使用您的应用时,系统都会使用该令牌。如果要在其他浏览器或其他机器上使用该令牌,请将 self.FIREBASE_APPCHECK_DEBUG_TOKEN 明确设置为该令牌对应的字符串,而不是 true

  3. App Check 注册调试令牌:

    1. Firebase 控制台中,依次前往安全性 > App Check > 应用标签页

    2. 找到您的应用,点击溢出菜单 (),然后选择管理调试令牌

    3. 按照屏幕上的说明注册调试令牌。

如需详细了解调试提供程序(包括如何获取新的调试令牌),请参阅官方 App Check 文档

Unity

如需在模拟器中以交互方式运行应用时(例如在本地开发期间)使用调试提供程序,请执行以下操作:

  1. Firebase 控制台中,创建调试令牌:

    1. Firebase 控制台中,依次前往安全性 > App Check > 应用标签页

    2. 找到您的应用,点击溢出菜单 (),然后选择管理调试令牌

    3. 按照屏幕上的说明创建新的调试令牌。

  2. 在应用的初始化代码中,添加以下内容:

    using Firebase.AppCheck;
    
    void InitializeFirebase() {
      // Configure the Debug Provider factory with your debug token.
      DebugAppCheckProviderFactory.Instance.SetDebugToken("YOUR_DEBUG_TOKEN");
    
      // Set App Check to use the debug provider factory
      FirebaseAppCheck.SetAppCheckProviderFactory(
        DebugAppCheckProviderFactory.Instance);
    
      // Proceed to initialize Firebase as normal
    }
    

如需详细了解调试提供程序(包括如何获取新的调试令牌),请参阅官方 App Check 文档

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

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

在向 Gemini 模型发送提示之前,请为所选的 API 提供方初始化服务,并创建 GenerativeModel 实例。

Swift


import FirebaseAILogic

// 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-3.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-3.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-3.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-3.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-3.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-3.5-flash");

请注意,根据您使用的功能,您可能并不总是需要创建 GenerativeModel 实例。如需使用 Gemini Live API 对输入和输出进行流式处理,请创建 LiveModel 实例。

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

第 5 步:向模型发送请求

您现在已设置好,可以向 Gemini 模型发送请求。

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

Swift


import FirebaseAILogic

// 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-3.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 中的方法是挂起函数,需要从 Coroutine 范围调用。

// 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-3.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 = model.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-3.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-3.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-3.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-3.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.");

您还可以做些什么?

详细了解支持的型号

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

试用其他功能

了解如何控制内容生成

您还可以尝试使用提示和模型配置,甚至可以使用 Google AI Studio 获取生成的代码段。


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