Skip to content
FunCoding

Search

Search docs, Skills and MCP

JSON Schema 结构化结果

在无头任务中验证最终对象,选择 schema 来源和输出封装。

This page has not been translated into English yet. The original Chinese version is shown below.

--json-schema 给主运行注册 synthetic structured_output 终止工具。模型必须提交满足 schema 的参数;第一次有效调用结束运行。它不是只要求模型“尽量返回 JSON”。

示例

qwen -p "Summarize this project and rate its complexity." \
  --json-schema '{"type":"object","properties":{"summary":{"type":"string"},"complexity":{"type":"string","enum":["low","medium","high"]}},"required":["summary","complexity"],"additionalProperties":false}'

默认 text 模式 stdout 只有 JSON.stringify(payload) 加换行,不包事件 envelope。失败 stdout 为空,错误和日志走 stderr;模型规划时的附带文字被丢弃,也不会镜像到 stderr。

从文件读取

qwen -p "Summarize this project." --json-schema @./schemas/summary.json

文件需预先存在,@path 支持 ~、路径规范化和 UTF-8。必须是普通文件,拒绝 FIFO、设备与目录,最多 4 MiB;内容需有效 JSON,并能在严格 Ajv 配置下编译。拼错关键字会报错,合法的 required 未逐一列入 properties 等模式仍接受。

schema 根必须接受对象,因为工具参数只能是 JSON 对象;类型、enum/const、组合与条件会做尽力的根检查,无法静态决定的交给运行时 Ajv。根 $ref 被拒绝,可用 allOf 包裹本地引用,例如:

{
  "allOf": [{ "$ref": "#/$defs/Result" }],
  "$defs": {
    "Result": {
      "type": "object",
      "properties": { "summary": { "type": "string" } },
      "required": ["summary"]
    }
  }
}

空 schema {} 可以得到空对象 {},不能用它保证出现业务字段。含 pattern 的 schema 使用 ECMAScript 正则,复杂回溯可能阻塞验证,应仅采用可信且适度复杂的 schema。

输出封装

格式获取结果
textstdout 单行原始对象
json事件数组最后 result 的 structured_result 为原始对象,result 为字符串形式
stream-json终止 result 行中的 structured_result;result 同样保留字符串形式

json 模式可用 jq '.[-1].structured_result',不要对已经是对象的字段再做 JSON 字符串解析。

可用组合

仅支持无头:-p、位置 prompt 或 stdin prompt。与 -i、stream-json 输入、ACP/旧 experimental-acp 组合会在解析阶段拒绝;没有 prompt 也拒绝。输出为 stream-json 不影响使用,输入协议才是冲突项。

--bare 支持,会在其 read_file、edit、run_shell_command 之外注册终止工具。subagent 不注册它,只有顶层主轮和 drain 轮遵守终止契约。

成功后最多约 500ms 等待后台通知排空,没有后台任务时可提早结束。错误、权限、Hooks 和恢复说明见结构化结果的运行边界。