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

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

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

下面是一些示例:

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

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

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

准备工作

请确保您已完成混合体验构建入门指南

设置结构化输出的配置

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

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

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

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

JSON 输出

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

示例 1:使用 Firebase Schema 辅助方法

此示例使用 Firebase AI Logic SDK 提供的辅助方法来使架构定义更紧凑。

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

// This schema can also be defined as a plain JSON object.
// See next snippet for an example of a plain JSON schema.
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: {
      model: "gemini-3.1-flash-lite",
      responseMimeType: "application/json",
      responseSchema: jsonSchema
    },
  }
  onDeviceParams: {
    promptOptions: {
      responseConstraint: jsonSchema
    }
  }
});

const result = await model
  .generateContent(
    "Create profiles for some characters for a fantasy story.");

console.log(result.response.text());
console.log(JSON.parse(result.response.text()));

// ...

示例 2:使用纯 JSON 架构

此示例仅使用 JSON 定义架构,并返回相同的结果。

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

// The JSON schema defined as a plain JSON object.
const jsonSchema = {
    "type": "object",
    "properties": {
        "characters": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "name": {
                        "type": "string",
                        "nullable": false
                    },
                    "accessory": {
                        "type": "string",
                        "nullable": false
                    },
                    "age": {
                        "type": "number",
                        "nullable": false
                    },
                    "species": {
                        "type": "string",
                        "nullable": false
                    }
                },
                "nullable": false,
                "required": [
                    "name",
                    "age",
                    "species"
                ]
            },
            "nullable": false
        }
    },
    "nullable": false,
    "required": [
        "characters"
    ]
};

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

const result = await model
  .generateContent(
    "Create profiles for some characters for a fantasy story.");

console.log(result.response.text());
console.log(JSON.parse(result.response.text()));

枚举输出

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

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

// enumSchema can also be defined as a plain JSON schema instead of
// using the `Schema` helper methods, just as in the JSON output example.
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
    }
  }
});

// ...