Was this page helpful?
结构化输出约束 Claude 的响应遵循特定的模式,确保输出有效、可解析,便于下游处理。提供两个互补功能:
output_config.format):以特定 JSON 格式获取 Claude 的响应strict: true):保证工具名称和输入的模式验证output_format 参数已移至 output_config.format。旧的 output_format 参数暂时仍然有效,但已弃用,将在未来的 API 版本中移除。请更新您的代码以使用 output_config: {format: {...}}。
这些功能可以在同一请求中独立使用或组合使用。
结构化输出已在 Claude API 和 Amazon Bedrock 上正式发布,支持 Claude Opus 4.6、Claude Sonnet 4.5、Claude Opus 4.5 和 Claude Haiku 4.5。结构化输出在 Microsoft Foundry 上仍处于公开测试阶段。
从测试版迁移? 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 模式
创建一个 JSON 模式来描述您希望 Claude 遵循的结构。该模式使用标准 JSON Schema 格式,但有一些限制(参见 JSON Schema 限制)。
添加 output_config.format 参数
在您的 API 请求中包含 output_config.format 参数,设置 type: "json_schema" 和您的模式定义。
解析响应
Claude 的响应将是与您的模式匹配的有效 JSON,在 response.content[0].text 中返回。
Python 和 TypeScript SDK 提供了辅助工具,使 JSON 输出的使用更加便捷,包括模式转换、自动验证以及与流行模式库的集成。
SDK 辅助方法(如 .parse() 和 Pydantic/Zod 集成)仍然接受 output_format 作为便捷参数。SDK 会在内部将其转换为 output_config.format。以下示例展示的是 SDK 辅助语法。
对于 Python 和 TypeScript 开发者,您可以使用熟悉的模式定义工具(如 Pydantic 和 Zod)来替代编写原始 JSON 模式。
Python:client.messages.parse()(推荐)
parse() 方法会自动转换您的 Pydantic 模型、验证响应,并返回 parsed_output 属性。
Python:transform_schema() 辅助函数
当您需要在发送前手动转换模式,或者想要修改 Pydantic 生成的模式时使用。与 client.messages.parse() 自动转换提供的模式不同,此函数会返回转换后的模式供您进一步自定义。
Python 和 TypeScript SDK 都会自动转换包含不支持特性的模式:
minimum、maximum、minLength、maxLength)additionalProperties: false这意味着 Claude 接收到的是简化后的模式,但您的代码仍然通过验证来强制执行所有约束。
示例: 带有 minimum: 100 的 Pydantic 字段在发送的模式中变为普通整数,但描述会更新为 "Must be at least 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 可以自动转换包含不支持特性的模式,方法是移除这些特性并将约束添加到字段描述中。详情请参阅 SDK 特定方法。
虽然结构化输出在大多数情况下保证模式合规,但在某些场景下输出可能不匹配您的模式:
拒绝(stop_reason: "refusal")
即使使用结构化输出,Claude 仍然保持其安全性和有用性特性。如果 Claude 出于安全原因拒绝请求:
stop_reason: "refusal"达到 token 限制(stop_reason: "max_tokens")
如果响应因达到 max_tokens 限制而被截断:
stop_reason: "max_tokens"max_tokens 值重试以获取完整的结构化输出如果您的模式使用了不支持的特性或过于复杂,您将收到 400 错误:
"Too many recursive definitions in schema"
"Schema is too complex"
strict: true 的工具数量对于有效模式的持续问题,请联系支持并提供您的模式定义。
兼容:
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, transform_schema
class ContactInfo(BaseModel):
name: str
email: str
plan_interest: str
demo_requested: bool
client = Anthropic()
# 使用 .create() - 需要 transform_schema()
response = client.messages.create(
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": transform_schema(ContactInfo),
}
}
)
print(response.content[0].text)
# 使用 .parse() - 可以直接传递 Pydantic 模型
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 输出:结构化响应格式
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
}
}]
)