Appearance
一句话总结:结构化输出约束从弱到强四级——提示词 → JSON mode → Structured Outputs(json_schema+strict)→ Constrained Decoding(token 级 FSM 遮盖);铁律是两层约束:模型侧尽量按模式生成 + 应用侧无条件校验拒绝,才能让"大模型回答"变成"业务可消费的数据"。
约束四级(面试默写)
| 层级 | 机制 | 保证程度 |
|---|---|---|
| 提示词描述 | "请输出 JSON" | 最弱,经常炸 |
| JSON mode | 保证合法 JSON | 不保证 schema |
| Structured Outputs | response_format={type:json_schema, schema, strict:true} + temperature=0 | 严格符合 schema |
| Constrained Decoding | token 生成阶段 FSM 遮盖非法 token | 物理上只能输出合法内容 |
- Constrained Decoding 实例:Ollama
format参数(schema→grammar)、llama.cpp--json、Outlines - strict:true 必须开——无 strict 会加多余键/漏必填字段,破坏反序列化
两层约束原则(拉分点)
模型侧:尽量按 schema 生成(Structured Outputs / Tool Calling 参数约束)
应用侧:无条件校验、拒绝、记录异常(JSON Schema 描述形状 + Pydantic 转类型/校验器)- Tool Calling 约束:通过工具参数定义约束输出结构(模型返回匹配 schema 的参数而非自由文本)
- 比 JSON mode 更稳:schema 随请求传输、provider 约束更激进
踩坑清单
- 无 strict → 多余键/漏字段
- 只靠提示词 → 复杂推理下格式被忽略
- 应用侧不校验 → 坏数据进业务链路
面试要点
- 能默写约束四级(提示词→JSON mode→Structured→Decoding)
- 能讲 strict:true 作用
- 能说两层约束原则
- 能讲 Tool Calling vs JSON mode 差异
相关概念
- AI基础概念-LLM-API与Function-Calling — 工具约束
- [AI-Agent-Prompt-Agent系统提示与工具描述](/学习笔记/AI技术/AI Agent/AI-Agent-Prompt-Agent系统提示与工具描述) — 提示层
- [AI-Agent-工具调用](/学习笔记/AI技术/AI Agent/AI-Agent-工具调用) — 调用链
- [AI-Agent-评测指标与评估流程](/学习笔记/AI技术/AI Agent/AI-Agent-评测指标与评估流程) — 质量验证