在網頁應用程式中,為混合式體驗生成結構化輸出內容

Gemini 模型預設會以非結構化文字的形式回覆。 不過,部分用途需要結構化文字,例如 JSON。舉例來說,您可能會將回覆用於其他需要建立資料結構定義的下游工作。

為確保模型生成的輸出內容一律符合特定結構定義,您可以定義結構定義,做為模型回覆的藍圖。然後直接從模型輸出內容擷取資料,減少後續處理作業。

例如:

  • 確保模型回覆會產生有效的 JSON,並符合您提供的結構定義。
    舉例來說,模型可以生成食譜的結構化項目,其中一律包含食譜名稱、食材清單和步驟。這樣一來,您就能更輕鬆地在應用程式的 UI 中剖析及顯示這項資訊。

  • 限制模型在分類工作中的回應方式。
    舉例來說,您可以讓模型使用特定標籤集 (例如一組特定的列舉,如 positivenegative) 註解文字,而不是模型產生的標籤 (這類標籤可能具有一定程度的變異性,例如 goodpositivenegativebad)。

本頁說明如何在網頁應用程式的混合式體驗中產生結構化輸出內容 (例如 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
    }
  }
});

// ...