Gemini 中文指南
获取 API 密钥 ↗

结构化输出

↓ 下载 Markdown

您可以配置 Gemini 模型以生成符合所提供的 JSON Schema 的响应。这确保了可预测的、类型安全的结果,并简化了从非结构化文本中提取结构化数据的过程。

使用结构化输出非常适合:

  • 数据提取: 从文本中提取特定信息,例如姓名和日期。
  • 结构化分类: 将文本分类到预定义的类别中。
  • 智能体工作流程: 为工具或 API 生成结构化输入。

除了在 REST API 中支持 JSON Schema 之外,Google GenAI SDK 还允许使用以下方式定义模式: Pydantic (Python)和 Zod (JavaScript)。

结构化输出示例 #

配方提取器 #

此示例演示如何使用基本 JSON Schema 类型从文本中提取结构化数据,例如 object, array, string, 和 integer.

python
from google import genai
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]

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-4-hydrogen",
    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)

响应示例:

json
{
  "recipe_name": "Delicious Chocolate Chip Cookies",
  "ingredients": [
    { "name": "all-purpose flour", "quantity": "2 and 1/4 cups" },
    { "name": "baking soda", "quantity": "1 teaspoon" },
    { "name": "salt", "quantity": "1 teaspoon" },
    { "name": "unsalted butter (softened)", "quantity": "1 cup" },
    { "name": "granulated sugar", "quantity": "3/4 cup" },
    { "name": "packed brown sugar", "quantity": "3/4 cup" },
    { "name": "vanilla extract", "quantity": "1 teaspoon" },
    { "name": "large eggs", "quantity": "2" },
    { "name": "semisweet chocolate chips", "quantity": "2 cups" }
  ],
  "instructions": [
    "Preheat the oven to 375°F (190°C).",
    "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.",
    "Stir in the chocolate chips.",
    "Drop by rounded tablespoons onto ungreased baking sheets and bake for 9 to 11 minutes."
  ]
}

内容审核 #

这个例子展示了 anyOf 对于条件模式和 enum 用于分类,允许输出结构根据内容而变化。

python
from google import genai
from pydantic import BaseModel, Field
from typing import Union, Literal

class SpamDetails(BaseModel):
    reason: str = Field(description="The reason why the content is considered spam.")
    spam_type: Literal["phishing", "scam", "unsolicited promotion", "other"] = Field(description="The type of spam.")

class NotSpamDetails(BaseModel):
    summary: str = Field(description="A brief summary of the content.")
    is_safe: bool = Field(description="Whether the content is safe for all audiences.")

class ModerationResult(BaseModel):
    decision: Union[SpamDetails, NotSpamDetails]

client = genai.Client()

prompt = """
Please moderate the following content and provide a decision.
Content: 'Congratulations! You''ve won a free cruise to the Bahamas. Click here to claim your prize: www.definitely-not-a-scam.com'
"""

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

result = ModerationResult.model_validate_json(interaction.output_text)
print(result)

响应示例:

json
{
  "decision": {
    "reason": "The content is an unsolicited prize notification attempting to trick the user into clicking a suspicious link.",
    "spam_type": "scam"
  }
}

递归结构 #

此示例说明如何定义递归架构(例如组织结构图)。

python
from google import genai
from pydantic import BaseModel, Field
from typing import List

class Employee(BaseModel):
    """Represents an employee in an organization."""
    name: str
    employee_id: int
    reports: List["Employee"] = Field(
        default_factory=list,
        description="A list of employees reporting to this employee."
    )

client = genai.Client()

prompt = """
Generate an organization chart for a small team.
The manager is Alice, who manages Bob and Charlie. Bob manages David.
"""

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

employee = Employee.model_validate_json(interaction.output_text)
print(employee)

响应示例:

json
{
  "name": "Alice",
  "employee_id": 101,
  "reports": [
    {
      "name": "Bob",
      "employee_id": 102,
      "reports": [
        {
          "name": "David",
          "employee_id": 104,
          "reports": []
        }
      ]
    },
    {
      "name": "Charlie",
      "employee_id": 103,
      "reports": []
    }
  ]
}

流式传输结果 #

您可以流式传输结构化输出,从而允许您在生成响应时开始处理响应。流式传输的块是有效的部分 JSON 字符串,可以将其连接起来形成最终的 JSON 对象。

python
from google import genai
from pydantic import BaseModel
from typing import Literal

class Feedback(BaseModel):
    sentiment: Literal["positive", "neutral", "negative"]
    summary: str

client = genai.Client()
prompt = "The new UI is incredibly intuitive. Add a very long summary to test streaming!"

stream = client.interactions.create(
    model="gemini-4-hydrogen",
    input=prompt,
    response_format={
        "type": "text",
        "mime_type": "application/json",
        "schema": Feedback.model_json_schema()
    },
    stream=True
)
for event in stream:
    if event.event_type == "step.delta" and event.delta.text:
        print(event.delta.text, end="")

使用工具进行结构化输出 #

Gemini 4 和 Gemini 3 可让您将结构化输出与内置工具结合起来,包括 使用 Google 搜索提供事实依据, URL上下文, 代码执行, 文件搜索, 和 函数调用.

python
from google import genai
from pydantic import BaseModel, Field
from typing import List

class MatchResult(BaseModel):
    winner: str = Field(description="The name of the winner.")
    final_match_score: str = Field(description="The final match score.")
    scorers: List[str] = Field(description="The name of the scorer.")

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-4-carbon",
    input="Search for all details for the latest Euro.",
    tools=[{"type": "google_search"}, {"type": "url_context"}],
    response_format={
        "type": "text",
        "mime_type": "application/json",
        "schema": MatchResult.model_json_schema()
    },
)

result = MatchResult.model_validate_json(interaction.output_text)
print(result)

JSON 模式支持 #

要生成 JSON 对象,请配置 response_format 具有类型的对象(或包含对象的数组) text 并设置其 mime_type 到 application/json。架构应在 schema 场。

Gemini的结构化输出模式支持的子集 JSON Schema 规格。

以下值 type 支持:

  • string: 对于文本。
  • number:对于浮点数。
  • integer:对于整数。
  • boolean:对于 true 或 false 值。
  • object:适用于具有键值对的结构化数据。
  • array:用于项目列表。
  • null:要允许属性为空,请包括 "null" 在类型数组中(例如, {"type": ["string", "null"]}).

这些描述性属性有助于指导模型:

  • title:属性的简短描述。
  • description:对属性的更长、更详细的描述。

特定于类型的属性 #

对于 object 价值观:

  • properties:一个对象,其中每个键都是属性名称,每个值都是该属性的架构。
  • required:字符串数组,列出哪些属性是必需的。
  • additionalProperties:控制属性是否未列出 properties 是允许的。可以是布尔值或模式。
  • 不支持的计数约束: minProperties 和 maxProperties 在受限解码期间不会强制执行,并且会被服务器忽略。如果需要,验证应用程序代码中的属性计数。

对于 string 价值观:

  • enum:列出用于分类任务的一组特定的可能字符串。
  • format:指定字符串的语法,例如 date-time, date, time.
  • 不支持的长度限制: minLength 和 maxLength 在受限解码期间不会强制执行,并且会被服务器忽略。如果需要,验证应用程序代码中的字符串长度。

对于 number 和 integer 价值观:

  • enum:列出一组特定的可能数值。
  • minimum:最小包含值。
  • maximum:最大包含值。

对于 array 价值观:

  • items:定义数组中所有项目的架构。
  • prefixItems:定义前 N 项的模式列表,允许类似元组的结构。
  • minItems:数组中的最小项目数。
  • maxItems:数组中的最大项目数。
  • 不支持的数组约束: uniqueItems, contains, minContains, 和 maxContains 在受限解码期间不会强制执行,并且会被服务器忽略。如果需要,请删除应用程序代码中的重复项或检查数组内容。

结构化输出与函数调用 #

特点主要用例
结构化输出格式化最终响应。 当您需要模型时使用 回答 以特定的格式。
函数调用在谈话中采取行动。 当模型需要时使用 问你 在提供最终答案之前执行任务。

最佳实践 #

  • 清晰的描述: 使用 description 场来指导模型。
  • 强类型: 使用特定类型(integer, string, enum).
  • 即时工程: 清楚地说明您希望模型做什么。
  • 验证: 虽然输出是语法上正确的 JSON,但请始终验证应用程序中的值。
  • 错误处理: 对符合模式但语义不正确的输出实施强大的错误处理。

限制 #

  • 架构子集: 并非所有 JSON Schema 功能均受支持。
  • 模式复杂度: 非常大或深度嵌套的模式可能会被拒绝。
  • 非强制约束: minLength, maxLength, minProperties, maxProperties, uniqueItems, contains, minContains, 和 maxContains (及其 Snake_case 变体)不受约束解码语法引擎强制执行。如果这些关键字存在于您的架构中(例如,由 Pydantic 自动发出) Field(min_length=...) 或 Zod 的 .min()),API 在请求规范化期间自动剥离并忽略它们,而不是返回错误。 minItems 和 maxItems 被强制执行。要强制执行其他约束,请验证客户端应用程序中的输出(例如,使用 Pydantic model_validate_json() 或 Zod .parse()).

简化复杂的模式 #

当您请求结构化输出时,API 将您的 JSON Schema 编译为约束 token 生成的状态机。该状态机强制限制总状态、分支路径和嵌套深度。如果您的架构超出这些限制,API 将拒绝该请求并显示 400 INVALID_ARGUMENT 错误。

要修复架构拒绝错误,请减少架构的结构深度和分支因子。您可以通过多种方式简化复杂的模式:

  • 将非结构性规则移至描述: 领域 description 属性和系统指令指导模型,而不向输出语法添加状态。如果复杂的约束使您的架构超出了限制,请将这些规则移至简洁的描述中,并验证应用程序代码中的响应。
  • 展平嵌套对象和绑定递归: 用更扁平的结构替换深度嵌套的对象层次结构。如果你使用 $defs 和 $ref 对于递归类型,使递归引用可选或可为空。避免通过所需的属性或数组进行递归 minItems 大于零。
  • 减少可选字段、枚举和联合的分支: 可选属性, enum 价值观,以及 anyOf 分支乘以输出语法中的分支路径。将属性标记为 required 在可能的情况下并允许 null 当字段可以为空时的值。修剪大 enum 列出并简化 anyOf 联合,或在提示中包含约束(例如,使用 Pydantic 架构)作为较软的限制。
  • 缩短属性名称并删除数组或数字边界: 属性键消耗与其字符长度成比例的状态。数组边界例如 minItems 和 maxItems 复制每个计数位置的项目架构和数字边界 (minimum 和 maximum)也增加了状态空间。使用简洁的属性名称,删除未使用的字段,并在提示中包含边界(例如,使用 Pydantic 架构)作为较软的限制或验证应用程序代码中的边界。

搜索标题、API 名称或正文内容