结构化输出会约束 Claude 的响应遵循特定的 schema(模式),确保输出有效且可解析,便于下游处理。结构化输出提供两个互补的功能:
output_config.format):以特定的 JSON 格式获取 Claude 的响应strict: true):保证对工具名称和输入进行 schema 验证您可以在同一请求中独立使用这些功能,也可以组合使用。
结构化输出在 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 响应或无效的工具输入,从而导致您的应用程序出错。即使经过精心设计的提示,您仍可能遇到:
结构化输出通过约束解码保证响应符合 schema:
JSON.parse() 错误JSON 输出控制 Claude 的响应格式,确保 Claude 返回与您的 schema 匹配的有效 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 中返回与您的 schema 匹配的有效 JSON
{
"name": "John Smith",
"email": "[email protected]",
"plan_interest": "Enterprise",
"demo_requested": true
}定义您的 JSON schema
创建一个描述您希望 Claude 遵循的结构的 JSON schema。该 schema 使用标准的 JSON Schema 格式,但有一些限制(请参阅 JSON Schema 限制)。
添加 output_config.format 参数
在您的 API 请求中包含 output_config.format 参数,并设置 type: "json_schema" 以及您的 schema 定义。
解析响应
Claude 的响应是与您的 schema 匹配的有效 JSON,在 response.content[0].text 中返回。
SDK 提供了辅助工具,使 JSON 输出的使用更加便捷,包括 schema 转换、自动验证以及与流行 schema 库的集成。
Python SDK 的 client.messages.parse() 仍接受 output_format 作为便捷参数,并在内部将其转换为 output_config.format。其他 SDK 需要直接使用 output_config。以下示例展示了 SDK 辅助工具的语法。
您无需编写原始 JSON schema,而是可以使用您所用语言中熟悉的 schema 定义工具:
client.messages.parse() 使用 Pydantic 模型zodOutputFormat() 使用 Zod schema,或通过 jsonSchemaOutputFormat() 使用类型化的 JSON Schema 字面量outputConfig(Class<T>) 使用普通 Java 类并自动派生 schemaoutput_config: {format: Model} 使用 Anthropic::BaseModel 类outputConfig: ['format' => MyClass::class] 使用实现 StructuredOutputModel 的类Create<T>() 重载使用普通 C# 类,自动派生 schemaoutput_config 使用原始 JSON schemaoutput_config 传递原始 JSON schemafrom 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 页面。
Python、TypeScript、Ruby 和 PHP SDK 会自动转换包含不支持功能的 schema。当 schema 从原生类型派生时(C# 中的 Create<T>();Go beta API 上的结构体反射或 BetaJSONSchemaOutputFormat()),C# 和 Go SDK 也会应用相同的转换。转换步骤如下:
minimum、maximum、minLength、maxLength)additionalProperties: false这意味着 Claude 接收到的是简化后的 schema,但您的代码仍会通过验证强制执行所有约束。
示例: 带有 minimum: 100 的 Pydantic 字段在发送的 schema 中会变成普通整数,但 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 可以自动转换包含不支持功能的 schema,方法是移除这些功能并将约束添加到字段描述中。当 schema 从原生类型派生时,C# 和 Go SDK 也会执行相同的操作。有关详细信息,请参阅 SDK 特定方法。
使用结构化输出时,对象中的属性会保持您在 schema 中定义的顺序,但有一个重要的注意事项:必填属性会先出现,然后是可选属性。
例如,给定以下 schema:
{
"type": "object",
"properties": {
"notes": { "type": "string" },
"name": { "type": "string" },
"email": { "type": "string" },
"age": { "type": "integer" }
},
"required": ["name", "email"],
"additionalProperties": false
}输出中的属性排序如下:
name(必填,按 schema 顺序)email(必填,按 schema 顺序)notes(可选,按 schema 顺序)age(可选,按 schema 顺序)这意味着输出可能如下所示:
{
"name": "John Smith",
"email": "[email protected]",
"notes": "Interested in enterprise plan",
"age": 35
}如果输出中的属性顺序对您的应用程序很重要,请将所有属性标记为必填,或在解析逻辑中考虑这种重新排序。
虽然结构化输出在大多数情况下保证符合 schema,但在某些情况下输出可能与您的 schema 不匹配:
拒绝(stop_reason: "refusal")
即使在使用结构化输出时,Claude 也会保持其安全性和有用性特性。如果 Claude 出于安全原因拒绝请求:
stop_reason 为 "refusal"达到令牌限制(stop_reason: "max_tokens")
如果响应因达到 max_tokens 限制而被截断:
stop_reason 为 "max_tokens"max_tokens 值重试以获取完整的结构化输出结构化输出的工作原理是将您的 JSON schema 编译成约束 Claude 输出的语法。更复杂的 schema 会生成更大的语法,编译时间也更长。为防止编译时间过长,API 强制执行多项复杂度限制。
以下限制适用于所有带有 output_config.format 或 strict: true 的请求:
| 限制 | 值 | 描述 |
|---|---|---|
| 每个请求的严格工具数 | 20 | 带有 strict: true 的工具的最大数量。非严格工具不计入此限制。 |
| 可选参数 | 24 | 所有严格工具 schema 和 JSON 输出 schema 中可选参数的总数。每个未在 required 中列出的参数都计入此限制。 |
| 使用联合类型的参数 | 16 | 所有严格 schema 中使用 anyOf 或类型数组(例如 "type": ["string", "null"])的参数总数。这些参数的成本特别高,因为它们会导致指数级的编译成本。 |
这些限制适用于单个请求中所有严格 schema 的合计总数。例如,如果您有 4 个严格工具,每个工具有 6 个可选参数,即使单个工具看起来并不复杂,您也会达到 24 个参数的限制。
除了上表中的显式限制外,编译后的语法大小还有其他内部限制。这些限制的存在是因为 schema 复杂度无法简化为单一维度:可选参数、联合类型、嵌套对象和工具数量等特性会相互作用,可能导致编译后的语法不成比例地增大。
当超出这些限制时,您将收到 400 错误,消息为"Schema is too complex for compilation"(Schema 过于复杂,无法编译)。这些错误意味着您的 schema 的综合复杂度超出了可高效编译的范围,即使上表中的每个单独限制都已满足。作为最后的保障措施,API 还强制执行 180 秒的编译超时。通过所有显式检查但生成非常大的编译语法的 schema 可能会触发此超时。
如果您遇到复杂度限制,请按顺序尝试以下策略:
仅将关键工具标记为严格。 如果您有许多工具,请将严格模式保留给那些 schema 违规会导致实际问题的工具,对于较简单的工具则依赖 Claude 的自然遵循能力。
减少可选参数。 尽可能将参数设为 required。每个可选参数大约会使语法状态空间的一部分翻倍。如果某个参数始终有合理的默认值,请考虑将其设为必填,并让 Claude 显式提供该默认值。
简化嵌套结构。 带有可选字段的深度嵌套对象会加剧复杂度。尽可能扁平化结构。
拆分为多个请求。 如果您有许多严格工具,请考虑将它们拆分到单独的请求或子智能体中。
如果有效的 schema 持续出现问题,请联系支持团队并提供您的 schema 定义。
使用结构化输出时,提示和响应通过 ZDR(零数据保留)进行处理。但是,出于优化目的,JSON schema 本身会自最后一次使用起临时缓存最多 24 小时。除 API 响应外,不会保留任何提示或响应数据。
结构化输出符合 HIPAA 资格,但 JSON schema 定义中不得包含 PHI(受保护的健康信息)。API 会将 JSON schema 编译成语法,这些语法与消息内容分开缓存,并且这些缓存的 schema 不会获得与提示和响应相同的 PHI 保护。请勿在 schema 属性名称、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?