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.
  """

  response = client.models.generate_content(
      model="gemini-4-hydrogen",
      contents=prompt,
      config={
          "response_mime_type": "application/json",
          "response_json_schema": Recipe.model_json_schema(),
      },
  )

  recipe = Recipe.model_validate_json(response.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'
  """

  response = client.models.generate_content(
      model="gemini-4-hydrogen",
      contents=prompt,
      config={
          "response_mime_type": "application/json",
          "response_json_schema": ModerationResult.model_json_schema(),
      },
  )

  result = ModerationResult.model_validate_json(response.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.
  """

  response = client.models.generate_content(
      model="gemini-4-hydrogen",
      contents=prompt,
      config={
          "response_mime_type": "application/json",
          "response_json_schema": Employee.model_json_schema(),
      },
  )

  employee = Employee.model_validate_json(response.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, Field
  from typing import Literal

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

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

  response_stream = client.models.generate_content_stream(
      model="gemini-4-hydrogen",
      contents=prompt,
      config={
          "response_mime_type": "application/json",
          "response_json_schema": Feedback.model_json_schema(),
      },
  )

  for chunk in response_stream:
      print(chunk.candidates[0].content.parts[0].text)

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

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()

  response = client.models.generate_content(
      model="gemini-4-carbon",
      contents="Search for all details for the latest Euro.",
      config={
          "tools": [
              {"google_search": {}},
              {"url_context": {}}
          ],
          "response_mime_type": "application/json",
          "response_json_schema": MatchResult.model_json_schema(),
      },
  )

  result = MatchResult.model_validate_json(response.text)
  print(result)

JSON 模式支持 #

要生成 JSON 对象,请设置 response_json_schema (或 responseFormat.text.schema 在 REST 中)在生成配置中。架构必须是有效的 JSON Schema 描述所需的输出格式。

然后,模型将生成一个响应,该响应是与所提供的架构匹配的语法上有效的 JSON 字符串。使用结构化输出时,模型将按照与模式中键相同的顺序生成输出。

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

以下值 type 支持:

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

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

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

特定于类型的属性 #

对于 object 价值观:

  • properties:一个对象,其中每个键都是属性名称,每个值都是该属性的架构。
  • required:字符串数组,列出哪些属性是必需的。
  • additionalProperties:控制属性是否未列出 properties 是允许的。可以是布尔值或模式。

对于 string 价值观:

  • enum:列出用于分类任务的一组特定的可能字符串。
  • format:指定字符串的语法,例如 date-time, date, time.

对于 number 和 integer 价值观:

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

对于 array 价值观:

  • items:定义数组中所有项目的架构。
  • prefixItems:定义前 N 项的模式列表,允许类似元组的结构。
  • minItems:数组中的最小项目数。
  • maxItems:数组中的最大项目数。

型号支持 #

以下模型支持结构化输出:

模型结构化输出
Gemini 4 Carbon✔️
Gemini 4 Argon✔️
Gemini 4 Hydrogen✔️
Gemini 3.8 Flash✔️
Gemini 3.6 Flash✔️
Gemini 3.5 Flash-Lite✔️
Gemini 3.1 Flash-Lite✔️
Gemini 3.1 Pro Preview✔️
Gemini 3.1 Flash-Lite Preview✔️
Gemini 2.5 Pro✔️
Gemini 2.5 Flash✔️
Gemini 2.5 Flash-Lite✔️
Gemini 2.0 Flash✔️*
Gemini 2.0 Flash-Lite✔️*

* 请注意,Gemini 2.0 需要显式 propertyOrdering JSON 输入中的列表来定义首选结构。你可以在这里找到一个例子 食谱.

结构化输出与函数调用 #

结构化输出和函数调用都使用 JSON 模式,但它们有不同的用途:

特点主要用例
结构化输出格式化对用户的最终响应。 当你想要模型的时候使用这个 回答 采用特定格式(例如,从文档中提取数据以保存到数据库)。
函数调用在谈话过程中采取行动。 当模型需要时使用它 问你 在提供最终答案之前执行任务(例如“获取当前天气”)。

最佳实践 #

  • 清晰的描述: 使用 description 架构中的字段,为模型提供有关每个属性代表什么的清晰说明。这对于指导模型的输出至关重要。
  • 强类型: 使用特定类型(integer, string, enum)只要有可能。如果参数的有效值有限,请使用 enum.
  • 即时工程: 在提示中清楚地说明您希望模型执行的操作。例如,“从文本中提取以下信息...”或“根据提供的架构对此反馈进行分类...”。
  • 验证: 虽然结构化输出保证 JSON 在语法上正确,但它不能保证值在语义上正确。在使用应用程序代码之前始终验证其最终输出。
  • 错误处理: 在应用程序中实现强大的错误处理,以优雅地管理模型输出虽然符合架构但可能无法满足您的业务逻辑要求的情况。

限制 #

  • 架构子集: 并非 JSON Schema 规范的所有功能都受支持。该模型会忽略不支持的属性。
  • 模式复杂度: 非常大或深度嵌套的模式可能会被拒绝。

简化复杂的模式 #

当您请求结构化输出时,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 名称或正文内容