透過 Gemini API 產生結構化輸出內容


Gemini 預設會產生非結構化文字,但部分應用程式需要結構化文字。針對這些用途,您可以限制 Gemini 以 JSON 回應,這是一種適合自動處理的結構化資料格式。您也可以限制模型,讓模型以列舉中指定的其中一個選項回應。

以下列舉幾個可能需要模型輸出結構化內容的用途:

  • 從報紙文章中擷取公司資訊,建立公司資料庫。
  • 從履歷中提取標準化資訊。
  • 從食譜中擷取食材,並顯示每項食材的雜貨網站連結。

您可以在提示中要求 Gemini 產生 JSON 格式的輸出內容,但請注意,模型不保證會產生 JSON,而且只會產生 JSON。如要獲得更確定的回應,您可以在 responseSchema 欄位中傳遞特定的 JSON 結構定義,讓 Gemini 一律以預期的結構回應。如要進一步瞭解如何使用結構定義,請參閱「進一步瞭解 JSON 結構定義」。

本指南說明如何透過所選 SDK 使用 generateContent 方法,或直接使用 REST API 產生 JSON。範例顯示僅文字輸入內容,但 Gemini 也能針對包含圖片影片音訊的多模態要求產生 JSON 回應。

事前準備:設定專案和 API 金鑰

在呼叫 Gemini API 之前,您需要設定專案並設定 API 金鑰。

取得並保護 API 金鑰

您需要 API 金鑰才能呼叫 Gemini API。如果還沒有金鑰,請在 Google AI Studio 建立。

取得 API 金鑰

強烈建議您不要將 API 金鑰登錄到版本管控系統。

您應使用密鑰存放區來儲存 API 金鑰,例如 Google Cloud Secret Manager

本教學課程中的所有程式碼片段都假設您是以全域常數的形式存取 API 金鑰。

產生 JSON

當模型設為輸出 JSON 時,它會以 JSON 格式回應任何提示。

您可以提供結構定義來控制 JSON 回應的結構。您可以透過兩種方式向模型提供結構定義:

  • 以提示中的文字形式顯示
  • 透過模型設定提供的結構化結構定義

在提示中以文字形式提供結構定義

以下範例會提示模型以特定 JSON 格式傳回餅乾食譜。

由於模型會從提示中的文字取得格式規格,您可以靈活呈現規格。任何適合用於呈現 JSON 結構定義的合理格式都可能有效。

// Make sure to include these imports:
// import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);

const model = genAI.getGenerativeModel({
  model: "gemini-1.5-flash",
});

const prompt = `List a few popular cookie recipes using this JSON schema:

Recipe = {'recipeName': string}
Return: Array<Recipe>`;

const result = await model.generateContent(prompt);
console.log(result.response.text());

輸出內容可能如下所示:

[{"recipeName": "Chocolate Chip Cookies"}, {"recipeName": "Oatmeal Raisin Cookies"}, {"recipeName": "Snickerdoodles"}, {"recipeName": "Sugar Cookies"}, {"recipeName": "Peanut Butter Cookies"}]

透過模型設定提供結構定義

以下範例會執行下列操作:

  1. 以實例化方式建立透過結構定義設定的模型,以便以 JSON 回應。
  2. 提示模型傳回餅乾食譜。

相較於只依賴提示中的文字,這種宣告 JSON 結構定義的正式方法可讓您更精確地控管。

// Make sure to include these imports:
// import { GoogleGenerativeAI, SchemaType } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);

const schema = {
  description: "List of recipes",
  type: SchemaType.ARRAY,
  items: {
    type: SchemaType.OBJECT,
    properties: {
      recipeName: {
        type: SchemaType.STRING,
        description: "Name of the recipe",
        nullable: false,
      },
    },
    required: ["recipeName"],
  },
};

const model = genAI.getGenerativeModel({
  model: "gemini-1.5-pro",
  generationConfig: {
    responseMimeType: "application/json",
    responseSchema: schema,
  },
});

const result = await model.generateContent(
  "List a few popular cookie recipes.",
);
console.log(result.response.text());

輸出內容可能如下所示:

[{"recipeName": "Chocolate Chip Cookies"}, {"recipeName": "Oatmeal Raisin Cookies"}, {"recipeName": "Snickerdoodles"}, {"recipeName": "Sugar Cookies"}, {"recipeName": "Peanut Butter Cookies"}]

進一步瞭解 JSON 結構定義

將模型設為傳回 JSON 回應時,您可以使用 Schema 物件定義 JSON 資料的形狀。Schema 代表 OpenAPI 3.0 結構定義物件的選取子集。

以下是所有 Schema 欄位的偽 JSON 表示法:

{
  "type": enum (Type),
  "format": string,
  "description": string,
  "nullable": boolean,
  "enum": [
    string
  ],
  "maxItems": string,
  "minItems": string,
  "properties": {
    string: {
      object (Schema)
    },
    ...
  },
  "required": [
    string
  ],
  "propertyOrdering": [
    string
  ],
  "items": {
    object (Schema)
  }
}

結構定義的 Type 必須是 OpenAPI 的資料類型之一。每個 Type 只支援部分欄位。以下清單將每個 Type 對應至該類型的有效欄位:

  • string -> enum, 格式
  • integer -> 格式
  • number -> 格式
  • boolean
  • array -> minItems、maxItems、items
  • object -> properties, required, propertyOrdering, nullable

以下是顯示有效類型和欄位組合的範例結構定義:

{ "type": "string", "enum": ["a", "b", "c"] }

{ "type": "string", "format": "date-time" }

{ "type": "integer", "format": "int64" }

{ "type": "number", "format": "double" }

{ "type": "boolean" }

{ "type": "array", "minItems": 3, "maxItems": 3, "items": { "type": ... } }

{ "type": "object",
  "properties": {
    "a": { "type": ... },
    "b": { "type": ... },
    "c": { "type": ... }
  },
  "nullable": true,
  "required": ["c"],
  "propertyOrdering": ["c", "b", "a"]
}

如需結構定義欄位在 Gemini API 中使用的完整說明文件,請參閱結構定義參考資料

資源排序

在 Gemini API 中使用 JSON 結構定義時,屬性順序非常重要。根據預設,API 會依照字母順序排列屬性,且不會保留屬性定義的順序 (不過,Google Gen AI SDK 可能會保留這個順序)。如果您為已設定結構定義的模型提供範例,而範例的屬性順序與結構定義的屬性順序不一致,輸出結果可能會雜亂或不符合預期。

為確保屬性排序一致且可預測,您可以使用選用的 propertyOrdering[] 欄位。

"propertyOrdering": ["recipe_name", "ingredients"]

propertyOrdering[] 不是 OpenAPI 規格中的標準欄位,而是用於判斷回應中屬性順序的字串陣列。指定屬性順序,然後提供包含相同順序屬性的示例,有助於改善結果品質。