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

Gemini 模型預設會以非結構化文字的形式傳回回覆。不過,某些用途需要結構化文字 (例如 JSON 或列舉)。舉例來說,您可能需要使用回應來執行其他下游工作,而這些工作需要既定的資料結構定義。

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

以下是一些範例用途:

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

  • 限制模型在分類任務中的回應方式。
    舉例來說,您可以讓模型使用一組特定標籤 (例如 positive 和 negative 等特定列舉) 為文字加上註解,而不是使用模型產生的標籤 (可能會有 good、positive、negative 或 bad 等變化)。

本頁說明如何在網頁應用程式的混合式體驗中,生成結構化輸出內容 (例如 JSON 和列舉)。

跳至 JSON 輸出內容 跳至列舉輸出內容

結構化輸出內容的設定

使用雲端託管和裝置端模型進行推論時,可生成結構化輸出內容 (例如 JSON 和列舉)。

  • 混合推論模式:同時設定 inCloudParams 和 onDeviceParams,無論推論是在雲端或裝置端執行,模型都會以結構化輸出內容回覆:

    • 裝置端模型:使用 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.object、Schema.array、Schema.string 和 Schema.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)。

在這些範例的情境中,模型會從預先定義的允許選項清單 (drama、comedy 或 documentary) 中選取單一類型,藉此分類電影說明。

您可以使用下列任一方法定義回覆結構定義:

  • 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」使用體驗的意見回饋