使用 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 開發網路應用程式。本指南與架構無關。

  • 請確認開發環境和網路應用程式符合下列規定:

    • (選用) Node.js
    • 新式網路瀏覽器
  • (選用) 查看範例應用程式。

    下載範例應用程式

    您可以快速試用 SDK、查看各種用途的完整實作方式,或使用範例應用程式 (如果您沒有自己的網頁應用程式)。如要使用範例應用程式,請將其連結至 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」供應商。你之後隨時可以設定及使用其他 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 Apple 平台 SDK (firebase-ios-sdk)。

如果您已使用 Firebase,請確認 Firebase 套件為 11.13.0 以上版本。

  1. 在 Xcode 中保持開啟應用程式專案,然後依序點選「File」(檔案) 和「Add Package Dependencies」(新增 Package 依附元件)

  2. 系統提示時,請新增 Firebase Apple 平台 SDK 存放區:

    https://github.com/firebase/firebase-ios-sdk
    
  3. 選取最新版 SDK。

  4. 選取 FirebaseAI 程式庫。

完成後,Xcode 會自動開始在背景中解析並下載依附元件。

Kotlin

Firebase AI Logic Android 適用的 SDK (firebase-ai) 提供 API 存取權,可與 GeminiImagen 模型互動。

模組 (應用程式層級) 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.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) 提供 API 存取權,可與 GeminiImagen 模型互動。

模組 (應用程式層級) 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.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,可與 GeminiImagen 模型互動。這個程式庫是 Firebase JavaScript SDK for Web 的一部分。

  1. 使用 npm 安裝適用於網頁的 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) 可存取與 GeminiImagen 模型互動的 API。

  1. 在 Flutter 專案目錄中執行下列指令,安裝核心外掛程式和 Firebase AI Logic 外掛程式:

    flutter pub add firebase_core && flutter pub add 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 中的方法是暫停函式,需要從 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-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.");

你還可以做些什麼?

進一步瞭解支援的機型

瞭解各種用途適用的模型,以及配額價格

試試其他功能

瞭解如何控管內容生成

您也可以使用 Google AI Studio 實驗提示和模型設定,甚至取得生成的程式碼片段。


提供有關 Firebase AI Logic 的使用體驗意見回饋