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

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

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

以下是一些示例用例:

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

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

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

跳转到 JSON 输出 跳转到枚举输出

结构化输出的配置

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

  • 混合推理模式:同时配置 inCloudParamsonDeviceParams,以便模型以结构化输出进行回答,无论推理是在云端还是在设备上运行:

    • 对于设备端模型:使用通过 Schema 辅助方法创建的架构或纯 JSON 架构,在 onDeviceParams 中指定 responseConstraint

    • 对于云端托管的模型:在 inCloudParams 中指定 responseMimeType(JSON 为 application/json,枚举为 text/x.enum)和 responseSchema

  • 非混合推理模式:仅使用上述适用的配置。

准备工作

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

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


跳转到 JSON 输出 跳转到枚举输出

JSON 输出

以下示例调整了常规 JSON 输出示例,以适应混合推理(例如 PREFER_ON_DEVICE)。

在这些示例的场景中,模型会生成一个奇幻故事的角色资料列表,其中包含名称、年龄、种族和可选配件等结构化属性。

您可以使用以下任一方法定义回答架构

  • Firebase Schema 辅助方法 (推荐):使用辅助方法(例如 Schema.object()Schema.enumString())直接在代码中编写简洁紧凑的架构,而无需额外的样板代码。

  • 纯 JSON 架构:如果您已有架构定义、要在不同平台或后端服务之间共享架构,或者要从 JSON 文件导入架构,请使用标准 JSON 架构对象。

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

此示例使用 Firebase AI Logic SDK 提供的 Schema 辅助方法(例如 Schema.objectSchema.arraySchema.stringSchema.number)来定义对象架构。

在试用此示例之前,请完成本指南的准备工作部分,以设置您的项目和应用。
在该部分中,您还需要点击所选Gemini API提供商对应的按钮,以便在此页面上看到特定于提供商的内容

import { initializeApp } from "firebase/app";
import {
  getAI,
  getGenerativeModel,
  GoogleAIBackend,
  InferenceMode,
  Schema
} 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() });

// Define a schema using the `Schema` helper methods.
// Optional properties are specified in optionalProperties.
const jsonSchema = Schema.object({
  properties: {
    characters: Schema.array({
      items: Schema.object({
        properties: {
          name: Schema.string(),
          age: Schema.number(),
          species: Schema.string(),
          accessory: Schema.string()
        },
        optionalProperties: ["accessory"]
      })
    })
  }
});

// Create a GenerativeModel instance configured to use a hybrid inference mode (like PREFER_ON_DEVICE).
const model = getGenerativeModel(ai, {
  mode: InferenceMode.INFERENCE_MODE,
  // For cloud-hosted models, specify MIME type and response schema.
  inCloudParams: {
    model: "CLOUD_MODEL_NAME",
    generationConfig: {
      responseMimeType: "application/json",
      responseSchema: jsonSchema
    }
  },
  // For on-device models, pass the schema as the response constraint.
  onDeviceParams: {
    promptOptions: {
      responseConstraint: jsonSchema
    }
  }
});

const prompt = "Create profiles for some characters for a fantasy story.";

// Generate the structured output.
const result = await model.generateContent(prompt);

// Access the generated JSON string conforming to the schema from response.text().
console.log(result.response.text());

// Parse the JSON string into a JavaScript object.
console.log(JSON.parse(result.response.text()));

示例 2:使用纯 JSON 架构

此示例仅使用 JSON 定义架构。

在试用此示例之前,请完成本指南的准备工作部分,以设置您的项目和应用。
在该部分中,您还需要点击所选Gemini API提供商对应的按钮,以便在此页面上看到特定于提供商的内容

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() });

// Define the schema as a plain JSON object.
// Properties are required by default unless omitted from the required array.
const jsonSchema = {
  type: "object",
  properties: {
    characters: {
      type: "array",
      items: {
        type: "object",
        properties: {
          name: {
            type: "string",
            nullable: false
          },
          age: {
            type: "number",
            nullable: false
          },
          species: {
            type: "string",
            nullable: false
          },
          accessory: {
            type: "string",
            nullable: true
          }
        },
        nullable: false,
        required: [
          "name",
          "age",
          "species"
        ]
      },
      nullable: false
    }
  },
  nullable: false,
  required: [
    "characters"
  ]
};

// Create a GenerativeModel instance configured to use a hybrid inference mode (like PREFER_ON_DEVICE).
const model = getGenerativeModel(ai, {
  mode: InferenceMode.INFERENCE_MODE,
  // For cloud-hosted models, specify MIME type and response schema.
  inCloudParams: {
    model: "CLOUD_MODEL_NAME",
    generationConfig: {
      responseMimeType: "application/json",
      responseSchema: jsonSchema
    }
  },
  // For on-device models, pass the schema as the response constraint.
  onDeviceParams: {
    promptOptions: {
      responseConstraint: jsonSchema
    }
  }
});

const prompt = "Create profiles for some characters for a fantasy story.";

// Generate the structured output.
const result = await model.generateContent(prompt);

// Access the generated JSON string conforming to the schema from response.text().
console.log(result.response.text());

// Parse the JSON string into a JavaScript object.
console.log(JSON.parse(result.response.text()));

枚举输出

以下示例调整了常规枚举输出示例,以适应混合推理(例如 PREFER_ON_DEVICE)。

在这些示例的场景中,模型通过从预定义的允许选项列表(dramacomedydocumentary)中选择单个类型来对电影说明进行分类。

您可以使用以下任一方法定义回答架构

  • Firebase Schema 辅助方法 (推荐):使用辅助方法(例如 Schema.object()Schema.enumString())直接在代码中编写简洁紧凑的架构,而无需额外的样板代码。

  • 纯 JSON 架构:如果您已有架构定义、要在不同平台或后端服务之间共享架构,或者要从 JSON 文件导入架构,请使用标准 JSON 架构对象。

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

此示例使用 Firebase AI Logic SDK 提供的 Schema.enumString 辅助方法来定义允许的枚举值。

在试用此示例之前,请完成本指南的准备工作部分,以设置您的项目和应用。
在该部分中,您还需要点击所选Gemini API提供商对应的按钮,以便在此页面上看到特定于提供商的内容

import { initializeApp } from "firebase/app";
import {
  getAI,
  getGenerativeModel,
  GoogleAIBackend,
  InferenceMode,
  Schema
} 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() });

// Define an enum schema using the `Schema` helper method with allowed string values.
const enumSchema = Schema.enumString({
  enum: ["drama", "comedy", "documentary"]
});

// Create a GenerativeModel instance configured to use a hybrid inference mode (like PREFER_ON_DEVICE).
const model = getGenerativeModel(ai, {
  mode: InferenceMode.INFERENCE_MODE,
  // For cloud-hosted models, specify MIME type and response schema.
  inCloudParams: {
    model: "CLOUD_MODEL_NAME",
    generationConfig: {
      responseMimeType: "text/x.enum",
      responseSchema: enumSchema
    }
  },
  // For on-device models, pass the enum schema as the response constraint.
  onDeviceParams: {
    promptOptions: {
      responseConstraint: enumSchema
    }
  }
});

const prompt = `The film aims to educate and inform viewers about real-life
subjects, events, or people. It offers a factual record of a particular topic
by combining interviews, historical footage, and narration. The primary purpose
of a film is to present information and provide insights into various aspects
of reality.`;

// Generate the structured enum output.
const result = await model.generateContent(prompt);

// Access the selected enum value string from response.text().
console.log(result.response.text());

示例 2:使用纯 JSON 架构

此示例仅使用 JSON 定义了枚举架构。

在试用此示例之前,请完成本指南的准备工作部分,以设置您的项目和应用。
在该部分中,您还需要点击所选Gemini API提供商对应的按钮,以便在此页面上看到特定于提供商的内容

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() });

// Define the enum schema as a plain JSON object.
const enumSchema = {
  type: "string",
  enum: ["drama", "comedy", "documentary"]
};

// Create a GenerativeModel instance configured to use a hybrid inference mode (like PREFER_ON_DEVICE).
const model = getGenerativeModel(ai, {
  mode: InferenceMode.INFERENCE_MODE,
  // For cloud-hosted models, specify MIME type and response schema.
  inCloudParams: {
    model: "CLOUD_MODEL_NAME",
    generationConfig: {
      responseMimeType: "text/x.enum",
      responseSchema: enumSchema
    }
  },
  // For on-device models, pass the enum schema as the response constraint.
  onDeviceParams: {
    promptOptions: {
      responseConstraint: enumSchema
    }
  }
});

const prompt = `The film aims to educate and inform viewers about real-life
subjects, events, or people. It offers a factual record of a particular topic
by combining interviews, historical footage, and narration. The primary purpose
of a film is to present information and provide insights into various aspects
of reality.`;

// Generate the structured enum output.
const result = await model.generateContent(prompt);

// Access the selected enum value string from response.text().
console.log(result.response.text());


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