跳转到内容

Gemini结构化输出 ​

您可以将 Gemini 配置为生成结构化输出(而非非结构化文本),以便准确提取和标准化信息,以便进一步处理。例如,您可以使用结构化输出从简历中提取信息,并对其进行标准化以构建结构化数据库。

Gemini 可以生成 JSON 或枚举值作为结构化输出。

生成 JSON ​

您可以通过以下两种方式使用 Gemini API 生成 JSON:

在模型上配置架构 在文本提示中提供架构 在模型上配置架构是生成 JSON 的推荐方法,因为它会限制模型输出 JSON。

配置架构(推荐) 如需将模型限制为生成 JSON,请配置 responseSchema。然后,模型将以 JSON 格式的输出回答任何问题。 示例:

js
curl "https://mishu.one/google/v1beta/models/gemini-2.5-flash:generateContent?key=$MISHU_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

输出:

js
[
  {
    "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"
    ]
  },
  ...
]

生成枚举值 ​

在某些情况下,您可能希望模型从选项列表中选择单个选项。如需实现此行为,您可以在架构中传递枚举。您可以在 responseSchema 中可以使用 string 的任何位置使用枚举选项,因为枚举是字符串数组。与 JSON 架构一样,枚举可让您约束模型输出,以满足应用的要求。

例如,假设您正在开发一款应用,用于将乐器分类到以下五个类别之一:"Percussion"、"String"、"Woodwind"、"Brass" 或“"Keyboard"”。您可以创建一个枚举来帮助完成此任务。

在以下示例中,您将枚举作为 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(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

Mishu · API 开发文档