從 Google AI 用戶端 SDK 遷移至 Firebase AI 邏輯 SDK


直接前往遷移說明

為什麼要遷移至 Firebase AI Logic SDK?

您可能試過其他行動或網頁用戶端 SDK,並透過這些 SDK 存取 Gemini Developer API

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

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

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

使用 Firebase App CheckFirebase AI Logic 時,您絕不會將 Gemini Developer APIGemini API 金鑰直接加入行動或網頁應用程式的程式碼集。API 金鑰會留在伺服器上,不會暴露給不肖分子。Gemini

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

Firebase 是 Google 的行動和網頁應用程式開發平台,使用 Firebase AI Logic表示您的應用程式位於以全端應用程式和開發人員需求為主的生態系統中。例如:

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

  • 使用 Cloud Storage for Firebase 在多模態要求中加入大型檔案 (如果您使用 Vertex AI Gemini API)。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 控制台的「Firebase AI Logic」頁面

  3. 按一下「開始使用」,即可啟動導覽工作流程,協助您為專案設定必要 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,可與 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

Google AI 用戶端 SDK 不支援 Unity。

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

從應用程式中移除舊版 SDK

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

Swift

移除舊媒體庫:

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

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

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

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。

瞭解如何開始使用 Unity 適用的 Firebase AI Logic SDK

步驟 3:更新應用程式中的匯入項目和初始化設定

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

Swift

// BEFORE
import GoogleGenerativeAI

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

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

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

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-2.5-flash");

// 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-2.5-flash" });

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

Unity

Google AI 用戶端 SDK 不支援 Unity。

瞭解如何開始使用 Unity 適用的 Firebase AI Logic SDK

請注意,視您使用的功能而定,您可能不一定會建立 GenerativeModel 執行個體

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

本步驟說明您可能需要進行的變更,視您使用的功能而定。

  • Firebase AI Logic 用戶端 SDK 不支援執行程式碼。如果使用這項功能,請務必在應用程式中配合調整。

  • 請查看下列清單,瞭解程式碼中可能需要進行哪些變更,才能遷移至 Firebase AI Logic 用戶端 SDK。

所有語言和平台都必須提供

  • 函式呼叫
    如果您已實作這項功能,則需要更新定義結構定義的方式。建議您詳閱更新後的函式呼叫指南,瞭解如何編寫函式宣告。

  • 使用 responseSchema
    生成結構化輸出內容 (例如 JSON) 如果您已實作這項功能,則需要更新結構定義方式。建議您參閱新的結構化輸出指南,瞭解如何編寫 JSON 結構定義。

  • 逾時

    • 將要求的預設逾時時間變更為 180 秒。

視平台或語言而定

Swift

  • 列舉

    • 將大部分 enum 型別換成具有靜態變數的 struct。這項變更可讓您更靈活地以回溯相容的方式演進 API。使用 switch 陳述式時,現在必須加入 default: 情況,涵蓋不明或未處理的值,包括日後新增至 SDK 的值。

    • 已將 BlockThreshold 列舉重新命名為 HarmBlockThreshold,這個型別現在是 struct

    • 從下列列舉中移除 unknownunspecified 案例 (現在為 struct):HarmCategoryHarmBlockThresholdHarmProbabilityBlockReasonFinishReason

    • 將列舉 ModelContent.Part 替換為名為 Part 的通訊協定,以便以回溯相容的方式新增類型。如要瞭解這項異動的詳細資訊,請參閱「內容部分」一節。

  • 內容部分

    • 已移除 ThrowingPartsRepresentable 協定,並簡化 ModelContent 的初始值,避免偶爾發生編譯器錯誤。如果圖片編碼不正確,在 generateContent 中使用時仍會擲回錯誤。

    • 已將 ModelContent.Part 案例替換為以下 struct 型別, 並符合 Part 通訊協定:

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

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

    • 將先前在 CitationMetadata 中宣告的所有欄位,包裝到名為 Citation 的新類別中。您可以在 CitationMetadata 中找到名為「引文」citations的清單。這項異動可讓各平台上的型別更一致。
  • 計算權杖數

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

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

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

Java

  • 列舉

    • 以一般類別取代 enum 類別和 sealed 類別。這項變更可讓 API 發展更具彈性,同時確保回溯相容性。

    • BlockThreshold 列舉重新命名為 HarmBlockThreshold

    • 從下列列舉中移除值:HarmBlockThresholdHarmProbabilityHarmSeverityBlockReasonFinishReason

  • Blob 方法

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

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

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

    • 將先前在 CitationMetadata 中宣告的所有欄位,包裝到名為 Citation 的新類別中。您可以在 CitationMetadata 中找到名為「引文」citations的清單。這項異動可讓各平台上的型別更一致。
  • 計算權杖數

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

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

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

Web

請注意,自從 Firebase AI Logic 用戶端 SDK 從 JavaScript 適用的 Google AI 用戶端 SDK 分支以來,後者已歷經多次變更。以下列出一些潛在變更,您在遷移至 Firebase AI Logic 用戶端 SDK 時可能需要考量。

  • 列舉

    • 已從下列列舉中移除值:HarmCategoryBlockThresholdHarmProbabilityHarmSeverityBlockReasonFinishReason
  • 封鎖原因

    • PromptFeedback 中的 blockReason 變更為選用。
  • 搜尋基準

    • 由於 Firebase AI Logic SDK 尚未支援這項功能,因此已移除所有相關用法。
  • 錯誤

    • 移除所有 GoogleGenerativeAIError 用法,並視需要改用 AIError

Dart

  • 列舉

    • 從下列列舉中移除值:HarmCategoryHarmProbabilityBlockReasonFinishReason
  • 資料部分

    • 已將 DataPart 重新命名為 InlineDataPart,並將 static data 函式重新命名為 inlineData,與其他平台保持一致。
  • 要求選項

    • 由於 timeout 無法運作,因此已移除 RequestOptions。我們會在不久的將來重新加入這項功能,但會移至 GenerativeModel 類型,與其他平台保持一致。
  • 停止序列

    • 已將 GenerationConfig 中的 stopSequences 參數變更為選用參數,並預設為 null,而非空陣列。
  • 引用內容

    • 已在 CitationMetadata 中將 citationSources 屬性重新命名為 citations。為配合其他平台,CitationSource 型別已重新命名為 Citation
  • 不必要的公開型別、方法和屬性

    • 已移除下列無意間公開的型別、方法和屬性:defaultTimeoutCountTokensResponseFieldsparseCountTokensResponseparseEmbedContentResponseparseGenerateContentResponseparseContentBatchEmbedContentsResponseContentEmbeddingEmbedContentRequestEmbedContentResponse
  • 計算權杖數

    • countTokens 函式中移除不再需要的額外欄位。只需要 contents
  • 例項化模型

    • systemInstruction 參數移至參數清單結尾,與其他平台保持一致。
  • 嵌入功能

    • 從模型中移除不支援的嵌入功能 (embedContentbatchEmbedContents)。

Unity

Google AI 用戶端 SDK 不支援 Unity。

瞭解如何開始使用 Unity 適用的 Firebase AI Logic SDK


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