"Structured outputs"(结构化输出)将 Claude 的响应约束为遵循特定的 schema(模式),确保输出有效、可解析,便于下游处理。结构化输出提供两个互补的功能:
output_config.format):以特定的 JSON 格式获取 Claude 的响应strict: true):保证对工具名称和输入进行 schema 验证您可以在同一请求中单独或同时使用这些功能。
如果没有结构化输出,Claude 可能会生成格式错误的 JSON 响应或无效的工具输入,从而破坏您的应用程序。即使精心设计提示,您仍可能遇到:
结构化输出通过"constrained decoding"(约束解码)保证响应符合 schema:
JSON.parse() 错误JSON 输出控制 Claude 的响应格式,确保 Claude 返回与您的 schema 匹配的有效 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 (john@example.com) 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"))响应格式: 响应的文本内容块中包含与您的 schema 匹配的有效 JSON
{
"name": "John Smith",
"email": "john@example.com",
"plan_interest": "Enterprise",
"demo_requested": true
}定义您的 JSON schema
创建一个 JSON schema 来描述您希望 Claude 遵循的结构。该 schema 使用标准 JSON Schema 格式,但有一些限制(请参阅 JSON Schema 限制)。
添加 output_config.format 参数
在您的 API 请求中包含 output_config.format 参数,设置 type: "json_schema" 并提供您的 schema 定义。
解析响应
Claude 的响应是与您的 schema 匹配的有效 JSON,在响应的文本内容块中返回。
SDK 提供了辅助工具,使 JSON 输出的使用更加便捷,包括 schema 转换、自动验证以及与流行 schema 库的集成。
您可以使用所用语言中熟悉的 schema 定义工具,而不必编写原始 JSON schema:
client.messages.parse()zodOutputFormat(),或带类型的 JSON Schema 字面量配合 jsonSchemaOutputFormat()outputConfig(Class<T>) 自动派生 schemaAnthropic::BaseModel 类配合 output_config: {format: Model}StructuredOutputModel 的类配合 outputConfig: ['format' => MyClass::class]Create<T>() 重载,自动派生 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-5",
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Extract the key information from this email: John Smith (john@example.com) 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, john@example.com, interested in the Pro plan",
}
],
output_format=ContactInfo,
)
# 直接访问解析后的输出
contact = response.parsed_output
print(contact.name, contact.email)transform_schema() 辅助函数
适用于需要在发送前手动转换 schema,或希望修改 Pydantic 生成的 schema 的情况。与自动转换所提供 schema 的 client.messages.parse() 不同,此函数会返回转换后的 schema,以便您进一步自定义。
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 会自动转换包含不支持功能的 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 会将描述更新为"Must be at least 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 输出和严格工具使用共享这些限制。
使用结构化输出时,对象中的属性会保持您在 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": "john@example.com",
"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 值重试以获取完整的结构化输出枚举值大小写
结构化输出不保证字符串 enum 和 const 值的大小写:Claude 可能返回一个仅在大小写上与您的 schema 不同的值,通常是空格后单词的首字母。例如,给定以下 schema:
{
"type": "string",
"enum": ["Conversation Topic 1", "Conversation Topic 2", "Conversation topic 3"]
}输出可能包含 "Conversation Topic 3"(大写"T"),即使该确切值不在枚举中。响应会正常完成,没有错误,也没有特殊的 stop_reason。这同时适用于 JSON 输出和严格工具使用。请以不区分大小写的方式比较枚举值,并避免使用仅在大小写上不同的枚举值。
结构化输出的工作方式是将您的 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 复杂度无法归结为单一维度:可选参数、联合类型、嵌套对象和工具数量等特性会相互作用,可能使已编译的语法变得不成比例地庞大。
超出这些限制时,您将收到消息为"Schema is too complex for compilation."的 400 错误。这些错误意味着您的 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 的工具输入强制执行 JSON Schema 合规性。
将 Claude 连接到外部工具和 API。了解工具在何处执行以及智能体循环的工作原理。
了解 Anthropic 针对模型和功能的定价结构。
| Supported models |
|
|---|---|
| Supported platforms |
Was this page helpful?