怎么让 AI 按格式输出How to Get AI to Output in Your Format
微型指南 · 约 6 分钟Guide · about 6 min · 引用核验 2026-11-03(仅引用链接与日期) · refs checked 2026-11-03 (reference links and dates only)
程序要接 AI 的输出时,「请输出 JSON」经常不够。这篇讲从提示约束到结构化输出的三级做法。When a program has to consume AI output, "please output JSON" often isn't enough. Three levels, from prompt-level constraints to structured outputs.
第一级:提示里给格式说明加一个完整样例,多数场景够用,但字段缺失、多余解释仍会发生。
第二级:用接口的结构化输出/工具调用能力,由服务端约束解码保证格式合法,比口头要求可靠得多。
定义 schema 只写需要的字段并收紧类型:字段越少,出错面越小。
无论哪一级,接收端都要校验:模式校验失败就重试或降级,别直接喂给下游。
格式约束和任务质量会互相拉扯:强制格式可能让内容变差,两者要分开评测。
别用格式技巧代替内容评测:输出合法不等于输出正确。
Level one: a format spec plus one complete sample in the prompt. Enough for most cases, but missing fields and stray commentary still happen.
Level two: use the API's structured-output / tool-calling capability — server-side constrained decoding guarantees valid format, far more reliable than asking nicely.
Define schemas with only the fields you need and tighten types: fewer fields, smaller failure surface.
Validate on the receiving end regardless of level: on schema-validation failure, retry or degrade — never feed downstream code unchecked.
Format constraints and task quality pull against each other: forcing a format can degrade content, so evaluate the two separately.
Don't let format tricks substitute for content evaluation: valid output is not correct output.
例子与判断Example and interpretation
以下是教学情境,不是本站运行或实测记录。A teaching scenario, not a measured or executed site test.
要求输出 amount=12、currency=CNY 时,接收端仍要校验字段、数值类型和允许的币种。字符串“十二”、缺字段或额外文字应进入明确的重试或失败分支,不能直接写入业务记录。For output such as an amount of 12 and currency CNY, validate required fields, numeric types and allowed currencies at the receiving end. Missing fields, words instead of numbers or extra prose need an explicit retry/failure path.
结构化输出Structured Output 工具定义Tool Definition 提示词Prompt 护栏Guardrails
怎么向 AI 提问How to Ask AI · 怎么把提示词写结构How to Structure a Prompt · few-shot 示例怎么选How to Pick Few-Shot Examples · 怎么安全地用 MCP 工具How to Use MCP Tools Safely