在 Web 应用中为混合体验生成结构化输出


Gemini 模型默认以非结构化文本的形式返回回答。 不过,有些使用情形需要结构化文本,例如 JSON。例如,您可能正在将响应用于需要已建立数据架构的其他下游任务。

为确保模型生成的输出始终遵循特定架构,您可以定义一个架构,该架构类似于模型响应的蓝图。这样一来,您就可以直接从模型的输出中提取数据,而无需进行太多后期处理。

下面是一些示例:

  • 确保模型的回答生成有效的 JSON 并符合您提供的架构。
    例如,该模型可以为食谱生成结构化条目,这些条目始终包含食谱名称、配料列表和步骤。这样一来,您就可以更轻松地在应用的界面中解析和显示此信息。

  • 限制模型在分类任务期间的回答方式。
    例如,您可以让模型使用一组特定的标签(例如一组特定的枚举,如 positivenegative)来注释文本,而不是使用模型生成的标签(这些标签可能具有一定程度的变异性,如 goodpositivenegativebad)。

本页介绍了如何在 Web 应用的混合体验中生成结构化输出(例如 JSON 和枚举)。

准备工作

请确保您已完成打造混合体验入门指南

设置结构化输出的配置

使用云端托管模型和设备端模型进行推理时,支持生成结构化输出(例如 JSON 和枚举)。

对于混合推理,请同时使用 inCloudParamsonDeviceParams 来配置模型,使其以结构化输出进行回答。对于其他模式,请仅使用适用的配置。

  • 对于 inCloudParams:请指定适当的 responseMimeType(例如 application/json)以及您希望模型使用的 responseSchema

  • 对于 onDeviceParams:指定您希望模型使用的 responseConstraint

JSON 输出

以下示例调整了常规 JSON 输出示例,以适应混合推理(在本示例中为 PREFER_ON_DEVICE):

import {
  getAI,
  getGenerativeModel,
  Schema
} from "firebase/ai";

const jsonSchema = Schema.object({
 properties: {
    characters: Schema.array({
      items: Schema.object({
        properties: {
          name: Schema.string(),
          accessory: Schema.string(),
          age: Schema.number(),
          species: Schema.string(),
        },
        optionalProperties: ["accessory"],
      }),
    }),
  }
});

const model = getGenerativeModel(ai, {
  mode: InferenceMode.PREFER_ON_DEVICE,
  inCloudParams: {
    generationConfig: {
      responseMimeType: "application/json",
      responseSchema: jsonSchema
    },
  }
  onDeviceParams: {
    promptOptions: {
      responseConstraint: jsonSchema
    }
  }
});

// ...

枚举输出

以下示例调整了常规枚举输出示例,以适应混合推理(在本示例中为 PREFER_ON_DEVICE):

import {
  getAI,
  getGenerativeModel,
  Schema
} from "firebase/ai";

const enumSchema = Schema.enumString({
  enum: ["drama", "comedy", "documentary"],
});

const model = getGenerativeModel(ai, {
  mode: InferenceMode.PREFER_ON_DEVICE,
  inCloudParams: {
    generationConfig: {
      responseMimeType: "text/x.enum",
      responseSchema: enumSchema
    },
  }
  onDeviceParams: {
    promptOptions: {
      responseConstraint: enumSchema
    }
  }
});

// ...