您可以將 Gemini 設為結構化輸出內容,而非非結構化文字,以便精確擷取及標準化資訊,以利後續處理。舉例來說,您可以使用結構化輸出內容,從履歷中擷取資訊,並將這些資訊標準化,以建立結構化資料庫。
Gemini 可產生 JSON 或 enum 值做為結構化輸出內容。
產生 JSON
使用 Gemini API 產生 JSON 的方式有兩種:
- 在模型上設定結構定義
- 在文字提示中提供結構定義
在模型上設定結構定義是產生 JSON 的建議方式,因為這會限制模型輸出 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(api_key="GOOGLE_API_KEY") response = client.models.generate_content( model="gemini-2.0-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({ "GOOGLE_API_KEY" }); async function main() { const response = await ai.models.generateContent({ model: "gemini-2.0-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, &genai.ClientConfig{ APIKey: "GOOGLE_API_KEY", Backend: genai.BackendGeminiAPI, }) 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.0-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.0-flash:generateContent?key=$GOOGLE_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" ] }, ... ]
在文字提示中提供結構定義
您可以透過文字提示,以自然語言或擬似程式碼的形式提供結構定義,而無須進行設定。不建議採用這種方法,因為這可能會產生品質較低的輸出內容,而且模型不會受到限制,無法遵循結構定義。
以下是文字提示中提供的結構定義通用範例:
List a few popular cookie recipes, and include the amounts of ingredients. Produce JSON matching this specification: Recipe = { "recipeName": string, "ingredients": array<string> } Return: array<Recipe>
由於模型會從提示中的文字取得結構定義,因此您可以靈活呈現結構定義。不過,如果您提供類似這種內嵌的結構定義,模型實際上並不會受到限制,無法傳回 JSON。如要獲得更確定且品質更高的回覆,請在模型上設定結構定義,並避免在文字提示中重複結構定義。
產生列舉值
在某些情況下,您可能會希望模型從選項清單中選擇單一選項。如要實作這項行為,您可以在結構定義中傳遞枚舉值。您可以在 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(api_key="GEMINI_API_KEY") response = client.models.generate_content( model='gemini-2.0-flash', contents='What type of instrument is an oboe?', config={ 'response_mime_type': 'text/x.enum', 'response_schema': Instrument, }, ) print(response.text) # Woodwind
Python 程式庫會為 API 轉譯型別宣告。不過,API 會接受 OpenAPI 3.0 架構的子集 (架構)。
您可以透過其他兩種方式指定列舉。您可以使用 Literal
:
Python
Literal["Percussion", "String", "Woodwind", "Brass", "Keyboard"]
您也可以以 JSON 的形式傳遞結構定義:
Python
from google import genai client = genai.Client(api_key="GEMINI_API_KEY") response = client.models.generate_content( model='gemini-2.0-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(api_key="GEMINI_API_KEY") response = client.models.generate_content( model='gemini-2.0-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]
。此註解會宣告所有字典值為相同類型,但不會指定應納入哪些鍵。- 使用者定義的 Pydantic 模型。這個方法可讓您指定索引鍵名稱,並為與每個索引鍵相關聯的值定義不同類型,包括巢狀結構。
最佳做法
使用回應結構定義時,請留意下列考量事項和最佳做法:
- 回應結構定義的大小會計入輸入符記限制。
- 根據預設,欄位為選填欄位,表示模型可以填入欄位或略過欄位。您可以將欄位設為必填,強制模型提供值。如果相關輸入提示的脈絡資訊不足,模型會根據訓練資料產生回覆。
複雜的結構定義可能會導致
InvalidArgument: 400
錯誤。複雜度可能來自長的屬性名稱、長的陣列長度限制、具有許多值的列舉、具有許多選用屬性的物件,或這些因素的組合。如果您在使用有效結構定義時收到這項錯誤,請進行下列一或多項變更來解決錯誤:
- 縮短屬性名稱或列舉名稱。
- 展開巢狀陣列。
- 減少具有限制的屬性數量,例如設有最小值和最大值限制的數字。
- 減少具有複雜限制的屬性數量,例如具有
date-time
等複雜格式的屬性。 - 減少選用屬性數量。
- 減少列舉的有效值數量。
如果未顯示預期結果,請在輸入提示中加入更多背景資訊,或修改回應結構定義。舉例來說,您可以查看模型的回覆內容,瞭解模型的回應方式,而無須使用結構化輸出內容。接著,您可以更新回應結構定義,讓回應結構定義更符合模型的輸出內容。
後續步驟
您已瞭解如何產生結構化輸出內容,建議您試著使用 Gemini API 工具: