"Structured outputs"(结构化输出)会约束 Claude 的响应遵循特定的模式(schema),确保输出有效且可解析,以便进行下游处理。结构化输出提供两个互补的功能:
output_config.format):以特定的 JSON 格式获取 Claude 的响应strict: true):保证对工具名称和输入进行模式验证您可以独立使用这些功能,也可以在同一请求中组合使用。
如果不使用结构化输出,Claude 可能会生成格式错误的 JSON 响应或无效的工具输入,从而破坏您的应用程序。即使经过精心的提示设计,您仍可能遇到:
结构化输出通过约束解码(constrained decoding)保证响应符合模式:
JSON.parse() 错误JSON 输出控制 Claude 的响应格式,确保 Claude 返回与您的模式匹配的有效 JSON。在以下情况下使用 JSON 输出:
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-5",
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(next(block.text for block in response.content if block.type == "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,在响应的文本内容块中返回。
各 SDK 提供了辅助工具,使 JSON 输出的使用更加便捷,包括模式转换、自动验证以及与流行模式库的集成。
您可以使用所用语言中熟悉的模式定义工具,而无需编写原始 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-5",
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 的页面。
client.messages.parse()(推荐)
parse() 方法会自动转换您的 Pydantic 模型、验证响应,并返回一个 parsed_output 属性。
from pydantic import BaseModel
class ContactInfo(BaseModel):
name: str
email: str
plan_interest: str
response = client.messages.parse(
model="claude-opus-5",
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Extract contact info: John Smith, [email protected], interested in the Pro plan",
}
],
output_format=ContactInfo,
)
# 直接访问解析后的输出
contact = response.parsed_output
print(contact.name, contact.email)transform_schema() 辅助函数
适用于需要在发送前手动转换模式,或希望修改 Pydantic 生成的模式的情况。与自动转换所提供模式的 client.messages.parse() 不同,此函数会返回转换后的模式,以便您进一步自定义。
from anthropic import transform_schema
from pydantic import TypeAdapter
# 首先将 Pydantic 模型转换为 JSON schema,然后进行转换
schema = TypeAdapter(ContactInfo).json_schema()
schema = transform_schema(schema)
# 根据需要修改 schema
schema["properties"]["custom_field"] = {"type": "string"}
response = client.messages.create(
model="claude-opus-5",
max_tokens=1024,
messages=[{"role": "user", "content": "..."}],
output_config={
"format": {"type": "json_schema", "schema": schema},
},
)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-5",
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 输出和严格工具使用都受这些限制约束。
使用结构化输出时,对象中的属性会保持您在模式中定义的顺序,但有一个重要的注意事项:必填属性排在前面,然后是可选属性。
例如,给定以下模式:
{
"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"])的参数总数。这些参数的开销特别大,因为它们会导致指数级的编译成本。 |
除了上表中的显式限制外,编译后的语法大小还有其他内部限制。这些限制的存在是因为模式复杂度无法简化为单一维度:可选参数、联合类型、嵌套对象和工具数量等特性会相互作用,可能使编译后的语法变得不成比例地庞大。
当超出这些限制时,您将收到 400 错误,消息为"Schema is too complex for compilation"(模式过于复杂,无法编译)。这些错误意味着您的模式的组合复杂度超出了可高效编译的范围,即使上表中的每个单独限制都已满足。作为最后的保障措施,API 还强制执行 180 秒的编译超时。通过所有显式检查但生成非常大的编译语法的模式可能会触发此超时。
如果您遇到复杂度限制,请按顺序尝试以下策略:
仅将关键工具标记为严格。 如果您有许多工具,请将严格模式保留给那些模式违规会导致实际问题的工具,对于较简单的工具则依赖 Claude 的自然遵循能力。
减少可选参数。 尽可能将参数设为 required。每个可选参数大约会使语法状态空间的一部分翻倍。如果某个参数始终有合理的默认值,请考虑将其设为必填,并让 Claude 显式提供该默认值。
简化嵌套结构。 带有可选字段的深度嵌套对象会加剧复杂度。尽可能扁平化结构。
拆分为多个请求。 如果您有许多严格工具,请考虑将它们拆分到单独的请求或子智能体中。
如果有效模式仍持续出现问题,请联系支持团队并提供您的模式定义。
使用结构化输出时,提示和响应通过 ZDR(零数据保留)处理。但是,出于优化目的,JSON 模式本身会从最后一次使用起临时缓存最多 24 小时。除 API 响应外,不会保留任何提示或响应数据。
结构化输出符合 HIPAA 资格,但 JSON 模式定义中不得包含 PHI(受保护的健康信息)。API 会将 JSON 模式编译成语法,这些语法与消息内容分开缓存,并且这些缓存的模式不会获得与提示和响应相同的 PHI 保护。请勿在模式属性名称、enum 值、const 值或 pattern 正则表达式中包含 PHI。PHI 应仅出现在消息内容(提示和响应)中,在那里它受 HIPAA 保障措施的保护。
有关所有功能的 ZDR 和 HIPAA 资格,请参阅 API 和数据保留。
兼容:
output_config.format)和严格工具使用(strict: true)不兼容:
output_config.format 的同时启用引用,将返回 400 错误。让 Claude 在回答有关所提供文档的问题时引用其来源。
通过语法约束采样对 Claude 的工具输入强制执行 JSON Schema 合规性。
将 Claude 连接到外部工具和 API。了解工具在何处执行以及智能体循环的工作原理。
了解 Anthropic 针对模型和功能的定价结构。
| Supported models |
|
|---|---|
| Supported platforms |
Was this page helpful?