在 Android 应用中构建混合体验,使用设备端模型和云端托管模型


您可以使用混合推理构建 AI 赋能的 Android 应用和功能,并使用 Firebase AI Logic。混合推理支持在设备端模型可用时使用该模型运行推理,否则无缝回退到云端托管模型(反之亦然)。

本页面介绍了如何 开始使用客户端 SDK, 并展示了 其他配置选项和功能, 例如温度。

请注意,Firebase AI Logic支持通过设备端推理在特定设备上运行的 Android 应用,并且受机器学习套件条款以及机器学习套件生成式 AI 方面的特定条款的约束。

推荐的用例和支持的功能

推荐的用例

  • 使用设备端模型进行推理 可提供:

    • 增强的隐私保护
    • 本地环境
    • 免费推理
    • 离线功能
  • 使用混合 功能可提供:

    • 通过适应设备端模型的可用性和互联网连接来覆盖更多受众群体

设备端推理支持的功能

设备端推理仅支持单轮文本生成(而非聊天) ,并提供流式或非流式输出。 它支持以下文本生成功能:

  • 根据纯文本输入生成文本

  • 根据文本和图片输入生成文本,具体来说 ,是将单个位图图片作为输入

请务必查看本页底部尚未提供的设备端推理功能列表。

准备工作

请注意以下几点:

支持的 Android 设备及其设备端模型

对于设备端推理(使用机器学习套件中的 Prompt API),您 可以在 机器学习套件文档中找到支持的设备及其设备端模型 列表。

开始使用

这些入门步骤介绍了您要发送的任何受支持的提示请求所需的一般设置。

第 1 步:设置 Firebase 项目并将应用连接到 Firebase

  1. 登录 Firebase 控制台, 然后选择您的 Firebase 项目。

  2. Firebase 控制台中,依次前往 AI 服务 > AI Logic

  3. 点击开始使用 ,启动引导式工作流,帮助您为项目设置 所需的 API 和资源。

  4. 设置项目以使用“Gemini API”提供方。

    我们建议您先使用 Gemini Developer API 您可以随时 设置 Vertex AI Gemini API (及其结算要求)。

    对于 Gemini Developer API,控制台将在您的项目中启用所需的 API 并创建一个 Gemini API 密钥。
    请勿将此 Gemini API 密钥添加到应用的代码库中。
    了解详情。

  5. 如果控制台的工作流中出现提示,请按照屏幕上的说明注册您的应用并将其连接到 Firebase。

  6. 继续执行本指南中的下一步,将 SDK 添加到您的应用。

第 2 步:添加所需的 SDK

The Firebase AI Logic SDK for Android (firebase-ai) 以及 Firebase AI Logic On-Device SDK (firebase-ai-ondevice) 提供对 API 的访问权限,以便与生成式模型进行交互。

在您的模块(应用级)Gradle 文件 (例如 <project>/<app-module>/build.gradle.kts)中,添加适用于 Android 的 Firebase AI Logic 库的依赖项:

Kotlin

dependencies {
  // ... other androidx dependencies

  // Add the dependencies for the Firebase AI Logic libraries
  // Note that the on-device SDK is not yet included in the Firebase Android BoM
  implementation("com.google.firebase:firebase-ai:17.11.0")
  implementation("com.google.firebase:firebase-ai-ondevice:16.0.0-beta01")
}

Java

对于 Java,您需要添加两个额外的库。

dependencies {
  // ... other androidx dependencies

  // Add the dependencies for the Firebase AI Logic libraries
  // Note that the on-device SDK is not yet included in the Firebase Android BoM
  implementation("com.google.firebase:firebase-ai:17.11.0")
  implementation("com.google.firebase:firebase-ai-ondevice:16.0.0-beta01")

  // 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 步:检查设备端模型是否可用

使用 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()。 这会将设备端模型加载到内存中并初始化运行时组件。

第 4 步:初始化服务并创建模型实例

点击您的 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);

第 5 步:向模型发送提示请求

本部分介绍了如何发送各种类型的输入以生成不同类型的输出,包括:

根据纯文本输入生成文本

在试用此示例之前,请确保您已完成本指南的 开始使用部分。

您可以使用 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 个 token(或大约 3,000 个英语单词)的请求。

  • 多轮对话

  • 向模型提供工具以帮助其生成响应(例如函数调用、代码执行、网址上下文以及依托 Google 搜索进行接地)

Firebase 控制台中的 AI 监控不会显示任何 设备端推理数据(包括设备端日志)。不过,任何使用 云端托管模型的推理都可以像其他通过 Firebase AI Logic进行的推理一样受到监控。

其他限制

除了上述限制之外,设备端推理还有以下 限制 __(如需了解详情,请参阅 机器学习套件文档):

  • 您的应用的最终用户必须使用 支持设备 端推理的设备。

  • 您的应用只能在前台运行时运行设备端推理。

  • 设备端推理仅验证了英语和韩语。

  • 整个设备端推理请求的 token 上限为 4,000 个 token。如果您的请求可能会超出此限制,请务必配置可以使用云端托管模型的推理模式。

  • 我们建议避免使用需要长输出(超过 256 个 token)的设备端推理用例。

  • AICore (一项用于管理设备端模型的 Android 系统服务)会为每个应用强制执行 推理配额。在短时间内发出过多 API 请求 会导致 ErrorCode.BUSY 响应。如果您收到此错误,请考虑使用指数退避算法重试请求。此外,如果应用超出长时间配额(例如每日配额),则可能会返回 ErrorCode.PER_APP_BATTERY_USE_QUOTA_EXCEEDED


提供反馈 有关您的使用体验Firebase AI Logic