Loading...
    • 开发者指南
    • API 参考
    • MCP
    • 资源
    • 更新日志
    Search...
    ⌘K
    入门
    Claude 简介快速开始
    模型与定价
    模型概览选择模型Claude 4.6 新特性迁移指南模型弃用定价
    使用 Claude 构建
    功能概览使用 Messages API处理停止原因提示词最佳实践
    模型能力
    扩展思考自适应思考思考力度快速模式(研究预览)结构化输出引用流式消息批量处理PDF 支持搜索结果多语言支持嵌入视觉
    工具
    概览如何实现工具使用网页搜索工具网页获取工具代码执行工具记忆工具Bash 工具计算机使用工具文本编辑器工具
    工具基础设施
    工具搜索编程式工具调用细粒度工具流式传输
    上下文管理
    上下文窗口压缩上下文编辑提示缓存Token 计数
    文件与资源
    Files API
    Agent 技能
    概览快速开始最佳实践企业版技能通过 API 使用技能
    Agent SDK
    概览快速开始TypeScript SDKTypeScript V2(预览)Python SDK迁移指南
    API 中的 MCP
    MCP 连接器远程 MCP 服务器
    第三方平台上的 Claude
    Amazon BedrockMicrosoft FoundryVertex AI
    提示工程
    概览提示词生成器使用提示词模板提示词优化器清晰直接使用示例(多样本提示)让 Claude 思考(思维链)使用 XML 标签赋予 Claude 角色(系统提示词)链式复杂提示长上下文技巧扩展思考技巧
    测试与评估
    定义成功标准开发测试用例使用评估工具降低延迟
    加强安全护栏
    减少幻觉提高输出一致性防范越狱攻击流式拒绝减少提示词泄露保持 Claude 角色一致
    管理与监控
    Admin API 概览数据驻留工作空间用量与成本 APIClaude Code Analytics API零数据留存
    Console
    Log in
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...

    Solutions

    • AI agents
    • Code modernization
    • Coding
    • Customer support
    • Education
    • Financial services
    • Government
    • Life sciences

    Partners

    • Amazon Bedrock
    • Google Cloud's Vertex AI

    Learn

    • Blog
    • Catalog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Company

    • Anthropic
    • Careers
    • Economic Futures
    • Research
    • News
    • Responsible Scaling Policy
    • Security and compliance
    • Transparency

    Learn

    • Blog
    • Catalog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Help and security

    • Availability
    • Status
    • Support
    • Discord

    Terms and policies

    • Privacy policy
    • Responsible disclosure policy
    • Terms of service: Commercial
    • Terms of service: Consumer
    • Usage policy
    模型能力

    结构化输出

    从智能体工作流中获取经过验证的 JSON 结果

    结构化输出约束 Claude 的响应遵循特定的模式,确保输出有效、可解析,便于下游处理。提供两个互补功能:

    • JSON 输出(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 语法导致的解析错误
    • 缺少必填字段
    • 数据类型不一致
    • 需要错误处理和重试的模式违规

    结构化输出通过约束解码保证符合模式的响应:

    • 始终有效:不再出现 JSON.parse() 错误
    • 类型安全:保证字段类型和必填字段
    • 可靠:无需因模式违规而重试

    JSON 输出

    JSON 输出控制 Claude 的响应格式,确保 Claude 返回与您的模式匹配的有效 JSON。在以下场景中使用 JSON 输出:

    • 控制 Claude 的响应格式
    • 从图像或文本中提取数据
    • 生成结构化报告
    • 格式化 API 响应

    快速开始

    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
            }
          }
        }
      }'

    响应格式: 在 response.content[0].text 中返回与您的模式匹配的有效 JSON

    {
      "name": "John Smith",
      "email": "[email protected]",
      "plan_interest": "Enterprise",
      "demo_requested": true
    }

    工作原理

    1. 1

      定义您的 JSON 模式

      创建一个 JSON 模式来描述您希望 Claude 遵循的结构。该模式使用标准 JSON Schema 格式,但有一些限制(参见 JSON Schema 限制)。

    2. 2

      添加 output_config.format 参数

      在您的 API 请求中包含 output_config.format 参数,设置 type: "json_schema" 和您的模式定义。

    3. 3

      解析响应

      Claude 的响应将是与您的模式匹配的有效 JSON,在 response.content[0].text 中返回。

    在 SDK 中使用 JSON 输出

    Python 和 TypeScript SDK 提供了辅助工具,使 JSON 输出的使用更加便捷,包括模式转换、自动验证以及与流行模式库的集成。

    SDK 辅助方法(如 .parse() 和 Pydantic/Zod 集成)仍然接受 output_format 作为便捷参数。SDK 会在内部将其转换为 output_config.format。以下示例展示的是 SDK 辅助语法。

    使用 Pydantic 和 Zod

    对于 Python 和 TypeScript 开发者,您可以使用熟悉的模式定义工具(如 Pydantic 和 Zod)来替代编写原始 JSON 模式。

    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)

    SDK 特定方法

    Python:client.messages.parse()(推荐)

    parse() 方法会自动转换您的 Pydantic 模型、验证响应,并返回 parsed_output 属性。

    Python:transform_schema() 辅助函数

    当您需要在发送前手动转换模式,或者想要修改 Pydantic 生成的模式时使用。与 client.messages.parse() 自动转换提供的模式不同,此函数会返回转换后的模式供您进一步自定义。

    SDK 转换工作原理

    Python 和 TypeScript SDK 都会自动转换包含不支持特性的模式:

    1. 移除不支持的约束(例如 minimum、maximum、minLength、maxLength)
    2. 更新描述以包含约束信息(例如 "Must be at least 100"),当约束不被结构化输出直接支持时
    3. 为所有对象添加 additionalProperties: false
    4. 过滤字符串格式为仅支持的列表
    5. 根据原始模式验证响应(包含所有约束)

    这意味着 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。

    快速开始

    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.content[x].input 中返回包含经过验证的输入的工具使用块

    {
      "type": "tool_use",
      "name": "get_weather",
      "input": {
        "location": "San Francisco, CA"
      }
    }

    保证:

    • 工具 input 严格遵循 input_schema
    • 工具 name 始终有效(来自提供的工具或服务器工具)

    工作原理

    1. 1

      定义您的工具模式

      为工具的 input_schema 创建 JSON 模式。该模式使用标准 JSON Schema 格式,但有一些限制(参见 JSON Schema 限制)。

    2. 2

      添加 strict: true

      在工具定义中将 "strict": true 设置为顶级属性,与 name、description 和 input_schema 并列。

    3. 3

      处理工具调用

      当 Claude 使用工具时,tool_use 块中的 input 字段将严格遵循您的 input_schema,name 将始终有效。

    常见用例

    同时使用两个功能

    JSON 输出和严格工具使用解决不同的问题,可以一起使用:

    • JSON 输出控制 Claude 的响应格式(Claude 说什么)
    • 严格工具使用验证工具参数(Claude 如何调用您的函数)

    组合使用时,Claude 可以使用保证有效的参数调用工具,并返回结构化的 JSON 响应。这对于需要可靠工具调用和结构化最终输出的智能体工作流非常有用。

    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
            }
        }]
    )

    重要注意事项

    语法编译和缓存

    结构化输出使用带有编译语法工件的约束采样。这引入了一些需要注意的性能特征:

    • 首次请求延迟:首次使用特定模式时,语法编译会产生额外延迟
    • 自动缓存:编译后的语法从最后一次使用起缓存 24 小时,使后续请求更快
    • 缓存失效:以下更改会使缓存失效:
      • JSON 模式结构的更改
      • 请求中工具集的更改(同时使用结构化输出和工具使用时)
      • 仅更改 name 或 description 字段不会使缓存失效

    提示词修改和 token 成本

    使用结构化输出时,Claude 会自动接收一个额外的系统提示词来解释预期的输出格式。这意味着:

    • 您的输入 token 数量会略有增加
    • 注入的提示词会像其他系统提示词一样消耗 token
    • 更改 output_config.format 参数将使该对话线程的任何提示词缓存失效

    JSON Schema 限制

    结构化输出支持标准 JSON Schema,但有一些限制。JSON 输出和严格工具使用共享这些限制。

    Python 和 TypeScript SDK 可以自动转换包含不支持特性的模式,方法是移除这些特性并将约束添加到字段描述中。详情请参阅 SDK 特定方法。

    无效输出

    虽然结构化输出在大多数情况下保证模式合规,但在某些场景下输出可能不匹配您的模式:

    拒绝(stop_reason: "refusal")

    即使使用结构化输出,Claude 仍然保持其安全性和有用性特性。如果 Claude 出于安全原因拒绝请求:

    • 响应将包含 stop_reason: "refusal"
    • 您将收到 200 状态码
    • 您将为生成的 token 付费
    • 输出可能不匹配您的模式,因为拒绝消息优先于模式约束

    达到 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 的工具数量

    对于有效模式的持续问题,请联系支持并提供您的模式定义。

    功能兼容性

    兼容:

    • 批量处理:以 50% 折扣大规模处理结构化输出
    • Token 计数:无需编译即可计算 token
    • 流式传输:像普通响应一样流式传输结构化输出
    • 组合使用:在同一请求中同时使用 JSON 输出(output_config.format)和严格工具使用(strict: true)

    不兼容:

    • 引用:引用需要在文本中交错插入引用块,这与严格的 JSON 模式约束冲突。如果在启用引用的同时使用 output_config.format,将返回 400 错误。
    • 消息预填充:与 JSON 输出不兼容

    语法作用范围:语法仅适用于 Claude 的直接输出,不适用于工具使用调用、工具结果或思考标签(使用扩展思考时)。语法状态在各部分之间重置,允许 Claude 自由思考,同时在最终响应中仍然产生结构化输出。

    Was this page helpful?

    • JSON 输出
    • 在 SDK 中使用 JSON 输出
    • 提示词修改和 token 成本
    • JSON Schema 限制