Loading...
    • 开发者指南
    • API 参考
    • MCP
    • 资源
    • 发布说明
    Search...
    ⌘K
    快速开始
    Claude 简介快速入门
    模型与定价
    模型概览选择模型Claude 4.5 新功能迁移到 Claude 4.5模型弃用定价
    使用 Claude 构建
    功能概览使用 Messages API上下文窗口提示词最佳实践
    能力
    提示词缓存上下文编辑扩展思考工作量流式消息批量处理引用多语言支持Token 计数嵌入视觉PDF 支持Files API搜索结果结构化输出
    工具
    概览如何实现工具使用细粒度工具流式传输Bash 工具代码执行工具程序化工具调用计算机使用工具文本编辑器工具Web 获取工具Web 搜索工具内存工具工具搜索工具
    Agent Skills
    概览快速入门最佳实践在 API 中使用 Skills
    Agent SDK
    概览快速入门TypeScript SDKTypeScript V2(预览版)Python SDK迁移指南
    API 中的 MCP
    MCP 连接器远程 MCP 服务器
    第三方平台上的 Claude
    Amazon BedrockMicrosoft FoundryVertex AI
    提示词工程
    概览提示词生成器使用提示词模板提示词改进器清晰直接使用示例(多轮提示)让 Claude 思考(CoT)使用 XML 标签给 Claude 一个角色(系统提示词)预填充 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_format):获取 Claude 特定 JSON 格式的响应
    • 严格工具使用 (strict: true):保证工具名称和输入的模式验证

    这些功能可以独立使用,也可以在同一请求中一起使用。

    结构化输出目前在 Claude API 中作为公开测试版功能提供,支持 Claude Sonnet 4.5、Claude Opus 4.1、Claude Opus 4.5 和 Claude Haiku 4.5。

    要使用此功能,请设置 beta 标头 structured-outputs-2025-11-13。

    使用此 表单 分享反馈。

    为什么使用结构化输出

    没有结构化输出,Claude 可能会生成格式错误的 JSON 响应或无效的工具输入,从而破坏您的应用程序。即使进行仔细的提示,您也可能遇到:

    • 来自无效 JSON 语法的解析错误
    • 缺少必需字段
    • 数据类型不一致
    • 需要错误处理和重试的模式违规

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

    • 始终有效:不再有 错误
    • JSON 输出
    • 在 SDK 中使用 JSON 输出
    • JSON Schema 限制
    JSON.parse()
  1. 类型安全:保证字段类型和必需字段
  2. 可靠:不需要为模式违规重试
  3. 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" \
      -H "anthropic-beta: structured-outputs-2025-11-13" \
      -d '{
        "model": "claude-sonnet-4-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": {
          "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
          }
        }
      }'

    响应格式: 与您的模式匹配的有效 JSON,位于 response.content[0].text 中

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

    工作原理

    1. 1

      定义您的 JSON 模式

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

    2. 2

      添加 output_format 参数

      在您的 API 请求中包含 output_format 参数,其中 type: "json_schema" 和您的模式定义。

    3. 3

      包含 beta 标头

      将 anthropic-beta: structured-outputs-2025-11-13 标头添加到您的请求中。

    4. 4

      解析响应

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

    在 SDK 中使用 JSON 输出

    Python 和 TypeScript SDK 提供了帮助程序,使得使用 JSON 输出变得更容易,包括模式转换、自动验证和与流行模式库的集成。

    使用 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()
    
    # With .create() - requires transform_schema()
    response = client.beta.messages.create(
        model="claude-sonnet-4-5",
        max_tokens=1024,
        betas=["structured-outputs-2025-11-13"],
        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={
            "type": "json_schema",
            "schema": transform_schema(ContactInfo),
        }
    )
    
    print(response.content[0].text)
    
    # With .parse() - can pass Pydantic model directly
    response = client.beta.messages.parse(
        model="claude-sonnet-4-5",
        max_tokens=1024,
        betas=["structured-outputs-2025-11-13"],
        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.beta.messages.parse() (推荐)

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

    parse() 方法在 client.beta.messages 上可用,而不是在 client.messages 上。

    Python: transform_schema() 帮助程序

    用于在发送前手动转换模式,或当您想修改 Pydantic 生成的模式时。与 client.beta.messages.parse() 不同,后者自动转换提供的模式,这给您转换后的模式,以便您可以进一步自定义它。

    SDK 转换如何工作

    Python 和 TypeScript SDK 都自动转换具有不支持功能的模式:

    1. 删除不支持的约束(例如 minimum、maximum、minLength、maxLength)
    2. 更新描述,包含约束信息(例如"必须至少 100"),当约束不直接支持结构化输出时
    3. 为所有对象添加 additionalProperties: false
    4. 过滤字符串格式为仅支持的列表
    5. 验证响应是否符合您的原始模式(包含所有约束)

    这意味着 Claude 接收简化的模式,但您的代码仍然通过验证强制执行所有约束。

    示例: 具有 minimum: 100 的 Pydantic 字段在发送的模式中变成普通整数,但描述更新为"必须至少 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" \
      -H "anthropic-beta: structured-outputs-2025-11-13" \
      -d '{
        "model": "claude-sonnet-4-5",
        "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

      包含 beta 标头

      将 anthropic-beta: structured-outputs-2025-11-13 标头添加到您的请求中。

    4. 4

      处理工具调用

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

    常见用例

    同时使用两个功能

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

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

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

    response = client.beta.messages.create(
        model="claude-sonnet-4-5",
        betas=["structured-outputs-2025-11-13"],
        max_tokens=1024,
        messages=[{"role": "user", "content": "Help me plan a trip to Paris for next month"}],
        # JSON outputs: structured response format
        output_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
            }
        }]
    )

    重要考虑事项

    语法编译和缓存

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

    • 首次请求延迟:第一次使用特定模式时,在编译语法时会有额外的延迟
    • 自动缓存:编译的语法从上次使用起缓存 24 小时,使后续请求快得多
    • 缓存失效:如果您更改以下内容,缓存将失效:
      • JSON 模式结构
      • 请求中的工具集(使用结构化输出和工具使用时)
      • 仅更改 name 或 description 字段不会使缓存失效

    提示修改和令牌成本

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

    • 您的输入令牌计数将略高
    • 注入的提示像任何其他系统提示一样花费您的令牌
    • 更改 output_format 参数将使该对话线程的任何 提示缓存 失效

    JSON Schema 限制

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

    Python 和 TypeScript SDK 可以通过删除不支持的功能并将约束添加到字段描述来自动转换模式。有关详细信息,请参阅 SDK 特定方法。

    无效输出

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

    拒绝 (stop_reason: "refusal")

    Claude 即使在使用结构化输出时也保持其安全性和有用性属性。如果 Claude 出于安全原因拒绝请求:

    • 响应将具有 stop_reason: "refusal"
    • 您将收到 200 状态代码
    • 您将被计费生成的令牌
    • 输出可能不匹配您的模式,因为拒绝消息优先于模式约束

    达到令牌限制 (stop_reason: "max_tokens")

    如果响应因达到 max_tokens 限制而被截断:

    • 响应将具有 stop_reason: "max_tokens"
    • 输出可能不完整且不匹配您的模式
    • 使用更高的 max_tokens 值重试以获取完整的结构化输出

    模式验证错误

    如果您的模式使用不支持的功能或过于复杂,您将收到 400 错误:

    "模式中的递归定义过多"

    • 原因:模式具有过多或循环递归定义
    • 解决方案:简化模式结构,减少嵌套深度

    "模式过于复杂"

    • 原因:模式超过复杂性限制
    • 解决方案:分解为较小的模式,简化结构,或减少标记为 strict: true 的工具数量

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

    功能兼容性

    适用于:

    • 批处理:以 50% 折扣大规模处理结构化输出
    • 令牌计数:计数令牌而不编译
    • 流式传输:像普通响应一样流式传输结构化输出
    • 组合使用:在同一请求中一起使用 JSON 输出(output_format)和严格工具使用(strict: true)

    不兼容:

    • 引用:引用需要将引用块与文本交错,这与严格 JSON 模式约束冲突。如果启用了引用的 output_format,返回 400 错误。
    • 消息预填充:与 JSON 输出不兼容

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