您可以將 Gemini 設為輸出結構化內容,而非非結構化文字,以便精確擷取及標準化資訊,供後續處理。舉例來說,您可以運用結構化輸出內容從履歷表擷取資訊,並將這些資訊標準化,以建構結構化資料庫。
Gemini 可以生成 JSON 或 enum 值做為結構化輸出。
產生 JSON
如要限制模型生成 JSON,請設定 responseSchema
。模型隨後會以 JSON 格式輸出任何提示的回覆。
Python
from google import genai from pydantic import BaseModel class Recipe(BaseModel): recipe_name: str ingredients: list[str] client = genai.Client() response = client.models.generate_content( model="gemini-2.5-flash", contents="List a few popular cookie recipes, and include the amounts of ingredients.", config={ "response_mime_type": "application/json", "response_schema": list[Recipe], }, ) # Use the response as a JSON string. print(response.text) # Use instantiated objects. my_recipes: list[Recipe] = response.parsed
JavaScript
import { GoogleGenAI, Type } from "@google/genai"; const ai = new GoogleGenAI({}); async function main() { const response = await ai.models.generateContent({ model: "gemini-2.5-flash", contents: "List a few popular cookie recipes, and include the amounts of ingredients.", config: { responseMimeType: "application/json", responseSchema: { type: Type.ARRAY, items: { type: Type.OBJECT, properties: { recipeName: { type: Type.STRING, }, ingredients: { type: Type.ARRAY, items: { type: Type.STRING, }, }, }, propertyOrdering: ["recipeName", "ingredients"], }, }, }, }); console.log(response.text); } main();
Go
package main import ( "context" "fmt" "log" "google.golang.org/genai" ) func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } config := &genai.GenerateContentConfig{ ResponseMIMEType: "application/json", ResponseSchema: &genai.Schema{ Type: genai.TypeArray, Items: &genai.Schema{ Type: genai.TypeObject, Properties: map[string]*genai.Schema{ "recipeName": {Type: genai.TypeString}, "ingredients": { Type: genai.TypeArray, Items: &genai.Schema{Type: genai.TypeString}, }, }, PropertyOrdering: []string{"recipeName", "ingredients"}, }, }, } result, err := client.Models.GenerateContent( ctx, "gemini-2.5-flash", genai.Text("List a few popular cookie recipes, and include the amounts of ingredients."), config, ) if err != nil { log.Fatal(err) } fmt.Println(result.Text()) }
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent" \ -H "x-goog-api-key: $GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -d '{ "contents": [{ "parts":[ { "text": "List a few popular cookie recipes, and include the amounts of ingredients." } ] }], "generationConfig": { "responseMimeType": "application/json", "responseSchema": { "type": "ARRAY", "items": { "type": "OBJECT", "properties": { "recipeName": { "type": "STRING" }, "ingredients": { "type": "ARRAY", "items": { "type": "STRING" } } }, "propertyOrdering": ["recipeName", "ingredients"] } } } }' 2> /dev/null | head
輸出內容可能如下所示:
[ { "recipeName": "Chocolate Chip Cookies", "ingredients": [ "1 cup (2 sticks) unsalted butter, softened", "3/4 cup granulated sugar", "3/4 cup packed brown sugar", "1 teaspoon vanilla extract", "2 large eggs", "2 1/4 cups all-purpose flour", "1 teaspoon baking soda", "1 teaspoon salt", "2 cups chocolate chips" ] }, ... ]
產生列舉值
在某些情況下,您可能希望模型從選項清單中選擇單一選項。如要實作這項行為,可以在結構定義中傳遞 enum。您可以在 responseSchema
中使用列舉選項,因為列舉是字串陣列。string
與 JSON 結構定義類似,列舉可限制模型輸出內容,以符合應用程式需求。
舉例來說,假設您要開發應用程式,將樂器分類為五種其中一種:"Percussion"
、"String"
、"Woodwind"
、"Brass"
或「"Keyboard"
」。您可以建立列舉,協助完成這項工作。
在下列範例中,您會將列舉傳遞為 responseSchema
,限制模型選擇最合適的選項。
Python
from google import genai import enum class Instrument(enum.Enum): PERCUSSION = "Percussion" STRING = "String" WOODWIND = "Woodwind" BRASS = "Brass" KEYBOARD = "Keyboard" client = genai.Client() response = client.models.generate_content( model='gemini-2.5-flash', contents='What type of instrument is an oboe?', config={ 'response_mime_type': 'text/x.enum', 'response_schema': Instrument, }, ) print(response.text) # Woodwind
JavaScript
import { GoogleGenAI, Type } from "@google/genai"; const ai = new GoogleGenAI({}); const response = await ai.models.generateContent({ model: "gemini-2.5-flash", contents: "What type of instrument is an oboe?", config: { responseMimeType: "text/x.enum", responseSchema: { type: Type.STRING, enum: ["Percussion", "String", "Woodwind", "Brass", "Keyboard"], }, }, }); console.log(response.text);
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent" \ -H "x-goog-api-key: $GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -d '{ "contents": [{ "parts":[ { "text": "What type of instrument is an oboe?" } ] }], "generationConfig": { "responseMimeType": "text/x.enum", "responseSchema": { "type": "STRING", "enum": ["Percussion", "String", "Woodwind", "Brass", "Keyboard"] } } }'
Python 程式庫會轉譯 API 的型別宣告。不過,API 接受 OpenAPI 3.0 架構 (架構) 的子集。
您也可以透過其他兩種方式指定列舉。你可以使用 Literal
: ```
Python
Literal["Percussion", "String", "Woodwind", "Brass", "Keyboard"]
您也可以將結構定義以 JSON 形式傳遞:
Python
from google import genai client = genai.Client() response = client.models.generate_content( model='gemini-2.5-flash', contents='What type of instrument is an oboe?', config={ 'response_mime_type': 'text/x.enum', 'response_schema': { "type": "STRING", "enum": ["Percussion", "String", "Woodwind", "Brass", "Keyboard"], }, }, ) print(response.text) # Woodwind
除了基本的多項選擇題,您還可以在 JSON 結構定義中的任何位置使用列舉。舉例來說,您可以要求模型提供食譜名稱清單,並使用 Grade
列舉為每個名稱指定熱門程度等級:
Python
from google import genai import enum from pydantic import BaseModel class Grade(enum.Enum): A_PLUS = "a+" A = "a" B = "b" C = "c" D = "d" F = "f" class Recipe(BaseModel): recipe_name: str rating: Grade client = genai.Client() response = client.models.generate_content( model='gemini-2.5-flash', contents='List 10 home-baked cookie recipes and give them grades based on tastiness.', config={ 'response_mime_type': 'application/json', 'response_schema': list[Recipe], }, ) print(response.text)
回應可能如下所示:
[ { "recipe_name": "Chocolate Chip Cookies", "rating": "a+" }, { "recipe_name": "Peanut Butter Cookies", "rating": "a" }, { "recipe_name": "Oatmeal Raisin Cookies", "rating": "b" }, ... ]
關於 JSON 結構定義
使用 responseSchema
參數設定模型輸出 JSON 時,需要依賴 Schema
物件定義結構。這個物件代表 OpenAPI 3.0 架構物件的選取子集,並新增 propertyOrdering
欄位。
以下是所有 Schema
欄位的虛擬 JSON 表示法:
{ "type": enum (Type), "format": string, "description": string, "nullable": boolean, "enum": [ string ], "maxItems": integer, "minItems": integer, "properties": { string: { object (Schema) }, ... }, "required": [ string ], "propertyOrdering": [ string ], "items": { object (Schema) } }
結構定義的 Type
必須是 OpenAPI 資料類型之一,或是這些類型的聯集 (使用 anyOf
)。每個 Type
僅適用於部分欄位。 下表列出每個 Type
對應的欄位子集,這些欄位適用於該類型:
string
->enum
、format
、nullable
integer
->format
、minimum
、maximum
、enum
、nullable
number
->format
、minimum
、maximum
、enum
、nullable
boolean
->nullable
array
->minItems
、maxItems
、items
、nullable
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": ["recipeName", "ingredients"]
propertyOrdering[]
(並非 OpenAPI 規格中的標準欄位) 是字串陣列,用於判斷回應中的屬性順序。指定屬性的順序,然後提供屬性順序相同的範例,可能有助於提升結果品質。手動建立 types.Schema
時,系統僅支援 propertyOrdering
。
Python 中的結構定義
使用 Python 程式庫時,response_schema
的值必須是下列其中一個:
- 類型,如您在型別註解中使用的類型 (請參閱 Python
typing
模組) genai.types.Schema
的執行個體genai.types.Schema
的dict
等效函式
定義結構定義最簡單的方法是使用 Pydantic 型別 (如上一個範例所示):
Python
config={'response_mime_type': 'application/json', 'response_schema': list[Recipe]}
使用 Pydantic 型別時,Python 程式庫會為您建構 JSON 結構定義,並傳送至 API。如需其他範例,請參閱 Python 程式庫文件。
Python 程式庫支援使用下列型別定義的結構定義 (其中 AllowedType
是任何允許的型別):
int
float
bool
str
list[AllowedType]
AllowedType|AllowedType|...
- 如果是結構化類型:
dict[str, AllowedType]
。這項註解會將所有 dict 值宣告為相同類型,但不會指定應包含哪些鍵。- 使用者定義的 Pydantic 模型。這種做法可讓您指定鍵名,並為與每個鍵相關聯的值定義不同類型,包括巢狀結構。
支援 JSON 結構定義
JSON 結構定義是比 OpenAPI 3.0 更新的規格,而 Schema 物件就是以 OpenAPI 3.0 為基礎。您可以使用 responseJsonSchema
欄位,以搶先版形式支援 JSON 結構定義,但接受任何 JSON 結構定義時,須遵守下列限制:
- 這項功能僅適用於 Gemini 2.5。
- 雖然可以傳遞所有 JSON 結構定義屬性,但並非所有屬性都受到支援。詳情請參閱說明文件。
- 遞迴參照只能做為非必要物件屬性的值。
- 系統會根據結構定義的大小,將遞迴參照展開至有限程度。
- 含有
$ref
的結構定義只能包含以$
開頭的屬性。
以下範例說明如何使用 Pydantic 產生 JSON 結構定義,並提交給模型:
curl "https://generativelanguage.googleapis.com/v1alpha/models/\ gemini-2.5-flash:generateContent" \ -H "x-goog-api-key: $GEMINI_API_KEY"\ -H 'Content-Type: application/json' \ -d @- <<EOF { "contents": [{ "parts":[{ "text": "Please give a random example following this schema" }] }], "generationConfig": { "response_mime_type": "application/json", "response_json_schema": $(python3 - << PYEOF from enum import Enum from typing import List, Optional, Union, Set from pydantic import BaseModel, Field, ConfigDict import json class UserRole(str, Enum): ADMIN = "admin" VIEWER = "viewer" class Address(BaseModel): street: str city: str class UserProfile(BaseModel): username: str = Field(description="User's unique name") age: Optional[int] = Field(ge=0, le=120) roles: Set[UserRole] = Field(min_items=1) contact: Union[Address, str] model_config = ConfigDict(title="User Schema") # Generate and print the JSON Schema print(json.dumps(UserProfile.model_json_schema(), indent=2)) PYEOF ) } } EOF
使用 SDK 時,系統尚不支援直接傳遞 JSON 結構定義。
最佳做法
使用回應結構定義時,請注意下列事項和最佳做法:
- 回應結構定義的大小會計入輸入權杖限制。
- 根據預設,欄位為選填,也就是說模型可以填入欄位或略過欄位。您可以將欄位設為必填,強制模型提供值。如果相關聯的輸入提示脈絡不足,模型主要會根據訓練資料生成回覆。
複雜的結構定義可能會導致
InvalidArgument: 400
錯誤。複雜度可能來自於屬性名稱過長、陣列長度限制過長、具有許多值的列舉、具有大量選用屬性的物件,或是這些因素的組合。如果使用有效結構定義時發生這項錯誤,請進行下列一或多項變更來解決問題:
- 縮短屬性名稱或列舉名稱。
- 整併巢狀陣列。
- 減少設有限制的屬性數量,例如設有上下限的數字。
- 減少具有複雜限制的屬性數量,例如具有複雜格式的屬性,如
date-time
。 - 減少選用屬性的數量。
- 減少列舉的有效值數量。
如果未看到預期結果,請在輸入提示中新增更多背景資訊,或修訂回覆結構定義。舉例來說,您可以查看模型在沒有結構化輸出內容的情況下如何回覆。然後更新回覆結構定義,讓其更符合模型的輸出內容。如需結構化輸出內容的其他疑難排解提示,請參閱疑難排解指南。
後續步驟
您已瞭解如何產生結構化輸出內容,現在不妨試用 Gemini API 工具: