在 Web 应用中利用设备端模型和云端托管模型打造混合体验

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

本页介绍了如何开始使用客户端 SDK。完成此标准设置后,请查看其他配置选项和功能(例如结构化输出)。

请注意,在桌面版 Chrome 上运行的 Web 应用支持设备端推理。

跳转到代码示例

推荐的使用场景和支持的功能

推荐的使用场景:

  • 使用设备端模型进行推理具有以下优势:

    • 隐私保护更完善
    • Local Context
    • 免费推理
    • 离线功能
  • 使用混合功能可带来以下好处:

    • 无论设备端模型是否可用或是否连接到互联网,都能覆盖 100% 的受众群体

设备端推理支持的功能和特性:

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

您还可以生成结构化输出,包括 JSON 和枚举。

准备工作

请注意以下几点:

  • 使用设备端模型进行推理时,会使用 Chrome 的 Prompt API;而使用云托管模型进行推理时,会使用您选择的 Gemini API 提供方(Gemini Developer API 或 Agent Platform Gemini API (formerly Vertex AI))。

  • 本页面介绍了如何开始使用 localhost 进行开发(如需详细了解如何在 localhost 上使用 API,请参阅 Chrome 文档)。

    完成此标准设置后,请查看其他配置选项和功能(例如结构化输出)。

在 localhost 上开始

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

第 1 步:设置 Chrome 和 Prompt API 以进行设备端推理

  1. 请确保您使用的是最新版 Chrome。在 chrome://settings/help 中更新。
    Chrome 139 及更高版本支持设备端推理。

  2. 通过将以下标志设置为已启用,启用设备端多模态模型:

    • chrome://flags/#prompt-api-for-gemini-nano-multimodal-input
  3. 重启 Chrome。

  4. (可选)在发出第一个请求之前下载设备端模型。

    Prompt API 已内置于 Chrome 中,但设备端模型默认不可用。如果您在首次请求设备端推理之前尚未下载模型,则该请求会自动在后台启动模型下载。

第 2 步:设置 Firebase 项目并将您的应用连接到 Firebase

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

  2. 在 Firebase 控制台中,依次前往 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 和关联服务。

    工作流的这一阶段会自动 为 AI Logic 强制执行 Firebase App Check, 这是一项关键服务,可在从应用直接访问 时帮助保护 Gemini API。在开始使用时(请参阅本指南后面 的步骤),您需要为本地开发配置 App Check 调试提供程序 ,以便在强制执行 App Check 时使用。

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

第 3 步:添加 SDK

Firebase 库提供了用于与生成模型交互的 API。该库包含在 Firebase JavaScript SDK for Web 中。

  1. 使用 npm 安装 Firebase JS SDK for Web:

    npm install firebase
    
  2. 在您的应用中初始化 Firebase:

    import { initializeApp } from "firebase/app";
    import { initializeAppCheck } 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);
    

第 4 步:为本地开发配置 App Check 调试提供程序

在控制台中,作为 AI Logic 引导式设置工作流的一部分,系统会自动强制执行 Firebase App Check,以保护 Gemini API。 对于本地开发,您需要配置 App Check 调试提供程序,以绕过证明,同时仍保持 App Check 的强制执行。

如需在从 localhost 以交互方式运行应用时(例如在本地开发期间)使用调试提供程序,请执行以下操作:

  1. 在调试 build 中,请在初始化 App Check 之前将 self.FIREBASE_APPCHECK_DEBUG_TOKEN 设置为 true 以启用调试模式。例如:

    self.FIREBASE_APPCHECK_DEBUG_TOKEN = true;
    initializeAppCheck(firebaseApp, { /* App Check options */ });
    
  2. 在本地访问 Web 应用,然后打开浏览器的开发者工具。在调试控制台中,您将看到一个调试令牌:

    AppCheck debug token: "123a4567-b89c-12d3-e456-789012345678".
    You will need to safelist it in the Firebase console for it to work.
    
  3. 向 App Check 注册调试令牌:

    1. 在 Firebase 控制台中,前往安全性 > App Check > 应用标签页。

    2. 找到您的应用,点击溢出菜单 (),然后选择管理调试令牌。

    3. 按照屏幕上的说明注册调试令牌。

如需详细了解调试提供程序(包括如何获取新的调试令牌),请参阅官方 App Check 文档。

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

点击您的 Gemini API 提供商,以查看此页面上特定于提供商的内容和代码。

在向模型发送提示请求之前,请先完成以下设置:

  1. 为您选择的 API 提供方初始化服务。

  2. 创建一个 GenerativeModel 实例。请务必将 mode 设置为以下值之一:

    • PREFER_ON_DEVICE:使用设备端模型(如果可用);否则,回退到云托管模型。

    • ONLY_ON_DEVICE:如果设备端模型可用,则使用该模型;否则,抛出异常。

    • PREFER_IN_CLOUD:使用云托管模型(如果可用);否则,回退到设备端模型。

    • ONLY_IN_CLOUD:使用云托管模型(如果可用);否则,抛出异常。

import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend, InferenceMode } 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
// Set the mode (for example, use the on-device model if it's available)
const model = getGenerativeModel(ai, { mode: InferenceMode.PREFER_ON_DEVICE });

第 6 步:初始化设备端模型

您必须在最终用户与页面互动(例如点击按钮)之后或期间,以及向模型发送提示请求之前,调用 initializeDeviceModel()。如需详细了解用户激活要求,请参阅 Chrome 文档。

import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend, InferenceMode } 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
// Set the mode (for example, use the on-device model if it's available)
const model = getGenerativeModel(ai, { mode: InferenceMode.PREFER_ON_DEVICE });

// `initializeDeviceModel` must be called:
// (1) after or on an end-user page interaction such as a button click
// and
// (2) before any queries to the model (such as `generateContent()`)
// You may want to `await` this promise if using `ONLY_ON_DEVICE` (see note below).
model.initializeDeviceModel((val) =>
  // Example: "Download progress: 72.62%""
  console.log(`Download progress: ${Math.round(val*10000) / 100}%`)
);

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

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

如果您想生成结构化输出(例如 JSON 或枚举),请使用以下“生成文本”示例之一,并将模型配置为根据提供的架构进行回答。

根据纯文本输入生成文本

在尝试此示例之前,请确保您已完成本指南的入门部分。

您可以使用 generateContent() 根据包含文本的提示生成文本:

// Imports + initialization of FirebaseApp and backend service + creation of model instance

// Wrap in an async function so you can use await
async function run() {
  // Provide a prompt that contains text
  const prompt = "Write a story about a magic backpack."

  // To generate text output, call `generateContent` with the text input
  const result = await model.generateContent(prompt);

  const response = result.response;
  const text = response.text();
  console.log(text);
}

run();

请注意,Firebase AI Logic 还支持使用 generateContentStream(而不是 generateContent)流式传输文本回答。

根据文本和图片(多模态)输入生成文本

在尝试此示例之前,请确保您已完成本指南的入门部分。

您可以使用 generateContent() 根据包含文本和图片文件的提示生成文本,并提供每个输入文件的 mimeType 和文件本身。

设备端推理支持的输入图片类型为 PNG 和 JPEG。

// Imports + initialization of FirebaseApp and backend service + creation of model instance

// Converts a File object to a Part object.
async function fileToGenerativePart(file) {
  const base64EncodedDataPromise = new Promise((resolve) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result.split(',')[1]);
    reader.readAsDataURL(file);
  });
  return {
    type: "inlineData",
    inlineData: { data: await base64EncodedDataPromise, mimeType: file.type },
  };
}

async function run() {
  // Provide a text prompt to include with the image
  const prompt = "Write a poem about this picture:";

  const fileInputEl = document.querySelector("input[type=file]");
  const imagePart = await fileToGenerativePart(fileInputEl.files[0]);

  // To generate text output, call `generateContent` with the text and image
  const result = await model.generateContent([prompt, imagePart]);

  const response = result.response;
  const text = response.text();
  console.log(text);
}

run();

请注意,Firebase AI Logic 还支持使用 generateContentStream(而不是 generateContent)流式传输文本回答。

你还可以做些什么?

您可以为混合体验使用各种其他配置选项和功能:

设备端推理尚不支持的功能

并非 Web SDK 的所有功能都可用于设备端推理。设备端推理尚不支持以下功能(但这些功能通常可用于基于云的推理)。

  • 从 JPEG 和 PNG 以外的图片文件输入类型生成文本

    • 可以回退到云托管模型;但是,ONLY_ON_DEVICE 模式会抛出错误。
  • 根据输入的音频、视频和文档(例如 PDF)生成文本

    • 可以回退到云托管模型;但是,ONLY_ON_DEVICE 模式会抛出错误。
  • 使用 Gemini Nano Banana 模型生成图片

    • 可以回退到云托管模型;但是,ONLY_ON_DEVICE 模式会抛出错误。
  • 在多模态请求中使用网址提供文件。您必须以 内嵌数据的形式向设备端模型提供文件。

  • 多轮对话

    • 可以回退到云托管模型;但是,ONLY_ON_DEVICE 模式会抛出错误。
  • 使用 Gemini Live API 进行双向流式传输

  • 为模型提供工具,帮助其生成回答(例如函数调用、代码执行、网址上下文、依托 Google Search 进行接地以及依托 Google Maps 进行接地)

  • 统计 token 数量

    • 始终抛出错误。云托管模型和设备端模型的计数会有所不同,因此没有直观的后备方案。
  • Firebase 控制台中的 AI 监控功能,用于监控设备端推理。

    • 请注意,使用云托管模型的任何推理都可以像使用 Firebase AI Logic 客户端 Web SDK 的其他推理一样进行监控。


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