SDK 接入 · 截至 2026-11-25

Claude 结构化输出完整指南:用 output_config.format 与 strict 工具调用稳定拿到合法 JSON

想让 Claude 每次都返回能直接 json.loads 的数据,截至 2026-11-25 最可靠的做法是 Anthropic 的「结构化输出」(Structured outputs):在请求里设置 output_config.format(JSON 输出),或在工具定义上加 strict: true(严格工具调用)。 两者都通过把 JSON Schema 编译成语法、在采样时约束 token,来保证输出符合 schema。官方文档称该功能已正式可用(不再需要 beta 头),支持 Opus 5.5、Sonnet 5.5、Haiku 5.5、Fable 5.2 等全部当前模型。通过 QCode 的 Anthropic 接口 https://api.qcode.cc/api 调用时,请求写法与官方示例一致;如果依赖 output_config.format、工具上的 strict 或 eager_input_streaming 原样透传,请先用一个小请求测试。

QCode 是独立的第三方 API 服务,与 Anthropic 没有隶属或合作关系。下文参数与限制引自 platform.claude.com 的 Structured outputs、Strict tool use 与 Fine-grained tool streaming 文档(2026-11-25 读取)。

更新于 2026-11-26

要点速览

  • 两种模式: JSON 输出用 output_config={"format": {"type": "json_schema", "schema": {...}}},约束模型的最终回复;严格工具调用在工具上设置 "strict": true,约束工具名和工具参数。两者可以在同一请求里同时使用。
  • 旧参数已弃用: output_format 不带 structured-outputs-2025-11-13 beta 头会返回 400;Python SDK v1.0 起把字典传给 output_format 会抛 TypeError。
  • SDK 帮手: Python 用 client.messages.parse(..., output_format=PydanticModel),结果在 parsed_output;TypeScript 用 zodOutputFormat() 或 jsonSchemaOutputFormat() 配合 client.messages.parse()。
  • schema 限制: 每个请求最多 20 个 strict 工具、合计 24 个可选参数、16 个联合类型参数;不支持递归、oneOf、数值与字符串长度约束;object 必须 additionalProperties: false。
  • 仍可能不合规的情况: stop_reason: "refusal"、stop_reason: "max_tokens",以及 enum 值大小写不保证。
  • 5.5 系列的变化: Opus 5.5 / Sonnet 5.5 拒绝 tool_choice 的 any 与 tool,Opus 5.5 / Sonnet 5.5 也拒绝 assistant 预填充,所以“强制调用工具”和“预填 {”这两种老办法都不能再用。

几种拿 JSON 的方法对比

方法 是否保证合法 在 5.5 系列上 适用场景
提示词里写“只返回 JSON” 不保证 可用 原型、要求不严格的内部脚本
assistant 预填充 { 不保证 Opus 5.5 / Sonnet 5.5 被拒绝(400) 已不推荐
强制 tool_choice 调用某个工具 参数基本可靠 Opus 5.5 / Sonnet 5.5 返回 400 仅旧模型
严格工具调用 strict: true 工具名与参数符合 schema 支持,配合 tool_choice: auto Agent 动作、多个结构化动作
JSON 输出 output_config.format 最终回复符合 schema 支持 信息抽取、分类、生成结构化结果

一句话选择:要的是“答案本身”是 JSON,用 output_config.format;要的是“模型去执行一个动作”并带结构化参数,用 strict 工具。

方法一:JSON 输出 + Pydantic(Python)

官方推荐把 Pydantic 模型交给 client.messages.parse()。SDK 会转换 schema、作为 output_config.format 发送、校验返回内容,并把解析结果放进 parsed_output。解析在你的进程中完成;如果经 QCode 依赖 messages.parse(),请先用一个小请求测试。

import os
from typing import Literal
import anthropic
from pydantic import BaseModel

client = anthropic.Anthropic(
    base_url="https://api.qcode.cc/api",
    api_key=os.environ["QCODE_API_KEY"],   # cr_ 开头的 Key
)

class Ticket(BaseModel):
    title: str
    severity: Literal["low", "medium", "high"]
    components: list[str]
    needs_repro: bool

resp = client.messages.parse(
    model="claude-sonnet-5-5",
    max_tokens=2048,
    messages=[{"role": "user", "content": "Turn this bug report into a ticket:\n" + report_text}],
    output_format=Ticket,
)
ticket = resp.parsed_output
print(ticket.severity, ticket.components)

SDK 转换时会去掉语法不支持的约束(例如 minimum、maxLength),把它们写进字段描述,并补上 additionalProperties: false。模型看到的是简化后的 schema,但会校验的帮手函数仍在你的代码里执行全部约束,所以客户端校验失败依然可能发生,下面的重试逻辑就是为此准备的。

方法二:JSON 输出 + Zod(TypeScript)

import Anthropic from "@anthropic-ai/sdk";
import { z } from "zod";
import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";

const client = new Anthropic({
  baseURL: "https://api.qcode.cc/api",
  apiKey: process.env.QCODE_API_KEY,
});

const Ticket = z.object({
  title: z.string(),
  severity: z.enum(["low", "medium", "high"]),
  components: z.array(z.string()),
  needs_repro: z.boolean(),
});

const res = await client.messages.parse({
  model: "claude-haiku-5-5",
  max_tokens: 1024,
  messages: [{ role: "user", content: `Turn this bug report into a ticket:\n${report}` }],
  output_config: { format: zodOutputFormat(Ticket) },
});
console.log(res.parsed_output);

不想引入 Zod,可以用 @anthropic-ai/sdk/helpers/json-schema 里的 jsonSchemaOutputFormat() 传普通 JSON Schema(用 as const 声明可获得类型推断)。注意官方说明它不会校验响应,需要自己校验。

直接用 HTTP 请求

不走 SDK 的同一个请求。QCode 上的路径是 /api/v1/messages:

curl https://api.qcode.cc/api/v1/messages \
  -H "x-api-key: $QCODE_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-haiku-5-5",
    "max_tokens": 1024,
    "messages": [{"role": "user", "content": "Extract name and email: Jane Doe, jane@example.com"}],
    "output_config": {
      "format": {
        "type": "json_schema",
        "schema": {
          "type": "object",
          "properties": {"name": {"type": "string"}, "email": {"type": "string", "format": "email"}},
          "required": ["name", "email"],
          "additionalProperties": false
        }
      }
    }
  }'

JSON 以字符串形式出现在 content 的 text 块中。新版 SDK 会发送更晚的 anthropic-version(官方 curl 示例用 2026-10-21);如果经 QCode 依赖特定版本的头,请先用一个小请求测试。

方法三:严格工具调用(让模型带着结构化参数去“做事”)

tools = [{
    "name": "create_ticket",
    "description": "Create a ticket in the bug tracker. Call once per distinct bug.",
    "strict": True,
    "input_schema": {
        "type": "object",
        "properties": {
            "title": {"type": "string"},
            "severity": {"type": "string", "enum": ["low", "medium", "high"]},
            "component": {"type": "string"},
        },
        "required": ["title", "severity", "component"],
        "additionalProperties": False,
    },
}]

resp = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=4096,
    tools=tools,
    tool_choice={"type": "auto"},   # 5.5 系列只接受 auto / none
    messages=[{"role": "user", "content": "Read these logs and call create_ticket for each bug:\n" + logs}],
)

for block in resp.content:
    if block.type == "tool_use" and block.name == "create_ticket":
        create_ticket(**block.input)   # input 已是符合 input_schema 的 dict

在 Opus 5.5 和 Sonnet 5.5 上,tool_choice: {"type": "any"} 或 {"type": "tool", ...} 会返回 tool_choice: type "tool" and "any" are not supported for this model.。替代做法是 auto + strict,并在提示词里写清楚什么时候调用。迁移细节见 Opus 5.5 / Sonnet 5.5 迁移清单。另外,computer use、browser use 的工具集条目(computer_toolset_20260801、browser_toolset_20260801)不接受 strict,MCP 工具集条目也不接受。

校验与重试:把“几乎总是对的”变成“总是可用的”

结构化输出保证的是“符合 schema”,不保证“符合你的业务规则”,而且官方列出了三种例外。建议用下面这种写法,把它们都处理掉:

import json
from typing import Literal
from pydantic import BaseModel, ValidationError, field_validator

INVOICE_SCHEMA = {
    "type": "object",
    "properties": {
        "vendor": {"type": "string"},
        "invoice_number": {"type": "string"},
        "currency": {"type": "string", "enum": ["USD", "EUR", "CNY"]},
        "total": {"type": "number", "description": "Total including tax"},
        "due_date": {"type": ["string", "null"], "description": "YYYY-MM-DD or null"},
    },
    "required": ["vendor", "invoice_number", "currency", "total", "due_date"],
    "additionalProperties": False,
}

class Invoice(BaseModel):
    vendor: str
    invoice_number: str
    currency: Literal["USD", "EUR", "CNY"]
    total: float
    due_date: str | None

    @field_validator("currency", mode="before")
    @classmethod
    def normalize_case(cls, v):
        return v.upper() if isinstance(v, str) else v   # enum 大小写不保证

def extract_invoice(text: str, retries: int = 2) -> Invoice:
    max_tokens = 2048
    for _ in range(retries + 1):
        resp = client.messages.create(
            model="claude-sonnet-5-5",
            max_tokens=max_tokens,
            output_config={
                "effort": "low",
                "format": {"type": "json_schema", "schema": INVOICE_SCHEMA},
            },
            messages=[{"role": "user", "content": "Extract the invoice fields:\n\n" + text}],
        )
        if resp.stop_reason == "refusal":
            raise RuntimeError("Model refused; inspect the input instead of retrying as-is")
        if resp.stop_reason == "max_tokens":
            max_tokens *= 2        # 输出被截断,加大后重试
            continue
        raw = next(b.text for b in resp.content if b.type == "text")
        try:
            inv = Invoice.model_validate_json(raw)
        except ValidationError:
            continue
        if inv.total < 0:          # 语法管不到的业务规则
            continue
        return inv
    raise RuntimeError("No valid invoice after retries")

要点:

  • refusal: HTTP 200 但 stop_reason: "refusal",按生成的 token 计费,输出可能不符合 schema。不要原样重试。另外,schema 里如果有要求模型写出“逐步推理过程”的字段,可能触发 reasoning_extraction 类拒绝,改成“简短说明”即可。
  • max_tokens: 输出被截断、JSON 不完整。注意 5.5 系列默认开启思考,max_tokens 同时覆盖思考和正文,不要设得太小。
  • enum 大小写: 官方说明可能返回只差大小写的值(常见于空格后的首字母),且不报错。比较时忽略大小写,也不要定义只差大小写的 enum 值。
  • 按 type 取块: 响应可能先有 thinking 块,所以用 b.type == "text" 取正文,不要用 content[0]。语法只作用于最终输出,不影响思考部分。
  • 属性顺序: 输出中必填属性在前、可选属性在后。如果顺序重要,就把所有属性都设为必填(上例即如此,可空字段用 ["string", "null"])。

流式输出与部分 JSON

JSON 输出可以像普通回复一样流式返回,但在流结束前得到的是不完整的 JSON。做法是边收边拼接,结束后再解析:

chunks = []
with client.messages.stream(
    model="claude-sonnet-5-5",
    max_tokens=4096,
    output_config={"format": {"type": "json_schema", "schema": INVOICE_SCHEMA}},
    messages=[{"role": "user", "content": "Extract the invoice fields:\n\n" + text}],
) as stream:
    for piece in stream.text_stream:
        chunks.append(piece)      # 可在此用容错的部分 JSON 解析器刷新界面
data = json.loads("".join(chunks))

工具参数的流式是另一套机制:在工具定义上设置 "eager_input_streaming": true,参数会以 input_json_delta 事件的 partial_json 片段到达,在 content_block_stop 时拼接解析。官方特别提醒:这种细粒度流式不在服务端缓冲和校验,拼出来的字符串可能不是合法 JSON;遇到这种情况,返回一个 is_error: true 的 tool_result,把原始字符串包在 {"INVALID_JSON": "..."} 里交给模型处理。

Schema 写法与复杂度限制

限制 数值 说明
每请求 strict 工具数 20 非 strict 工具不计入
可选参数总数 24 所有 strict 工具与 JSON 输出 schema 合计
联合类型参数总数 16 使用 anyOf 或类型数组(如 ["string", "null"])的参数
语法编译超时 180 秒 超出会失败

超出内部限制时返回 400:Schema is too complex for compilation.。降低复杂度的顺序:只给关键工具开 strict;尽量把参数设为必填;拍平嵌套;把很多 strict 工具拆到不同请求或子代理。

支持: 基本类型、enum / const、anyOf / allOf(有例外)、$ref / $defs、常见字符串 format(date-time、date、email、uri、uuid 等)、数组 minItems 为 0 或 1。不支持: 递归 schema、oneOf(改用 anyOf)、not、外部 $ref、minimum / maximum / multipleOf、minLength / maxLength、复杂正则(反向引用、环视)。

键名不固定的对象怎么办? 因为 additionalProperties 必须是 false,模型只能返回你列出的键。键名事先未知时,改用由 {"key": ..., "value": ...} 组成的数组。

与其他功能的兼容: 官方文档称可以和批处理、token 计数、流式一起用;不能和 Citations 一起用(同时开启会返回 400),也不能和消息预填充一起用。

延迟与成本技巧

  • 首次请求较慢: 某个 schema 第一次使用时要编译语法,编译结果缓存 24 小时(从最后一次使用算起)。改 schema 结构或(同时用工具时)改工具集合会使缓存失效;只改 name 或 description 不会。
  • schema 要稳定: 修改 output_config.format 会让该对话的提示缓存失效。把 schema 当作常量,不要每次请求动态拼字段顺序。
  • 注入的提示也要计费: 结构化输出会注入一段系统提示,输入 token 会略增。
  • 选对模型: 字段抽取、分类这类任务,Haiku 5.5 往往够用,官方价 $0.10 / $0.50 每百万 token(提示 ≤100K;超过 100K 整次请求按 $0.50 / $2.50);需要推理的复杂结构用 Sonnet 5.5($2 / $10),并把 effort 调到 low 减少思考 token。
  • 批量离线任务: 官方 Batch API 对结构化输出同样打 5 折;QCode 是否提供没有文档说明,依赖前请先用一个小请求测试。
  • QCode 按官方价 × 1.0 计费,以 /models 实时价格为准。

GPT 模型怎么办?

QCode 的同一个 Key 也能调用 GPT 模型,但 GPT 只走 OpenAI 协议接口(https://api.qcode.cc/openai/v1),结构化输出要用 OpenAI 自己的参数,而不是 output_config;具体参数请先用一个小请求确认。Responses API 下的工具调用与缓存实践可参考 GPT-6.2 Sol Responses API 工具调用与缓存。

常见问题

Claude 结构化输出需要 beta 头吗?

不需要。官方文档把该功能标为正式可用,参数为 output_config.format。只有继续使用已弃用的 output_format 时才需要 structured-outputs-2025-11-13 头,否则返回 400。

哪些模型支持结构化输出?

官方列出全部当前模型,包括 claude-opus-5-5、claude-sonnet-5-5、claude-haiku-5-5、claude-fable-5-2,以及 Opus 4.6 至 4.8、Sonnet 4.5 / 4.6、Haiku 4.5 等。通过 QCode 调用时使用相同的模型 ID。

JSON 输出和 strict 工具调用该选哪个?

需要模型直接给出结构化答案时,用 JSON 输出;需要模型决定调用哪个动作、并给出结构化参数时,用 strict 工具。两者可以在同一请求里组合使用。

为什么结构化输出还是返回了不符合 schema 的内容?

官方列出的例外是拒绝(stop_reason: "refusal")和被 max_tokens 截断,另外 enum 值的大小写不保证。请检查 stop_reason,并在客户端做校验与重试。

报错 Schema is too complex for compilation 怎么办?

说明所有 strict schema 加起来超出了编译限制。减少 strict 工具数量、把可选参数改为必填、减少 anyOf 和可空类型、拍平嵌套结构,或把工具拆到多个请求里。

结构化输出可以流式返回吗?

可以,像普通文本一样流式返回,但完整 JSON 要在流结束后才能解析。工具参数可用 eager_input_streaming 细粒度流式,但拼接结果可能不是合法 JSON,需要容错处理。

通过 QCode 使用结构化输出要改代码吗?

只需把 SDK 的 Base URL 设为 https://api.qcode.cc/api 并换成 QCode 的 Key;请求体与 create 相同,解析在客户端完成。如果经 QCode 依赖 messages.parse(),请先用一个小请求测试。Claude 模型只能走 Anthropic 接口,不能通过 /openai/v1 调用。

能不能把 PHI 等敏感信息写进 schema?

官方说明 schema 会被单独缓存最多 24 小时,且不享有与提示、响应相同的保护,不能把 PHI 放进属性名、enum、const 或正则里。敏感数据只应出现在消息内容中。

推荐方案

结构化输出多用于数据管道、抽取脚本、小工具这类用量起伏大的场景,不一定需要包月。QCode 按量包从 ¥26 起,无需订阅,7 天有效,按官方价 × 1.0 扣费,详见 /pay-as-you-go。如果之后变成每天稳定的大量调用,再看 /pricing 的日额度套餐。

推荐方案

一个 Key 同时支持 Anthropic Messages 与 OpenAI 兼容接口;Claude 与 GPT 按官方价 ×1.0 计费,实时单价见 /models。

不确定从哪开始?

先试一周

小包 ¥26($30 额度,7 天)

每天都用

体验版 ¥63/月,每天 $5 额度;每 $1 额度只要 ¥0.42,中包约 ¥0.79