Skip to content

Latest commit

 

History

History
122 lines (94 loc) · 5.07 KB

File metadata and controls

122 lines (94 loc) · 5.07 KB

3.7 结构化输出:保证响应格式的可靠性

在生产环境中,一次格式错误就可能引发级联故障——JSON 解析失败、工具调用参数不匹配、多 Agent 通信中断。Claude 的结构化输出分为两条官方路径:用 output_config.format 控制最终 JSON 响应,用 strict: true 控制工具调用参数;不要把其他厂商的 response_format 参数照搬到 Anthropic Messages API。

💡 纯 JSON 抽取、分类和报告优先使用 output_config.format;只有需要函数/工具调用语义时,才把结构定义为 client tool 的 input_schema,并配合 strict: truetool_choice

3.7.1 为什么需要结构化输出

传统方式下,开发者通过提示词要求 Claude “以 JSON 格式返回”,但模型可能返回多余的 Markdown 包装、遗漏必填字段、或数据类型不匹配。生产系统应使用原生结构化输出:纯响应格式走 output_config.format,工具参数走 strict tool use。

3.7.2 使用方式

JSON Outputs

纯数据抽取或结构化报告时,直接要求响应匹配 JSON Schema:

import json

response = client.messages.create(
    model="claude-opus-4-8",
    max_tokens=1024,
    messages=[{"role": "user", "content": "提取以下邮件的姓名、邮箱和需求..."}],
    output_config={
        "format": {
            "type": "json_schema",
            "schema": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "email": {"type": "string"},
                    "request": {"type": "string"},
                },
                "required": ["name", "email", "request"],
                "additionalProperties": False,
            },
        }
    },
)

data = json.loads(response.content[0].text)

Strict Tool Use

把数据提取任务建模成一个无副作用的 client tool,并强制 Claude 调用它:

response = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=1024,
    tools=[
        {
            "name": "record_extraction",
            "description": "Extract the title, date, and named entities from the provided text. Return only fields supported by the schema.",
            "input_schema": {
                "type": "object",
                "properties": {
                    "title": {"type": "string"},
                    "date": {"type": "string", "description": "ISO 8601 date if present"},
                    "entities": {"type": "array", "items": {"type": "string"}},
                },
                "required": ["title", "entities"],
                # strict 模式下 object 必须显式关闭额外字段,否则返回 400
                "additionalProperties": False,
            },
            "strict": True,
        }
    ],
    tool_choice={"type": "tool", "name": "record_extraction"},
    messages=[{"role": "user", "content": "提取以下文本的关键信息..."}],
)

tool_call = next(block for block in response.content if block.type == "tool_use")
data = tool_call.input

Tool Mode

对会产生外部副作用的业务动作,也可以在工具定义中使用 strict: true,保证工具调用参数严格匹配 Schema:

tools = [{
    "name": "create_ticket",
    "description": "创建工单",
    "input_schema": {
        "type": "object",
        "properties": {
            "title": {"type": "string"},
            "priority": {"type": "string", "enum": ["P0", "P1", "P2", "P3"]},
            "assignee": {"type": "string"}
        },
        "required": ["title", "priority"]
    },
    "strict": True
}]

3.7.3 支持的 Schema 特性

结构化输出支持丰富的 JSON Schema 子集,包括基础类型(string、number、integer、boolean、null)、复合类型(嵌套 object、array)、枚举约束(enum)、联合类型(anyOf)和必填字段(required)。

3.7.4 关键应用场景

数据提取:从非结构化文本(合同、发票、简历)中提取结构化数据,下游系统可以显著减少格式容错,但仍要处理拒答、截断、空值和业务校验失败。

多 Agent 通信:Agent 之间通过结构化消息通信时,格式保证可以降低序列化/反序列化失败的风险,显著提升系统稳定性。

复杂搜索工具:搜索 Agent 返回的结果严格符合预定义结构,前端仍需保留安全渲染、长度限制和空结果处理。

3.7.5 注意事项

  • 纯 JSON 输出优先使用 output_config.format,再解析 response.content[0].text
  • 工具调用场景使用 strict: true,再从 tool_use.input 读取结构化参数
  • tool_choice={"type": "any"} 或指定工具可保证返回工具调用;和 extended thinking 组合时要先查当前兼容性限制
  • 对于特别复杂的 Schema(深层嵌套超过 5 层),建议拆分为多次调用

随着工具的增多,不仅面临管理的挑战,还面临连接的挑战。如何标准化地连接本地文件、远程服务和各类数据库?

➡️ 第四章:MCP 模型上下文协议