结构化输出(structured outputs)约束 Claude 的响应遵循特定的模式(schema),确保输出有效、可解析,便于下游处理。结构化输出提供两个互补的功能:
output_config.format):以特定的 JSON 格式获取 Claude 的响应strict: true):保证对工具名称和输入进行模式验证您可以在同一请求中独立或组合使用这些功能。
结构化输出已在 Claude API 上正式可用,适用于 Claude Fable 5、Claude Mythos 5、Claude Opus 4.8、Claude Mythos Preview、Claude Opus 4.7、Claude Opus 4.6、Claude Sonnet 5、Claude Sonnet 4.6、Claude Sonnet 4.5、Claude Opus 4.5 和 Claude Haiku 4.5。在 Amazon Bedrock 上,结构化输出已正式可用于 Claude Opus 4.6、Claude Sonnet 4.6、Claude Sonnet 4.5、Claude Opus 4.5 和 Claude Haiku 4.5;Claude Sonnet 5、Claude Opus 4.7 和 Claude Mythos Preview 可通过 Claude in Amazon Bedrock(Messages-API Bedrock 端点)使用。结构化输出可在 Claude Platform on AWS 上使用。在 Google Cloud 上,结构化输出已正式可用于 Claude Fable 5、Claude Mythos 5、Claude Opus 4.8、Claude Mythos Preview、Claude Opus 4.7、Claude Opus 4.6、Claude Sonnet 5、Claude Sonnet 4.6、Claude Sonnet 4.5、Claude Opus 4.5 和 Claude Haiku 4.5。结构化输出已在 Microsoft Foundry 上正式可用,并且需要 Hosted on Anthropic 部署。
此功能符合零数据保留(ZDR)的条件,但存在有限的技术性保留。有关保留内容及原因的详细信息,请参阅数据保留部分。
正在从 beta 迁移? output_format 参数已移至 output_config.format,并且不再需要 beta 标头。旧的 beta 标头(structured-outputs-2025-11-13)和 output_format 参数将在过渡期内继续有效。请参阅以下代码示例了解更新后的 API 形式。
如果不使用结构化输出,Claude 可能会生成格式错误的 JSON 响应或无效的工具输入,从而破坏您的应用程序。即使经过精心设计的提示,您仍可能遇到:
结构化输出通过约束解码(constrained decoding)保证响应符合模式:
JSON.parse() 错误JSON 输出控制 Claude 的响应格式,确保 Claude 返回与您的模式匹配的有效 JSON。在以下情况下使用 JSON 输出:
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-4-8",
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Extract the key information from this email: John Smith ([email protected]) is interested in our Enterprise plan and wants to schedule a demo for next Tuesday at 2pm.",
}
],
output_config={
"format": {
"type": "json_schema",
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"email": {"type": "string"},
"plan_interest": {"type": "string"},
"demo_requested": {"type": "boolean"},
},
"required": ["name", "email", "plan_interest", "demo_requested"],
"additionalProperties": False,
},
}
},
)
print(response.content[0].text)响应格式: 在 response.content[0].text 中返回与您的模式匹配的有效 JSON
{
"name": "John Smith",
"email": "[email protected]",
"plan_interest": "Enterprise",
"demo_requested": true
}定义您的 JSON 模式
创建一个 JSON 模式来描述您希望 Claude 遵循的结构。该模式使用标准 JSON Schema 格式,但有一些限制(请参阅 JSON Schema 限制)。
添加 output_config.format 参数
在您的 API 请求中包含 output_config.format 参数,设置 type: "json_schema" 和您的模式定义。
解析响应
Claude 的响应是与您的模式匹配的有效 JSON,在 response.content[0].text 中返回。
SDK 提供了辅助工具,使 JSON 输出的使用更加容易,包括模式转换、自动验证以及与流行模式库的集成。
Python SDK 的 client.messages.parse() 仍然接受 output_format 作为便捷参数,并在内部将其转换为 output_config.format。其他 SDK 需要直接使用 output_config。以下示例展示了 SDK 辅助工具的语法。
您可以使用您所用语言中熟悉的模式定义工具,而不必编写原始 JSON 模式:
client.messages.parse()zodOutputFormat(),或类型化的 JSON Schema 字面量配合 jsonSchemaOutputFormat()outputConfig(Class<T>) 自动派生模式Anthropic::BaseModel 类配合 output_config: {format: Model}StructuredOutputModel 的类配合 outputConfig: ['format' => MyClass::class]Create<T>() 重载,自动派生模式output_config 使用原始 JSON 模式output_config 传递原始 JSON 模式from pydantic import BaseModel
from anthropic import Anthropic
class ContactInfo(BaseModel):
name: str
email: str
plan_interest: str
demo_requested: bool
client = Anthropic()
response = client.messages.parse(
model="claude-opus-4-8",
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Extract the key information from this email: John Smith ([email protected]) is interested in our Enterprise plan and wants to schedule a demo for next Tuesday at 2pm.",
}
],
output_format=ContactInfo,
)
print(response.parsed_output)每个 SDK 都提供了使结构化输出更易于使用的辅助工具。请参阅各个 SDK 页面了解完整详情。
通过 heredoc 主体传递原始 JSON 模式
CLI 将原始 JSON 模式作为 YAML heredoc 主体传递。使用 GJSON 的 @fromstr 修饰符配合 --transform 来解析 content[0].text 中返回的 JSON 字符串并投影特定字段。
ant messages create \
--transform 'content.0.text|@fromstr|{name,email}' \
--format yaml <<'YAML'
model: claude-opus-4-8
max_tokens: 1024
messages:
- role: user
content: >-
Extract contact info: John Smith, [email protected],
interested in the Pro plan
output_config:
format:
type: json_schema
schema:
type: object
properties:
name: {type: string}
email: {type: string}
plan_interest: {type: string}
required: [name, email, plan_interest]
additionalProperties: false
YAMLname: John Smith
email: [email protected]Python、TypeScript、Ruby 和 PHP SDK 会自动转换包含不支持功能的模式。当模式从原生类型派生时(C# 中的 Create<T>();Go beta API 上的结构体反射或 BetaJSONSchemaOutputFormat()),C# 和 Go SDK 会应用相同的转换。转换步骤:
minimum、maximum、minLength、maxLength)additionalProperties: false这意味着 Claude 收到的是简化后的模式,但您的代码仍然通过验证强制执行所有约束。
示例: 带有 minimum: 100 的 Pydantic 字段在发送的模式中变为普通整数,但 SDK 会将描述更新为"必须至少为 100",并根据原始约束验证响应。
有关使用语法约束采样对工具输入强制执行 JSON Schema 合规性的信息,请参阅严格工具使用。
JSON 输出和严格工具使用解决不同的问题,并且可以协同工作:
结合使用时,Claude 可以使用保证有效的参数调用工具,并返回结构化的 JSON 响应。这对于既需要可靠的工具调用又需要结构化最终输出的代理工作流非常有用。
response = client.messages.create(
model="claude-opus-4-8",
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Help me plan a trip to Paris departing May 15, 2026",
}
],
# JSON 输出:结构化响应格式
output_config={
"format": {
"type": "json_schema",
"schema": {
"type": "object",
"properties": {
"summary": {"type": "string"},
"next_steps": {"type": "array", "items": {"type": "string"}},
},
"required": ["summary", "next_steps"],
"additionalProperties": False,
},
}
},
# 严格工具使用:有保证的工具参数
tools=[
{
"name": "search_flights",
"strict": True,
"input_schema": {
"type": "object",
"properties": {
"destination": {"type": "string"},
"date": {"type": "string", "format": "date"},
},
"required": ["destination", "date"],
"additionalProperties": False,
},
}
],
)
print(response)结构化输出使用带有已编译语法产物的约束采样。这会引入一些需要注意的性能特征:
name 或 description 字段不会使缓存失效使用结构化输出时,Claude 会自动收到一个额外的系统提示,解释预期的输出格式。这意味着:
output_config.format 参数将使该对话线程的任何提示缓存失效结构化输出支持标准 JSON Schema,但有一些限制。JSON 输出和严格工具使用共享这些限制。
Python、TypeScript、Ruby 和 PHP SDK 可以通过移除不支持的功能并将约束添加到字段描述中来自动转换模式。当模式从原生类型派生时,C# 和 Go SDK 也会执行相同的操作。有关详细信息,请参阅 SDK 特定方法。
使用结构化输出时,对象中的属性会保持您模式中定义的顺序,但有一个重要的注意事项:必需属性排在前面,然后是可选属性。
例如,给定以下模式:
{
"type": "object",
"properties": {
"notes": { "type": "string" },
"name": { "type": "string" },
"email": { "type": "string" },
"age": { "type": "integer" }
},
"required": ["name", "email"],
"additionalProperties": false
}输出将按以下顺序排列属性:
name(必需,按模式顺序)email(必需,按模式顺序)notes(可选,按模式顺序)age(可选,按模式顺序)这意味着输出可能如下所示:
{
"name": "John Smith",
"email": "[email protected]",
"notes": "Interested in enterprise plan",
"age": 35
}如果输出中的属性顺序对您的应用程序很重要,请将所有属性标记为必需,或在解析逻辑中考虑这种重新排序。
虽然结构化输出在大多数情况下保证符合模式,但在某些场景下输出可能与您的模式不匹配:
拒绝(stop_reason: "refusal")
即使使用结构化输出,Claude 也会保持其安全性和有用性特性。如果 Claude 出于安全原因拒绝请求:
stop_reason 为 "refusal"达到令牌限制(stop_reason: "max_tokens")
如果响应因达到 max_tokens 限制而被截断:
stop_reason 为 "max_tokens"max_tokens 值重试以获取完整的结构化输出枚举值大小写
结构化输出不保证字符串 enum 和 const 值的大小写:Claude 可能返回一个仅在大小写上与您的模式不同的值,通常是空格后单词的首字母。例如,给定以下模式:
{
"type": "string",
"enum": ["Conversation Topic 1", "Conversation Topic 2", "Conversation topic 3"]
}输出可能包含 "Conversation Topic 3"(大写"T"),即使该确切值不在枚举中。响应会正常完成,没有错误,也没有特殊的 stop_reason。这适用于 JSON 输出和严格工具使用。请以不区分大小写的方式比较枚举值,并避免使用仅在大小写上不同的枚举值。
结构化输出的工作原理是将您的 JSON 模式编译为约束 Claude 输出的语法。更复杂的模式会产生更大的语法,编译时间更长。为了防止编译时间过长,API 强制执行多项复杂度限制。
以下限制适用于所有带有 output_config.format 或 strict: true 的请求:
| 限制 | 值 | 描述 |
|---|---|---|
| 每个请求的严格工具数 | 20 | 带有 strict: true 的工具的最大数量。非严格工具不计入此限制。 |
| 可选参数 | 24 | 所有严格工具模式和 JSON 输出模式中的可选参数总数。每个未在 required 中列出的参数都计入此限制。 |
| 使用联合类型的参数 | 16 | 所有严格模式中使用 anyOf 或类型数组(例如 "type": ["string", "null"])的参数总数。这些参数特别昂贵,因为它们会产生指数级的编译成本。 |
这些限制适用于单个请求中所有严格模式的合计总数。例如,如果您有 4 个严格工具,每个工具有 6 个可选参数,即使没有任何单个工具看起来复杂,您也会达到 24 个参数的限制。
除了上表中的显式限制之外,对已编译语法的大小还有额外的内部限制。这些限制之所以存在,是因为模式复杂度无法简化为单一维度:可选参数、联合类型、嵌套对象和工具数量等特性会相互作用,可能使已编译的语法变得不成比例地庞大。
当超出这些限制时,您将收到带有消息"Schema is too complex for compilation"的 400 错误。这些错误意味着您的模式的综合复杂度超出了可以高效编译的范围,即使上表中的每个单独限制都得到满足。作为最后的保障措施,API 还强制执行 180 秒的编译超时。通过所有显式检查但产生非常大的已编译语法的模式可能会触发此超时。
如果您遇到复杂度限制,请按顺序尝试以下策略:
仅将关键工具标记为严格。 如果您有许多工具,请将其保留给模式违规会导致实际问题的工具,对于较简单的工具则依赖 Claude 的自然遵循能力。
减少可选参数。 尽可能将参数设为 required。每个可选参数大约会使语法状态空间的一部分翻倍。如果某个参数始终有合理的默认值,请考虑将其设为必需,并让 Claude 显式提供该默认值。
简化嵌套结构。 带有可选字段的深度嵌套对象会加剧复杂度。尽可能扁平化结构。
拆分为多个请求。 如果您有许多严格工具,请考虑将它们拆分到单独的请求或子代理中。
对于有效模式的持续性问题,请联系支持并提供您的模式定义。
使用结构化输出时,提示和响应会以 ZDR 方式处理。但是,JSON 模式本身会自最后一次使用起临时缓存最多 24 小时,以用于优化目的。除 API 响应外,不会保留任何提示或响应数据。
结构化输出符合 HIPAA 资格,但 PHI 不得包含在 JSON 模式定义中。API 将 JSON 模式编译为与消息内容分开缓存的语法,这些缓存的模式不会获得与提示和响应相同的 PHI 保护。请勿在模式属性名称、enum 值、const 值或 pattern 正则表达式中包含 PHI。PHI 只应出现在消息内容(提示和响应)中,在那里它受到 HIPAA 保护措施的保护。
有关所有功能的 ZDR 和 HIPAA 资格,请参阅 API 与数据保留。
兼容:
output_config.format)和严格工具使用(strict: true)不兼容:
output_config.format,将返回 400 错误。语法作用域: 语法仅适用于 Claude 的直接输出,不适用于工具使用调用、工具结果或思考标签(使用扩展思考时)。语法状态在各部分之间重置,使 Claude 可以自由思考,同时仍在最终响应中生成结构化输出。
让 Claude 在回答有关所提供文档的问题时引用其来源。
使用语法约束采样对 Claude 的工具输入强制执行 JSON Schema 合规性。
将 Claude 连接到外部工具和 API。了解工具在何处执行以及代理循环的工作原理。
了解 Anthropic 的模型和功能定价结构。
Was this page helpful?