คุณสามารถกำหนดค่า 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
ในบางกรณี คุณอาจต้องการให้โมเดลเลือกตัวเลือกเดียวจากรายการตัวเลือก หากต้องการใช้ลักษณะการทำงานนี้ คุณสามารถส่ง enum ในสคีมาได้ คุณ ใช้ตัวเลือก enum ได้ทุกที่ที่ใช้ string
ใน responseSchema
เนื่องจาก enum คืออาร์เรย์ของสตริง เช่นเดียวกับสคีมา JSON enum ช่วยให้คุณจำกัดเอาต์พุตของโมเดลให้ตรงตามข้อกำหนดของ แอปพลิเคชันได้
ตัวอย่างเช่น สมมติว่าคุณกำลังพัฒนาแอปพลิเคชันเพื่อจัดประเภทเครื่องดนตรี เป็น 1 ใน 5 หมวดหมู่ ได้แก่ "Percussion"
, "String"
, "Woodwind"
, "Brass"
หรือ ""Keyboard"
" คุณสามารถสร้าง Enum เพื่อช่วย ในงานนี้ได้
ในตัวอย่างต่อไปนี้ คุณจะส่งผ่าน Enum เป็น 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 (สคีมา)
นอกจากนี้ ยังมีวิธีระบุการแจงนับอีก 2 วิธี คุณใช้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
นอกเหนือจากโจทย์แบบเลือกตอบพื้นฐานแล้ว คุณยังใช้ Enum ได้ทุกที่ในสคีมา JSON ตัวอย่างเช่น คุณอาจขอให้โมเดลแสดงรายการชื่อสูตรอาหารและ ใช้ Grade
enum เพื่อให้คะแนนความนิยมของแต่ละชื่อ
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
การกำหนดค่าโมเดลสำหรับเอาต์พุต JSON โดยใช้พารามิเตอร์ responseSchema
จะขึ้นอยู่กับออบเจ็กต์ 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 ได้ที่ข้อมูลอ้างอิงของสคีมา
การสั่งซื้อพร็อพเพอร์ตี้
เมื่อทำงานกับสคีมา JSON ใน Gemini API ลำดับของพร็อพเพอร์ตี้ มีความสำคัญ โดยค่าเริ่มต้น API จะจัดเรียงพร็อพเพอร์ตี้ตามตัวอักษรและจะไม่ รักษาลำดับที่กำหนดพร็อพเพอร์ตี้ (แม้ว่า Google Gen AI SDK อาจรักษาลำดับนี้ไว้) หากคุณ ระบุตัวอย่างให้กับโมเดลที่มีการกำหนดค่าสคีมา และลำดับพร็อพเพอร์ตี้ ของตัวอย่างไม่สอดคล้องกับลำดับพร็อพเพอร์ตี้ของ สคีมา เอาต์พุตอาจไม่ปะติดปะต่อหรือคาดไม่ถึง
คุณใช้ฟิลด์ propertyOrdering[]
ที่ไม่บังคับได้เพื่อให้มั่นใจว่าพร็อพเพอร์ตี้จะเรียงตามลำดับที่สอดคล้องกันและคาดการณ์ได้
"propertyOrdering": ["recipeName", "ingredients"]
propertyOrdering[]
– ไม่ใช่ฟิลด์มาตรฐานในข้อกำหนด OpenAPI – เป็นอาร์เรย์ของสตริงที่ใช้เพื่อกำหนดลำดับของพร็อพเพอร์ตี้ใน การตอบกลับ การระบุลําดับของพร็อพเพอร์ตี้ แล้วระบุตัวอย่างที่มีพร็อพเพอร์ตี้ในลําดับเดียวกันนั้นอาจช่วยปรับปรุงคุณภาพของผลลัพธ์ได้ propertyOrdering
จะรองรับเฉพาะเมื่อคุณสร้าง types.Schema
ด้วยตนเอง
สคีมาใน Python
เมื่อใช้ไลบรารี Python ค่าของ response_schema
ต้องเป็นค่าใดค่าหนึ่งต่อไปนี้
- ประเภทตามที่คุณใช้ในคำอธิบายประกอบประเภท (ดูโมดูล
typing
ของ Python) - อินสแตนซ์ของ
genai.types.Schema
dict
เทียบเท่ากับgenai.types.Schema
วิธีที่ง่ายที่สุดในการกำหนดสคีมาคือการใช้ประเภท 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 ซึ่งเป็นข้อกำหนดที่ออบเจ็กต์สคีมาใช้ การรองรับ JSON Schema พร้อมให้บริการในเวอร์ชันตัวอย่างโดยใช้ฟิลด์ responseJsonSchema
ซึ่ง ยอมรับ JSON Schema ใดก็ได้โดยมีข้อจำกัดต่อไปนี้
- โดยจะใช้ได้กับ Gemini 2.5 เท่านั้น
- แม้ว่าจะส่งพร็อพเพอร์ตี้ JSON Schema ทั้งหมดได้ แต่ระบบก็ไม่รองรับพร็อพเพอร์ตี้บางรายการ ดูรายละเอียดเพิ่มเติมเกี่ยวกับฟิลด์ได้ในเอกสารประกอบ
- การอ้างอิงแบบเรียกซ้ำใช้ได้เฉพาะเป็นค่าของพร็อพเพอร์ตี้ออบเจ็กต์ที่ไม่บังคับ เท่านั้น
- การอ้างอิงแบบเรียกซ้ำจะคลี่ออกในระดับที่จำกัดตามขนาดของสคีมา
- สคีมาที่มี
$ref
ต้องไม่มีพร็อพเพอร์ตี้อื่นนอกเหนือจากพร็อพเพอร์ตี้ที่ขึ้นต้นด้วย$
ต่อไปนี้คือตัวอย่างการสร้างสคีมา JSON ด้วย Pydantic และการส่งไปยังโมเดล
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 Schema โดยตรง
แนวทางปฏิบัติแนะนำ
โปรดคำนึงถึงข้อควรพิจารณาและแนวทางปฏิบัติแนะนำต่อไปนี้เมื่อใช้ สคีมาการตอบกลับ
- ขนาดของสคีมาการตอบกลับจะนับรวมในขีดจำกัดโทเค็นอินพุต
- โดยค่าเริ่มต้น ฟิลด์จะไม่บังคับ ซึ่งหมายความว่าโมเดลจะป้อนข้อมูลในฟิลด์หรือข้ามฟิลด์ก็ได้ คุณสามารถตั้งค่าช่องเป็นต้องกรอกเพื่อบังคับให้โมเดลระบุค่าได้ หากพรอมต์อินพุตที่เชื่อมโยงมีบริบทไม่เพียงพอ โมเดลจะสร้างคำตอบโดยอิงตามข้อมูลที่ใช้ฝึกเป็นหลัก
สคีมาที่ซับซ้อนอาจทำให้เกิด
InvalidArgument: 400
ข้อผิดพลาด ความซับซ้อน อาจเกิดจากชื่อพร็อพเพอร์ตี้ยาว ขีดจำกัดความยาวของอาร์เรย์ยาว อีนาเมลที่มี หลายค่า ออบเจ็กต์ที่มีพร็อพเพอร์ตี้ที่ไม่บังคับจำนวนมาก หรือการรวมกันของ ปัจจัยเหล่านี้หากได้รับข้อผิดพลาดนี้เมื่อใช้สคีมาที่ถูกต้อง ให้ทำการเปลี่ยนแปลงอย่างน้อย 1 อย่างต่อไปนี้เพื่อแก้ไขข้อผิดพลาด
- ย่อชื่อพร็อพเพอร์ตี้หรือชื่อ Enum
- แปลงอาร์เรย์ที่ซ้อนกันให้เป็นอาร์เรย์แบบแบน
- ลดจำนวนพร็อพเพอร์ตี้ที่มีข้อจำกัด เช่น ตัวเลขที่มี ขีดจำกัดต่ำสุดและสูงสุด
- ลดจำนวนพร็อพเพอร์ตี้ที่มีข้อจำกัดที่ซับซ้อน เช่น พร็อพเพอร์ตี้ที่มีรูปแบบที่ซับซ้อน เช่น
date-time
- ลดจำนวนพร็อพเพอร์ตี้ที่ไม่บังคับ
- ลดจำนวนค่าที่ถูกต้องสำหรับ Enum
หากไม่เห็นผลลัพธ์ที่คาดไว้ ให้เพิ่มบริบทลงในพรอมต์อินพุต หรือแก้ไขสคีมาการตอบกลับ เช่น ตรวจสอบคำตอบของโมเดล ที่ไม่มีเอาต์พุตที่มีโครงสร้างเพื่อดูวิธีที่โมเดลตอบ จากนั้นคุณจะ อัปเดตสคีมาการตอบกลับเพื่อให้เหมาะกับเอาต์พุตของโมเดลมากขึ้นได้ ดูเคล็ดลับการแก้ปัญหาเพิ่มเติมเกี่ยวกับเอาต์พุตที่มีโครงสร้างได้ที่คู่มือการแก้ปัญหา
ขั้นตอนถัดไป
เมื่อได้เรียนรู้วิธีสร้างเอาต์พุตที่มีโครงสร้างแล้ว คุณอาจต้องการลองใช้เครื่องมือ Gemini API ดังนี้