fromgoogleimportgenaifrompydanticimportBaseModelclassRecipe(BaseModel):recipe_name:stringredients:list[str]client=genai.Client(api_key="GOOGLE_API_KEY")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
目前尚不支持 Pydantic 验证器。如果发生 pydantic.ValidationError,系统会将其抑制,并且 .parsed 可能会为空/null。
JavaScript
import{GoogleGenAI,Type}from"@google/genai";constai=newGoogleGenAI({"GOOGLE_API_KEY"});asyncfunctionmain(){constresponse=awaitai.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
packagemainimport("context""fmt""log""google.golang.org/genai"funcmain(){ctx:=context.Background()client,err:=genai.NewClient(ctx,&genai.ClientConfig{APIKey:"GOOGLE_API_KEY",Backend:genai.BackendGeminiAPI,iferr!=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,iferr!=nil{log.Fatal(err)fmt.Println(result.Text())
REST
curl"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-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>
fromgoogleimportgenaiimportenumclassInstrument(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.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";constai=newGoogleGenAI({});constresponse=awaitai.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?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 架构的子集(架构)。
fromgoogleimportgenaiclient=genai.Client(api_key="GEMINI_API_KEY")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
fromgoogleimportgenaiimportenumfrompydanticimportBaseModelclassGrade(enum.Enum):A_PLUS="a+"A="a"B="b"C="c"D="d"F="f"classRecipe(BaseModel):recipe_name:strrating:Gradeclient=genai.Client(api_key="GEMINI_API_KEY")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)
在 Gemini API 中使用 JSON 架构时,属性的顺序非常重要。默认情况下,API 会按字母顺序对房源进行排序,而不保留房源的定义顺序(不过 Google Gen AI SDK 可能会保留此顺序)。如果您向配置了架构的模型提供示例,并且示例的属性顺序与架构的属性顺序不一致,则输出可能会杂乱无章或出乎意料。
curl"https://generativelanguage.googleapis.com/v1alpha/models/\gemini-2.5-flash:generateContent?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
fromenumimportEnum
fromtypingimportList,Optional,Union,Set
frompydanticimportBaseModel,Field,ConfigDict
importjson
classUserRole(str,Enum):
ADMIN="admin"VIEWER="viewer"
classAddress(BaseModel):
street:str
city:str
classUserProfile(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