首页/AI/大模型部署与运维速查/受约束解码:JSON/Schema/正则
本包目录(267 条)
部署形态与选型43 条推理环境与 GPU50 条
推理参数与优化50 条
显存与并发估算40 条服务化与网关34 条运维监控与排障50 条

受约束解码:JSON/Schema/正则

受约束解码让输出在生成时就符合目标语法:OpenAI 兼容的 response_format(JSON 模式)与 vLLM 的 guided decoding(底层 xgrammar/outlines 等后端)是常见入口,可降低解析失败率。

OpenAI 兼容 JSON 模式

OpenAI 兼容 JSON 模式
r = client.chat.completions.create(
    model="<模型名>",
    messages=[{"role": "user", "content": "输出包含 name 与 age 的 JSON"}],
    response_format={"type": "json_object"},
)

vLLM 引导解码(示意)

vLLM 引导解码(示意)
from vllm import SamplingParams
from vllm.sampling_params import GuidedDecodingParams
sp = SamplingParams(
    guided_decoding=GuidedDecodingParams(
        json={"type": "object", "properties": {"name": {"type": "string"}}, "required": ["name"]}
    )
)
约束校验有每步开销:首字延迟会上升,schema 越复杂越明显;接口形态随版本演进,以所用版本文档为准。

易错点

  • 把 JSON 模式当内容正确性保证:它只约束语法结构,字段值仍可能编造,业务校验不能省

数据来源与参考

  • vLLM 官方文档:Structured Outputs(docs.vllm.ai)
  • OpenAI API 参考:response_format(platform.openai.com/docs)
​‌‌​​‌​​​‌‌​‌‌‌‌​‌‌​​​‌‌​‌‌‌​​‌‌​​‌​‌‌‌​​‌‌‌​​​‌​‌‌​‌​​‌​‌‌‌​​​‌​‌‌​‌​​‌​‌‌​​​‌‌​‌‌‌​‌​​​‌‌​‌‌‌‌​​‌​‌‌‌​​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌​‌