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


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

本頁面說明如何開始使用用戶端 SDK,並介紹其他設定選項和功能,例如溫度。

請注意,使用 Firebase AI Logic SDK v17.10.0 以上版本 (BoM v34.10.0 以上版本) 的 Android 應用程式,必須在特定裝置上執行,才能透過 Firebase AI Logic 進行裝置端推論。這項功能受機器學習套件條款機器學習套件生成式 AI 相關條款規範。

建議用途和支援的功能

建議用途

  • 使用裝置端模型進行推論的優點:

    • 強化隱私權
    • 查看當地特色
    • 免付費推論
    • 離線功能
  • 使用混合功能提供:

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

支援的裝置端推論功能

裝置端推論僅支援單輪文字生成 (支援對話),支援的文字生成功能如下:

請務必查看本頁面底部的裝置端推論功能清單

事前準備

請注意下列事項:

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

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

開始使用

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

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

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

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

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

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

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

    您隨時可以設定Vertex AI Gemini API(以及帳單相關規定)。

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

    自 2026 年 7 月初起,工作流程的此階段會自動強制執行Firebase App CheckAI 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 LogicApp 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:17.13.0")
  implementation("com.google.firebase:firebase-ai-ondevice:16.0.0-beta03")
  implementation("com.google.firebase:firebase-appcheck-debug:19.2.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:17.13.0")
  implementation("com.google.firebase:firebase-ai-ondevice:16.0.0-beta03")
  implementation("com.google.firebase:firebase-appcheck-debug:19.2.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 月初起,在 Play 管理中心的引導式設定工作流程中,系統會自動強制執行 AI LogicFirebase 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 and downloading 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 系統服務) 會為您管理下載的模型和版本,並保持模型更新等。請注意,裝置只會下載一個模型,因此如果裝置上的其他應用程式先前已成功下載裝置端模型,這項檢查就會傳回模型可用的結果。

延遲時間最佳化

如要針對第一次推論呼叫進行最佳化,您可以讓應用程式呼叫 warmup()。這會將裝置端模型載入記憶體,並初始化執行階段元件。

步驟 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 = "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(
        "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_IN_CLOUD 推論模式,獲得更一致的體驗。

  • 生成結構化輸出內容 (例如 JSON 或列舉)

  • 從點陣圖以外的圖片檔輸入類型生成文字 (載入記憶體的圖片)

  • 從多個圖片檔生成文字

  • 從音訊、影片和文件 (例如 PDF) 輸入內容生成文字

  • 使用 GeminiImagen 模型生成圖片

  • 在多模態要求中,使用網址提供檔案。您必須以內嵌資料的形式,將檔案提供給裝置端模型

  • 傳送超過 4,000 個權杖的要求 (或大約 3,000 個英文字)。

  • 多輪對話

  • 提供工具給模型,協助生成回應 (例如函式呼叫、程式碼執行、網址內容、以 Google Search 為基礎和以 Google Maps 為基礎)

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

其他限制

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

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

  • 應用程式只能在前景執行時,在裝置上執行推論作業。

  • 只有英文和韓文經過驗證,可進行裝置端推論。

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

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

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


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