Was this page helpful?
结构化输出将 Claude 的响应限制为遵循特定模式,确保为下游处理提供有效的、可解析的输出。提供两种互补功能:
output_config.format):以特定 JSON 格式获取 Claude 的响应strict: true):保证对工具名称和输入进行模式验证这些功能可以独立使用,也可以在同一请求中一起使用。
结构化输出在 Claude API 和 Amazon Bedrock 上已正式发布,支持 Claude Opus 4.6、Claude Sonnet 4.6、Claude Sonnet 4.5、Claude Opus 4.5 和 Claude Haiku 4.5。结构化输出在 Microsoft Foundry 上仍处于公开测试阶段。
This feature qualifies for Zero Data Retention (ZDR) with limited technical retention. See the Data retention section for details on what is retained and why.
从测试版迁移? output_format 参数已移至 output_config.format,不再需要测试版请求头。旧的测试版请求头(structured-outputs-2025-11-13)和 output_format 参数将在过渡期内继续有效。请参阅下方代码示例了解更新后的 API 结构。
如果不使用结构化输出,Claude 可能会生成格式错误的 JSON 响应或无效的工具输入,从而破坏您的应用程序。即使经过仔细的提示,您也可能遇到:
结构化输出通过受约束的解码来保证符合模式的响应:
JSON.parse() 错误JSON 输出控制 Claude 的响应格式,确保 Claude 返回与您的模式匹配的有效 JSON。在以下情况下使用 JSON 输出:
响应格式: 在 response.content[0].text 中返回与您的模式匹配的有效 JSON
{
"name": "John Smith",
"email": "[email protected]",
"plan_interest": "Enterprise",
"demo_requested": true
}定义您的 JSON 模式
创建一个描述您希望 Claude 遵循的结构的 JSON 模式。该模式使用标准 JSON Schema 格式,但有一些限制(请参阅 JSON Schema 限制)。
添加 output_config.format 参数
在您的 API 请求中包含 output_config.format 参数,设置 type: "json_schema" 并提供您的模式定义。
解析响应
Claude 的响应将是与您的模式匹配的有效 JSON,在 response.content[0].text 中返回。
SDK 提供了辅助工具,使处理 JSON 输出更加便捷,包括模式转换、自动验证以及与流行模式库的集成。
SDK 辅助方法(如 .parse() 和 Pydantic/Zod 集成)仍接受 output_format 作为便捷参数。SDK 在内部处理到 output_config.format 的转换。以下示例展示了 SDK 辅助语法。
您可以使用语言中熟悉的模式定义工具,而无需编写原始 JSON 模式:
client.messages.parse() 的 Pydantic 模型zodOutputFormat() 的 Zod 模式outputFormat(Class<T>) 自动派生模式的普通 Java 类output_config: {format: Model} 的 Anthropic::BaseModel 类output_config 传递的原始 JSON 模式每个 SDK 都提供了辅助工具,使处理结构化输出更加便捷。请参阅各 SDK 页面了解完整详情。
Python 和 TypeScript SDK 自动转换具有不支持功能的模式:
minimum、maximum、minLength、maxLength)additionalProperties: false这意味着 Claude 接收简化的模式,但您的代码仍通过验证强制执行所有约束。
示例: 带有 minimum: 100 的 Pydantic 字段在发送的模式中变为普通整数,但描述更新为"必须至少为 100",SDK 根据原始约束验证响应。
严格工具使用验证工具参数,确保 Claude 使用正确类型的参数调用您的函数。在以下情况下使用严格工具使用:
构建可靠的智能体系统需要保证模式一致性。没有严格模式,Claude 可能返回不兼容的类型("2" 而不是 2)或缺少必需字段,从而破坏您的函数并导致运行时错误。
严格工具使用保证类型安全的参数:
例如,假设预订系统需要 passengers: int。没有严格模式,Claude 可能提供 passengers: "two" 或 passengers: "2"。使用 strict: true,响应将始终包含 passengers: 2。
响应格式: 工具使用块,其中验证后的输入位于 response.content[x].input
{
"type": "tool_use",
"name": "get_weather",
"input": {
"location": "San Francisco, CA"
}
}保证:
input 严格遵循 input_schemaname 始终有效(来自提供的工具或服务器工具)定义您的工具模式
为您的工具的 input_schema 创建 JSON 模式。该模式使用标准 JSON Schema 格式,但有一些限制(请参阅 JSON Schema 限制)。
添加 strict: true
在您的工具定义中将 "strict": true 设置为顶级属性,与 name、description 和 input_schema 并列。
处理工具调用
当 Claude 使用该工具时,tool_use 块中的 input 字段将严格遵循您的 input_schema,且 name 始终有效。
JSON 输出和严格工具使用解决不同的问题,可以一起使用:
结合使用时,Claude 可以使用有保障的有效参数调用工具,并返回结构化的 JSON 响应。这对于需要可靠工具调用和结构化最终输出的智能体工作流非常有用。
结构化输出使用带有已编译语法构件的约束采样。这引入了一些需要注意的性能特性:
name 或 description 字段不会使缓存失效使用结构化输出时,Claude 会自动收到一个额外的系统提示,说明预期的输出格式。这意味着:
output_config.format 参数将使该对话线程的任何提示词缓存失效结构化输出支持标准 JSON Schema,但有一些限制。JSON 输出和严格工具使用共享这些限制。
Python 和 TypeScript SDK 可以通过删除不支持的功能并在字段描述中添加约束来自动转换包含不支持功能的 schema。详情请参阅 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"达到 token 限制(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 复杂度不能简化为单一维度:可选参数、联合类型、嵌套对象和工具数量等功能相互作用,可能使已编译的语法变得不成比例地大。
当超出这些限制时,您将收到带有消息"Schema is too complex for compilation"的 400 错误。这些错误意味着您的 schema 的组合复杂度超出了可以有效编译的范围,即使上述每个单独的限制都满足。作为最后的保障,API 还强制执行 180 秒的编译超时。通过所有明确检查但产生非常大的已编译语法的 schema 可能会触发此超时。
如果您遇到复杂度限制,请按顺序尝试以下策略:
仅将关键工具标记为严格。 如果您有许多工具,请将其保留给 schema 违规会导致真正问题的工具,并依赖 Claude 对更简单工具的自然遵从。
减少可选参数。 尽可能将参数设为 required。每个可选参数大约会使语法状态空间的一部分翻倍。如果参数始终有合理的默认值,请考虑将其设为必填,并让 Claude 明确提供该默认值。
简化嵌套结构。 具有可选字段的深度嵌套对象会加剧复杂度。尽可能扁平化结构。
拆分为多个请求。 如果您有许多严格工具,请考虑将它们拆分到单独的请求或子智能体中。
对于有效 schema 的持续问题,请联系支持并提供您的 schema 定义。
使用结构化输出时,提示词和响应通过 ZDR 处理。但是,JSON schema 本身会从最后一次使用起临时缓存最多 24 小时,用于优化目的。API 响应之外不会保留任何提示词或响应数据。
有关所有功能的 ZDR 资格,请参阅 API 和数据保留。
兼容:
output_config.format)和严格工具使用(strict: true)不兼容:
output_config.format 中启用引用,则返回 400 错误。语法范围:语法仅适用于 Claude 的直接输出,不适用于工具使用调用、工具结果或思考标签(使用扩展思考时)。语法状态在各部分之间重置,允许 Claude 自由思考,同时在最终响应中仍然产生结构化输出。
curl https://api.anthropic.com/v1/messages \
-H "content-type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-opus-4-6",
"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
}
}
}
}'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-6",
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)curl https://api.anthropic.com/v1/messages \
-H "content-type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-opus-4-6",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "What is the weather in San Francisco?"}
],
"tools": [{
"name": "get_weather",
"description": "Get the current weather in a given location",
"strict": true,
"input_schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"]
}
},
"required": ["location"],
"additionalProperties": false
}
}]
}'response = client.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
messages=[
{"role": "user", "content": "Help me plan a trip to Paris for next month"}
],
# JSON outputs: structured response format
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,
},
}
},
# Strict tool use: guaranteed tool parameters
tools=[
{
"name": "search_flights",
"strict": True,
"input_schema": {
"type": "object",
"properties": {
"destination": {"type": "string"},
"date": {"type": "string", "format": "date"},
},
"required": ["destination", "date"],
"additionalProperties": False,
},
}
],
)