在 Android 應用程式中,使用裝置端和雲端代管模型建構混合式體驗


您可以使用 Firebase AI Logic 透過混合式推論建構 AI 輔助 Android 應用程式和功能。混合式推論可讓您在可用時使用裝置端模型執行推論,否則會順暢地改用雲端託管模型 (反之亦然)。

本頁說明如何開始使用用戶端 SDK,以及其他設定選項和功能。

請注意,Android 應用程式必須使用 Firebase AI Logic SDK 17.10.0 以上版本 (BoM 34.10.0 以上版本),並在特定裝置上執行,才能透過 Firebase AI Logic 進行裝置端推論。這項功能受《ML Kit 條款》和《ML Kit 生成式 AI 相關條款》規範。

建議用途和支援的功能

建議用途

  • 使用裝置端模型進行推論可帶來以下優點:

    • 強化隱私權
    • 查看當地特色
    • 免付費推論
    • 離線功能
  • 使用混合功能可享有以下優勢:

    • 配合裝置端模型可用性和網際網路連線,觸及更多目標對象

裝置端推論支援的功能和特色

裝置端推論僅支援單輪文字生成 (不支援對話),並可採用串流或非串流輸出。支援下列文字生成功能:

請務必查看本頁底部的裝置端推論尚未支援的功能清單。

事前準備

請注意下列事項:

支援的 Android 裝置和裝置端模型

如要瞭解裝置端推論 (使用 ML Kit 的 Prompt API),請參閱 ML Kit 說明文件中的支援裝置和裝置端模型清單。

開始使用

這些入門步驟說明瞭傳送任何支援的提示要求時,所需的一般設定。

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

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

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

  3. 按一下「開始使用」,啟動導覽工作流程,協助您為專案設定必要 API 和資源。

  4. 如果出現提示,請按照畫面上的指示註冊應用程式,並將 Firebase 設定新增至應用程式。

  5. 系統要求選擇「Gemini API 供應商」時,建議選取 Gemini Developer API,即可快速開始使用,不必付費。

    日後隨時可以設定 Agent Platform Gemini API (formerly Vertex AI) (以及計費規定)。

  6. 繼續執行工作流程,為 Firebase AI Logic 設定必要的 API 和相關聯服務。

    2026 年 7 月上旬起,這個工作流程階段會自動強制執行Firebase App Check,用於 AI Logic,這是一項重要服務,可在應用程式直接存取時,協助保護 Gemini API。在開始使用時 (請參閱本指南後續步驟),您必須在本機開發環境中,設定 App Check 偵錯服務,以便強制執行 App Check。

  7. 請繼續閱讀本指南的下一個步驟,將必要的 SDK 新增至應用程式。

步驟 2:新增必要的 SDK

Firebase AI Logic Android 版 SDK (firebase-ai) 和 Firebase AI Logic On-Device SDK (firebase-ai-ondevice) 提供 API 存取權,可與生成式模型互動。

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

Kotlin

dependencies {
  // ... other androidx dependencies

  // Add the dependencies for the Firebase AI Logic and App Check libraries
  // Note that the on-device SDK is not yet included in the Firebase Android BoM
  implementation("com.google.firebase:firebase-ai:18.0.0")
  implementation("com.google.firebase:firebase-ai-ondevice:16.0.0-beta06")
  implementation("com.google.firebase:firebase-appcheck-debug:20.0.0")
}

Java

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

dependencies {
  // ... other androidx dependencies

  // Add the dependencies for the Firebase AI Logic and App Check libraries
  // Note that the on-device SDK is not yet included in the Firebase Android BoM
  implementation("com.google.firebase:firebase-ai:18.0.0")
  implementation("com.google.firebase:firebase-ai-ondevice:16.0.0-beta06")
  implementation("com.google.firebase:firebase-appcheck-debug:20.0.0")

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

步驟 3:設定 App Check 偵錯服務,以便在本機開發

2026 年 7 月上旬起,在控制台設定 AI Logic 的引導式工作流程中,系統會自動強制執行 Firebase App Check,以保護Gemini API。在本機開發時,您需要設定 App Check 偵錯服務,略過認證程序,同時維持 App Check 的強制執行。

  1. 在偵錯版本中,將 App Check 設為使用偵錯服務工廠:

    Kotlin

    Firebase.initialize(context = this)
    Firebase.appCheck.installAppCheckProviderFactory(
        DebugAppCheckProviderFactory.getInstance(),
    )
    

    Java

    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 控制台中,依序前往「Security」(安全性) >「App Check」 >「Apps」(應用程式) 分頁標籤。

    2. 找出您的應用程式,按一下溢位選單 (),然後選取「管理偵錯權杖」。

    3. 按照畫面上的指示註冊偵錯權杖。

如要進一步瞭解偵錯服務 (包括如何取得新的偵錯權杖),請參閱官方 App Check 文件。

步驟 4:檢查裝置端模型是否可用

使用 FirebaseAIOnDevice 檢查裝置端模型是否可用,如果不可用,請下載模型。

下載完成後,AICore 會自動更新模型。如要進一步瞭解 AICore 和管理裝置端模型下載,請參閱程式碼片段後的附註。

Kotlin

val status = FirebaseAIOnDevice.checkStatus()
when (status) {
  OnDeviceModelStatus.UNAVAILABLE -> {
    Log.w(TAG, "On-device model is unavailable")
  }

  OnDeviceModelStatus.DOWNLOADABLE -> {
    FirebaseAIOnDevice.download().collect { status ->
      when (status) {
        is DownloadStatus.DownloadStarted ->
          Log.w(TAG, "Starting download - ${status.bytesToDownload}")

        is DownloadStatus.DownloadInProgress ->
          Log.w(TAG, "Download in progress ${status.totalBytesDownloaded} bytes downloaded")

        is DownloadStatus.DownloadCompleted ->
          Log.w(TAG, "On-device model download complete")

        is DownloadStatus.DownloadFailed ->
          Log.e(TAG, "Download failed ${status}")
      }
    }
  }
  OnDeviceModelStatus.DOWNLOADING -> {
    Log.w(TAG, "On-device model is being downloaded")
  }

  OnDeviceModelStatus.AVAILABLE -> {
    Log.w(TAG, "On-device model is available")
  }
}

Java

Checking for, downloading, and warming up the model is not yet available for Java.

However, all other APIs and interactions in this guide are available for Java.

下載裝置端模型時,請注意下列事項:

  • 下載裝置端模型所需的時間取決於多項因素,包括網路。

  • 如果程式碼使用裝置端模型進行主要或備用推論,請務必在應用程式生命週期的早期下載模型,確保裝置端模型在使用者遇到應用程式中的程式碼前可用。

  • 如果提出裝置端推論要求時,裝置端模型無法使用,SDK 不會自動觸發下載裝置端模型。SDK 會改用雲端託管模型,或擲回例外狀況 (請參閱推論模式行為的詳細資料)。

  • AICore (Android 系統服務) 會管理下載的模型和版本、保持模型更新等。請注意,裝置只會下載一個模型,因此如果裝置上的其他應用程式先前已成功下載裝置端模型,這項檢查就會傳回模型可用的結果。

延遲時間最佳化

如要最佳化首次推論呼叫,可以讓應用程式呼叫 onDeviceExtension?.warmUp() (目前僅適用於 Kotlin)。這會將裝置端模型載入記憶體,並初始化執行階段元件。

步驟 5:初始化服務並建立模型執行個體

按一下您的Gemini API供應商,即可在這個頁面查看供應商專屬內容和程式碼。

請先完成下列設定,再向模型傳送提示要求。

  1. 為所選 API 供應商初始化服務。

  2. 建立 GenerativeModel 例項,並將 mode 設為下列其中一項。這裡的說明非常概略,但您可以參閱「設定推論模式」,進一步瞭解這些模式的行為。

    • PREFER_ON_DEVICE:嘗試使用裝置端模型,否則改用雲端託管模型。

    • ONLY_ON_DEVICE:嘗試使用裝置端模型,否則擲回例外狀況。

    • PREFER_IN_CLOUD:嘗試使用雲端託管模型;否則改用裝置端模型。

    • ONLY_IN_CLOUD:嘗試使用雲端託管模型,否則擲回例外狀況。

Kotlin

// Using this SDK to access on-device inference is an Experimental release and requires opt-in
@OptIn(PublicPreviewAPI::class)

// ...

// Initialize the Gemini Developer API backend service
// Create a GenerativeModel instance with a model that supports your use case
// Set the inference mode (like PREFER_ON_DEVICE to use the on-device model if available)
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
    .generativeModel(
        modelName = "CLOUD_MODEL_NAME",
        onDeviceConfig = OnDeviceConfig(mode = InferenceMode.PREFER_ON_DEVICE)
    )

Java

// Initialize the Gemini Developer API backend service
// Create a GenerativeModel instance with a model that supports your use case
// Set the inference mode (like PREFER_ON_DEVICE to use the on-device model if available)
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
    .generativeModel(
        "CLOUD_MODEL_NAME",
        new OnDeviceConfig(InferenceMode.PREFER_ON_DEVICE)
    );

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

步驟 6:向模型傳送提示要求

本節說明如何傳送各種輸入內容,生成不同類型的輸出內容,包括:

根據純文字輸入內容生成文字

試用這個範例前,請務必先完成本指南的「開始使用」一節。

您可以使用 generateContent() 從含有文字的提示生成文字:

Kotlin

// Imports + initialization of Gemini API backend service + creation of model instance

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

// Imports + initialization of Gemini API backend service + creation of model instance

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

請注意,Firebase AI Logic 也支援使用 generateContentStream (而非 generateContent) 串流傳輸文字回應。

根據文字和圖片 (多模態) 輸入內容生成文字

試用這個範例前,請務必完成本指南的「入門」一節。

你可以使用 generateContent() 從提示生成文字,提示中包含文字和最多一個圖片檔 (僅限點陣圖),並提供每個輸入檔案的 mimeType 和檔案本身。

Kotlin

// Imports + initialization of Gemini API backend service + creation of model instance

// Loads an image from the app/res/drawable/ directory
val bitmap: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.sparky)

// Provide a prompt that includes the image specified above and text
val prompt = content {
  image(bitmap)
  text("What developer tool is this mascot from?")
}

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

Java

// Imports + initialization of Gemini API backend service + creation of model instance

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sparky);

// Provide a prompt that includes the image specified above and text
Content content = new Content.Builder()
        .addImage(bitmap)
        .addText("What developer tool is this mascot from?")
        .build();

// To generate text output, call generateContent with the prompt
ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
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);

請注意,Firebase AI Logic 也支援使用 generateContentStream (而非 generateContent) 串流文字回覆。

你還可以做些什麼?

您可以為混合式體驗使用各種額外的設定選項和功能:

裝置端推論功能尚未開放

由於是實驗版本,裝置端推論功能無法使用雲端模型的所有功能。下列功能尚未支援裝置端推論 (但通常支援雲端式推論)。

  • 正在產生圖片

    • 可以改用雲端代管模型,但 ONLY_ON_DEVICE 模式會擲回例外狀況。
  • 從點陣圖 (載入記憶體的圖片) 以外的圖片檔輸入類型生成文字

    • 可以改用雲端代管模型,但 ONLY_ON_DEVICE 模式會擲回例外狀況。
  • 從僅含圖片的檔案輸入內容生成文字。如要進行裝置端推論,您必須在多模態要求中提供文字。

    • 可以改用雲端代管模型,但 ONLY_ON_DEVICE 模式會擲回例外狀況。
  • 根據多個圖片檔輸入內容生成文字

    • 可改用雲端託管模型,但 ONLY_ON_DEVICE 模式會擲回例外狀況。
  • 依據輸入的音訊、影片和文件 (例如 PDF) 生成文字

    • 可改用雲端代管模型,但 ONLY_ON_DEVICE 模式會擲回例外狀況。
  • 在多模態要求中使用網址提供檔案。如要進行裝置端推論,您必須以點陣圖形式提供單一圖片。

    • 如果使用 fileData (FileDataPart) 提供檔案網址,系統可能會改用雲端託管模型 (ONLY_ON_DEVICE 模式會擲回例外狀況)。
    • 如果直接在文字提示詞中嵌入網址,系統不會自動改用雲端託管模型 (裝置端模型會忽略嵌入的網址)。
  • 傳送超過 4,000 個詞元的 要求 (約 3,000 個英文字)

    • 可改用雲端託管模型,但 ONLY_ON_DEVICE 模式會擲回例外狀況。
  • 多輪對話

    • 不會自動切換至雲端託管模型 (裝置端推論會將提示記錄串連成單一文字提示詞;由於裝置端模型不會區分角色,並將記錄視為單一訊息,因此精確度不如雲端託管模型)。
    • 如要使用多輪對話,建議採用 ONLY_IN_CLOUD 模式。
  • 提供工具,協助模型生成回覆 (例如呼叫函式、執行程式碼、網址背景資訊、使用 Google Search 建立基準,以及使用 Google Maps 建立基準)

    • 不會自動改用雲端代管模型。如要使用工具,建議使用 ONLY_IN_CLOUD 模式。

Firebase 控制台中的 AI monitoring 功能不會顯示任何裝置端推論資料 (包括裝置記錄)。不過,任何使用雲端託管模型的推論,都可以像其他推論一樣,透過 Firebase AI Logic 監控。

其他限制

除了上述限制外,裝置端推論還有下列限制 (詳情請參閱 ML Kit 說明文件):

  • 應用程式使用者必須使用支援的裝置,才能在裝置端執行推論。

  • 應用程式只能在前景執行裝置端推論。

  • 目前僅驗證過英文和韓文的裝置端推論。

  • 整個裝置端推論要求的權杖上限為 4,000 個。如果要求可能超過這項限制,請務必設定可使用雲端託管模型的推論模式。

  • 建議您避免使用需要長輸出內容 (超過 256 個權杖) 的裝置端推論用例。

  • AICore (管理裝置端模型的 Android 系統服務) 會為每個應用程式強制執行推論配額。如果在短時間內發出過多 API 要求,系統會傳回 ErrorCode.BUSY 回應。如果收到這項錯誤,建議您使用指數輪詢重試要求。此外,如果應用程式超過長期配額 (例如每日配額),系統也會傳回 ErrorCode.PER_APP_BATTERY_USE_QUOTA_EXCEEDED。


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