TodayAI

GuidesModels

用 Gemini Structured Outputs 约束 JSON 结果

按官方 Structured outputs:用 JSON Schema / Pydantic 约束 Gemini 的最终回答格式,提取菜谱等结构化数据并可直接校验。

基于 Google AI for Developers 整理 · 官方资料 ↗

自由文本好读,但难解析。Structured Outputs 让模型按你提供的 JSON Schema 回答,结果可预测、可类型校验,适合抽取字段、固定分类,以及给后续工具喂结构化输入。

官方路径是 Interactions API 的 response_format:mime_type 为 application/json,并带上 schema。Python 侧常用 Pydantic 的 model_json_schema()。

什么时候该用 Structured Outputs

  • 从非结构化文本里抽姓名、日期、清单等字段
  • 把内容分到预定义类别(含 enum)
  • Agent 工作流里需要稳定 JSON,再交给下游 API

它约束的是最终回答形态。若模型需要先让你执行外部动作,那是 Function Calling;两者目标不同,不要混用概念。

用 Pydantic 定义 Schema

官方 Recipe Extractor 示例用嵌套对象与数组:Ingredient 与 Recipe。Field(description=...) 会进入 schema,帮助模型填对字段。

官方 Recipe / Ingredient 模型

python
from pydantic import BaseModel, Field
from typing import List, Optional

class Ingredient(BaseModel):
    name: str = Field(description="Name of the ingredient.")
    quantity: str = Field(description="Quantity of the ingredient, including units.")

class Recipe(BaseModel):
    recipe_name: str = Field(description="The name of the recipe.")
    prep_time_minutes: Optional[int] = Field(
        description="Optional time in minutes to prepare the recipe."
    )
    ingredients: List[Ingredient]
    instructions: List[str]

在 Interactions API 里挂上 response_format

创建 Client,把自然语言提示和 schema 一起交给 interactions.create。当前官方示例模型为 gemini-3.6-flash。

官方 Recipe Extractor 调用

python
from google import genai

client = genai.Client()

prompt = """
Please extract the recipe from the following text.
The user wants to make delicious chocolate chip cookies.
They need 2 and 1/4 cups of all-purpose flour, 1 teaspoon of baking soda,
1 teaspoon of salt, 1 cup of unsalted butter (softened), 3/4 cup of granulated sugar,
3/4 cup of packed brown sugar, 1 teaspoon of vanilla extract, and 2 large eggs.
For the best part, they'll need 2 cups of semisweet chocolate chips.
First, preheat the oven to 375°F (190°C). Then, in a small bowl, whisk together the flour,
baking soda, and salt. In a large bowl, cream together the butter, granulated sugar, and brown sugar
until light and fluffy. Beat in the vanilla and eggs, one at a time. Gradually beat in the dry
ingredients until just combined. Finally, stir in the chocolate chips. Drop by rounded tablespoons
onto ungreased baking sheets and bake for 9 to 11 minutes.
"""

interaction = client.interactions.create(
    model="gemini-3.6-flash",
    input=prompt,
    response_format={
        "type": "text",
        "mime_type": "application/json",
        "schema": Recipe.model_json_schema(),
    },
)

recipe = Recipe.model_validate_json(interaction.output_text)
print(recipe)

model_validate_json 把输出重新变成类型安全对象。语法正确不等于语义正确:数量写错、步骤漏项仍要在业务层校验。

和 Function Calling 怎么区分

  • Structured Outputs:格式化最终回答
  • Function Calling:对话中途请求你执行动作,再继续生成

官方最佳实践:描述写清楚、类型尽量具体(integer / string / enum)、提示写明任务,并始终在应用里做值校验与错误处理。超大或过深嵌套的 schema 可能被拒绝。

容易踩的坑

输出不是合法 JSON 或校验失败

确认 response_format.mime_type 为 application/json,且 schema 来自同一套 Pydantic / JSON Schema;用 model_validate_json 看具体字段错误。

把 Structured Outputs 当成调外部 API

需要模型发起动作时改用 Function Calling;Structured Outputs 只保证回答形状。

schema 过于复杂被拒

缩小嵌套与可选分支;官方说明并非全部 JSON Schema 特性都支持。

官方资料

Google AI for Developers

Structured outputs