文章目录
-
- [1. 原理:约束解码(constrained decoding)](#1. 原理:约束解码(constrained decoding))
- [2. OpenAI 兼容接口用法](#2. OpenAI 兼容接口用法)
-
- [2.1 response_format(JSON Schema,最常用)](#2.1 response_format(JSON Schema,最常用))
- [2.2 vLLM 扩展参数(extra_body 通道)](#2.2 vLLM 扩展参数(extra_body 通道))
- [2.3 结构化输出 + 流式:`structured_outputs_config` 的 transition window](#2.3 结构化输出 + 流式:
structured_outputs_config的 transition window)
- [3. 工具调用(function calling)](#3. 工具调用(function calling))
- [4. 结构化输出的潜在问题](#4. 结构化输出的潜在问题)
- [5. 实验](#5. 实验)
- [6. 在 explorer 中验证](#6. 在 explorer 中验证)
-
学习仓库:kill-life/vllm-learn
结构化输出与工具调用
- 让模型"只许输出合法 JSON / 正则匹配的文本"。vLLM 的实现是 guided decoding(约束解码):每步把不合法 token 的 logit 置 -inf,因此 100% 合法且几乎零额外推理延迟。本章给出可直接跑的 API 与离线引擎用法。
1. 原理:约束解码(constrained decoding)
- 生成第 i 个 token 时,语法后端根据"当前已生成内容 + 目标语法"算出本步合法 token 集合,生成 bitmask 掩码后采样。语法状态机随生成推进(编译成跳转表,开销极小)。
文件 :v1/structured_output/------utils.py 的 apply_grammar_bitmask(掩码应用)、backend_xgrammar.py / backend_outlines.py / backend_guidance.py / backend_lm_format_enforcer.py(四套后端,扁平布局)。
| 后端 | 指定方式 | 备注 |
|---|---|---|
| xgrammar(默认) | --structured-outputs-config '{"backend": "xgrammar"}' |
性能最好 |
| outlines | backend 换 outlines | 学术出身,生态广 |
| guidance(xguidance) | backend 换 guidance | 微软系语法 |
| lm-format-enforcer | backend 换 lm_format_enforcer | 老牌实现 |
离线引擎在 SamplingParams(structured_outputs=StructuredOutputsParams(...)) 里传约束(from vllm.sampling_params import StructuredOutputsParams);HTTP 走 response_format 或 extra_body。
2. OpenAI 兼容接口用法
2.1 response_format(JSON Schema,最常用)
python
from openai import OpenAI
from pydantic import BaseModel
client = OpenAI(base_url="http://127.0.0.1:8000/v1", api_key="None")
class CapitalInfo(BaseModel):
name: str
population: float
resp = client.chat.completions.create(
model=client.models.list().data[0].id,
messages=[{"role": "user", "content": "Give me the capital and population of France."}],
response_format={
"type": "json_schema",
"json_schema": {"name": "foo", "schema": CapitalInfo.model_json_schema()},
},
temperature=0,
)
print(resp.choices[0].message.content) # 一定是合法 JSON,可 json.loads
2.2 vLLM 扩展参数(extra_body 通道)
- OpenAI SDK 会把
extra_body里的键平铺进请求体,vLLM 识别这些扩展参数:
python
resp = client.chat.completions.create(
model="default", messages=[{"role": "user", "content": "Paris is the capital of"}],
extra_body={"guided_regex": r"(Paris|London|Berlin)"},
)
python
extra_body={"guided_choice": ["yes", "no"]} # 枚举
extra_body={"guided_grammar": 'root ::= "yes" | "no"'} # EBNF
extra_body={"guided_json": {...schema...}} # 补全接口也支持
注意:用
requests直连 HTTP 时没有 extra_body 展开机制 ------把guided_*键直接写进顶层 JSON body 即可。
2.3 结构化输出 + 流式:structured_outputs_config 的 transition window
- 约束解码与流式兼容;进阶参数
--structured-outputs-config '{"disable_any_whitespace": true}'等可微调生成风格。默认配置已覆盖绝大多数场景。
3. 工具调用(function calling)
- Tool calling 本质也是结构化输出:模型按 chat template 的约定格式输出工具调用文本,服务端用解析器 把它转成 OpenAI 标准的
tool_calls字段。两个启动参数缺一不可:
bash
--enable-auto-tool-choice # 打开自动工具调用
--tool-call-parser qwen3_xml # 按模型选择解析器(本项目默认值)
--reasoning-parser qwen3 # 推理模型把 <think> 分离到 reasoning_content(可选)
少这两个参数的典型报错 :
auto tool choice requires --enable-auto-tool-choice and --tool-call-parser to be set。parser 必须与模型输出格式匹配 :本机 Qwen3.5-4B 实测输出 XML 风格
<tool_call><function=get_weather><parameter=city>北京</parameter></function></tool_call>,用qwen3_xml才能得到finish_reason=tool_calls;若用hermes(只认 JSON 风格),请求不报错,但tool_calls=null、标记残留在content里。
- 模型 → 解析器选型对照
| 模型 | --tool-call-parser 值 |
|---|---|
| Qwen3 系(Hermes 风格) | hermes |
| Qwen3 新版 XML 风格 | qwen3_xml |
| GLM | glm45 / glm47 |
| DeepSeek | deepseek_v3 |
| Llama | llama3_json |
| Mistral | mistral |
hf兜底方案
| 项目 | 说明 |
|---|---|
| 用法 | --tool-call-parser hf(推理侧同理:--reasoning-parser hf) |
| 原理 | 直接读 checkpoint 自带的 response_template |
| 前提 | 模型带该字段即可,免专用解析器 |
| 收益 | 新模型发布后无需等 vLLM 适配 |
- 陷阱 :Rust 前端中
qwen3_xml指 Qwen3-Coder 的 XML 格式;普通 Qwen3 的 JSON 风格请用qwen3_json。 - 另外 parser 与模型兼容性在启动时就校验:配错 parser 不用等第一个请求报错,服务起不来时日志直接指出。
验证命令 (容器外可直接跑,期望看到 finish_reason: tool_calls):
bash
MODEL=$(curl -s http://127.0.0.1:8000/v1/models | python3 -c "import json,sys;print(json.load(sys.stdin)['data'][0]['id'])")
curl http://127.0.0.1:8000/v1/chat/completions -H 'Content-Type: application/json' -d '{
"model": "'"$MODEL"'",
"messages": [{"role": "user", "content": "调用工具查询北京天气"}],
"tools": [{"type": "function", "function": {"name": "get_weather", "description": "查询城市天气",
"parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}}],
"max_tokens": 1024, "temperature": 0
}'
4. 结构化输出的潜在问题
- schema 越复杂越容易把模型"逼死":过深的嵌套 + 过长的枚举会让模型在无效状态循环。先小后大,逐步加字段。
- 不要约束"推理过程":Qwen3/DeepSeek-R1 的思维链被 JSON 约束包裹后质量下降。正确方式是两段式(先自由思考再结构化)。
temperature与约束正交:约束保证合法性,温度仍影响选择分布;要确定性输出温度设 0。- 长 schema 的首 token 延迟 :编译状态机有一次性成本(毫秒级,通常无感);海量不同 schema 高频切换时 xgrammar 的编译缓存(源码里
grammar_bitmask_tracker的缓存逻辑)会兜底。 - ** guided 参数互斥**:
guided_json/guided_regex/guided_choice/guided_grammar同一请求只能用一个。
5. 实验
workspace/experiments/03_structured_output.py脚本覆盖四个用例,逐个断言输出合法性:
response_formatjson_schema → chat.completions(JSON 可解析、字段类型正确);guided_regex(Paris|London|Berlin)→ 输出严格等于三者之一;guided_choiceyes/no;/v1/completions+guided_json。
bash
docker compose exec vllm python3 /vllm-workspace/learn/experiments/03_structured_output.py
bash
[1] response_format/json_schema ✓ {'name': '巴黎', 'population_m': 2.15}
[2] guided_regex ✓ Paris
[3] guided_choice ✓ yes
[4] completions+guided_json ✓ {'city': 'London'}
6. 在 explorer 中验证
- 「源码搜索」搜
xgrammar:定位v1/structured_output/backend_xgrammar.py(XgrammarBackend)等扁平后端文件; - 搜
def apply_grammar_bitmask(v1/structured_output/utils.py),看 bitmask 如何按批应用与重排; - 「API 调试」手工构造一个
response_format请求(预设「结构化输出」一键载入),观察返回内容 100% 合法; - 对比实验:同一请求去掉
response_format,看模型"裸奔"输出的不稳定。