從 Google AI 用戶端 SDK 遷移至 Firebase AI Logic SDK


直接前往遷移操作說明

為什麼要改用 Firebase AI Logic SDK?

您可能已試用過另一組行動或網頁用戶端 SDK,可讓您存取 Gemini Developer API。

這些用戶端 SDK 並未整合至強大的 Firebase 生態系統,該生態系統為行動和網頁應用程式提供重要服務。這些 API 現已淘汰,建議改用 Firebase AI Logic 用戶端 SDK,以便存取 Gemini Developer API。

行動和網頁應用程式的安全防護功能

對於行動和網頁應用程式,安全性至關重要,需要特別考量,因為您的程式碼 (包括對 Gemini API 的呼叫) 是在未受保護的環境中執行。您可以使用 Firebase App Check,防止未經授權的用戶端濫用 API。

搭配使用 Firebase App Check 和 Firebase AI Logic 時,請勿將 Gemini Developer API 的 Gemini API 金鑰直接加入行動或網頁應用程式的程式碼集。Gemini API 金鑰會留在伺服器上,不會暴露給惡意行為人。

專為行動和網頁應用程式打造的生態系統

Firebase 是 Google 的行動和網頁應用程式開發平台,使用 Firebase AI Logic,代表應用程式處於專注於全端應用程式和開發人員需求的生態系統中。例如:

  • 使用 Firebase Remote Config,動態設定執行階段設定,或替換應用程式中的值 (例如模型名稱和版本),不必發布新的應用程式版本。

  • 使用 Cloud Storage for Firebase 在多模態要求中加入大型檔案 (如果使用 Agent Platform Gemini API (formerly Vertex AI))。Cloud Storage 用戶端 SDK 可協助您處理檔案上傳和下載作業 (即使網路狀況不佳),並為使用者資料提供更完善的安全性。如要進一步瞭解 如何使用 Cloud Storage for Firebase,請參閱解決方案指南。

  • 使用專為行動和網頁應用程式建構的資料庫 SDK (例如 Cloud Firestore) 管理結構化資料。

遷移至 Firebase AI Logic SDK

遷移至 Firebase AI Logic SDK 的步驟總覽:

  • 步驟 1:設定新的或現有的 Firebase 專案,並將應用程式連結至 Firebase。

  • 步驟 2:在應用程式中加入 Firebase AI Logic SDK。

  • 步驟 3:更新應用程式中的匯入和初始化作業。

  • 步驟 4:根據使用的功能更新程式碼。

步驟 1:設定 Firebase 專案並連結應用程式

  1. 登入 Firebase 控制台,然後選取 Firebase 專案。

  2. 在 Firebase 控制台,依序前往「AI Services」(AI 服務) > 「AI Logic」。

  3. 按一下「Get started」(開始使用),啟動引導式工作流程,協助您設定專案所需的 API 和資源。

  4. 選取 Gemini Developer API。之後隨時可以視需要設定及使用其他 API 供應商。

    控制台會啟用必要的 API,並在專案中建立新的專屬 Gemini API 金鑰。
    請勿將這個新的 Gemini API 金鑰加入應用程式的程式碼集。 瞭解詳情。

  5. 如果控制台的工作流程中出現提示,請按照畫面上的指示註冊應用程式,並連結至 Firebase。

  6. 請繼續參閱本遷移指南,更新應用程式中的程式庫和初始化。

步驟 2:在應用程式中加入 Firebase AI Logic SDK

設定 Firebase 專案並將應用程式連結至 Firebase 後 (請參閱上一步),即可在應用程式中加入 Firebase AI Logic SDK。

Swift

使用 Swift Package Manager 安裝及管理 Firebase 依附元件。如有需要,請參閱其他安裝選項。

Firebase AI Logic 程式庫提供 API 存取權,可與 Gemini 模型互動。這個程式庫包含在 Apple 平台專用 Firebase SDK (firebase-ios-sdk) 中。

如果您已使用 Firebase,請確認 Firebase 套件為 12.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

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

在模組 (應用程式層級) Gradle 檔案 (例如 <project>/<app-module>/build.gradle.kts) 中,新增 Android Firebase AI Logic 和 App Check 程式庫的依附元件。建議使用 Firebase Android BoM 控制程式庫版本。

dependencies {
  // ... other androidx dependencies

  // Import the BoM for the Firebase platform
  implementation(platform("com.google.firebase:firebase-bom:35.2.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

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

在模組 (應用程式層級) Gradle 檔案 (例如 <project>/<app-module>/build.gradle.kts) 中,新增 Android 適用的 Firebase AI Logic 和 App Check 程式庫依附元件。建議使用 Firebase Android BoM 控制程式庫版本。

如果是 Java,則需要額外新增兩個程式庫。

dependencies {
  // ... other androidx dependencies

  // Import the BoM for the Firebase platform
  implementation(platform("com.google.firebase:firebase-bom:35.2.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 安裝 Firebase JS SDK for Web:

    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 和 App Check 外掛程式:

    flutter pub add firebase_ai firebase_app_check
    
  2. 在 lib/main.dart 檔案中,匯入 Firebase AI Logic 和 App 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

Google AI 用戶端 SDK 不支援 Unity。

瞭解如何開始使用 Firebase AI Logic SDK for Unity。

從應用程式中移除舊版 SDK

完成應用程式遷移後 (請參閱本指南的其餘部分),請務必刪除舊程式庫。

Swift

移除舊程式庫:

  1. 在 Xcode 中開啟應用程式專案,然後前往「Packages Dependencies」窗格。

  2. 從套件依附元件清單中選取 generative-ai-swift 套件。

  3. 按一下清單底部的 - 按鈕,然後按一下「Remove」(移除) 確認操作。

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。

瞭解如何開始使用 Firebase AI Logic SDK for Unity。

步驟 3:更新應用程式中的匯入和初始化作業

更新匯入項目、Gemini Developer API 後端服務的初始化方式,以及 GenerativeModel 執行個體的建立方式。

Swift

// BEFORE
import GoogleGenerativeAI

let model = GenerativeModel(name: "MODEL_NAME", apiKey: APIKey.default)

// AFTER
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-4-hydrogen")

Kotlin

// BEFORE
import 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-4-hydrogen")

Java

// BEFORE
import 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-4-hydrogen");

// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);

Web

// BEFORE
import { 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-4-hydrogen" });

Dart

// BEFORE
import '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-4-hydrogen');

Unity

Google AI 用戶端 SDK 不支援 Unity。

瞭解如何開始使用 Firebase AI Logic SDK for Unity。

請注意,視您使用的功能而定,您不一定會建立 GenerativeModel 執行個體。如要使用 Gemini Live API 串流輸入和輸出內容,請建立 LiveModel 執行個體。

步驟 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 欄位變更為可為空值。
  • Duration 類別

    • 移除 Kotlin Duration 類別的所有用途,並改用 long。這項變更可提升與 Java 的互通性。
  • 引用中繼資料

    • 將先前在 CitationMetadata 中宣告的所有欄位包裝到名為 Citation 的新類別中。您可以在 CitationMetadata 的 citations 清單中找到引用內容。這項變更可讓各平台的類型更一致。
  • 計算詞元數

    • 將 totalBillableCharacters 欄位變更為可為空值。
  • 計費字元總數

    • 將 CountTokensResponse 中的 totalBillableCharacters 屬性變更為選用,以反映未傳送任何字元的情況。
  • 例項化模型

    • 將 requestOptions 參數移至參數清單結尾,以便與其他平台保持一致。

Java

  • 列舉

    • 將 enum 類別和 sealed 類別替換為一般類別。這項變更可讓您以回溯相容的方式,更靈活地發展 API。

    • 將 BlockThreshold 列舉重新命名為 HarmBlockThreshold。

    • 從下列列舉中移除值:HarmBlockThreshold、HarmProbability、HarmSeverity、BlockReason 和 FinishReason。

  • Blob 方法

    • 重新命名名稱中包含 Blob 的所有方法,改用 InlineData。
  • 安全性設定

    • 將 method 欄位變更為可為空值。
  • Duration 類別

    • 移除 Kotlin Duration 類別的所有用途,並改用 long。這項變更可提升與 Java 的互通性。
  • 引用中繼資料

    • 將先前在 CitationMetadata 中宣告的所有欄位包裝到名為 Citation 的新類別中。您可以在 CitationMetadata 的 citations 清單中找到引用內容。這項變更可讓各平台的類型更一致。
  • 計算詞元數

    • 將 totalBillableCharacters 欄位變更為可為空值。
  • 計費字元總數

    • 將 CountTokensResponse 中的 totalBillableCharacters 屬性變更為選用,以反映未傳送任何字元的情況。
  • 例項化模型

    • 將 requestOptions 參數移至參數清單結尾,以便與其他平台保持一致。

Web

請注意,自 Firebase AI Logic 用戶端 SDK 從 Google AI JavaScript 用戶端 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,以便與其他平台保持一致。
  • 要求選項

    • 由於 timeout 無法運作,因此已移除 RequestOptions。我們會在不久後重新加入,但會移至 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 SDK for Unity。


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