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

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

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

以下是一些範例用途:

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

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

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

本範例使用 Schema 輔助方法 (例如 Schema.objectSchema.arraySchema.stringSchema.number),這些方法由 Firebase AI Logic SDK 提供,用於定義物件結構定義。

試用這個範例前,請先完成本指南的「事前準備」一節,設定專案和應用程式。
在該節中,您也會點選所選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 的使用體驗意見回饋