vllm-sglang-tool-call-parser-debugger 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. vllm_sglang_tool_call_parser_debugger/__init__.py +0 -0
  2. vllm_sglang_tool_call_parser_debugger/analyze.py +171 -0
  3. vllm_sglang_tool_call_parser_debugger/capture.py +221 -0
  4. vllm_sglang_tool_call_parser_debugger/cases.py +84 -0
  5. vllm_sglang_tool_call_parser_debugger/causes.py +150 -0
  6. vllm_sglang_tool_call_parser_debugger/chunking.py +87 -0
  7. vllm_sglang_tool_call_parser_debugger/cli.py +269 -0
  8. vllm_sglang_tool_call_parser_debugger/diagnose.py +760 -0
  9. vllm_sglang_tool_call_parser_debugger/examples/answer-returned-as-thinking.tools.json +1 -0
  10. vllm_sglang_tool_call_parser_debugger/examples/answer-returned-as-thinking.txt +1 -0
  11. vllm_sglang_tool_call_parser_debugger/examples/lost-while-streaming.tools.json +19 -0
  12. vllm_sglang_tool_call_parser_debugger/examples/lost-while-streaming.txt +1 -0
  13. vllm_sglang_tool_call_parser_debugger/examples/quoted-markup-becomes-call.tools.json +16 -0
  14. vllm_sglang_tool_call_parser_debugger/examples/quoted-markup-becomes-call.txt +11 -0
  15. vllm_sglang_tool_call_parser_debugger/examples/request.json +30 -0
  16. vllm_sglang_tool_call_parser_debugger/examples/wrong-parser.tools.json +19 -0
  17. vllm_sglang_tool_call_parser_debugger/examples/wrong-parser.txt +3 -0
  18. vllm_sglang_tool_call_parser_debugger/faketok.py +128 -0
  19. vllm_sglang_tool_call_parser_debugger/formats.py +268 -0
  20. vllm_sglang_tool_call_parser_debugger/minimize.py +40 -0
  21. vllm_sglang_tool_call_parser_debugger/realtok.py +86 -0
  22. vllm_sglang_tool_call_parser_debugger/reference.py +203 -0
  23. vllm_sglang_tool_call_parser_debugger/report.py +98 -0
  24. vllm_sglang_tool_call_parser_debugger/runner.py +194 -0
  25. vllm_sglang_tool_call_parser_debugger/sglang_driver.py +163 -0
  26. vllm_sglang_tool_call_parser_debugger/ui.py +257 -0
  27. vllm_sglang_tool_call_parser_debugger/util.py +23 -0
  28. vllm_sglang_tool_call_parser_debugger/vllm_driver.py +447 -0
  29. vllm_sglang_tool_call_parser_debugger/watch.py +231 -0
  30. vllm_sglang_tool_call_parser_debugger-0.1.0.dist-info/METADATA +143 -0
  31. vllm_sglang_tool_call_parser_debugger-0.1.0.dist-info/RECORD +35 -0
  32. vllm_sglang_tool_call_parser_debugger-0.1.0.dist-info/WHEEL +5 -0
  33. vllm_sglang_tool_call_parser_debugger-0.1.0.dist-info/entry_points.txt +3 -0
  34. vllm_sglang_tool_call_parser_debugger-0.1.0.dist-info/licenses/LICENSE +179 -0
  35. vllm_sglang_tool_call_parser_debugger-0.1.0.dist-info/top_level.txt +1 -0
File without changes
@@ -0,0 +1,171 @@
1
+ """One raw output in, one verdict out: shared by --output/--response/--server and the watch proxy."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+
7
+
8
+ def contract(request, got):
9
+ """What the request promised about tool calls, checked against what the client received."""
10
+ if not got:
11
+ return []
12
+ tc, calls, fin = request.get("tool_choice"), got.get("calls") or [], got.get("finish_reason")
13
+ names = [c.get("name") for c in calls]
14
+ out = []
15
+ if tc == "required" and not calls:
16
+ out.append('`tool_choice: "required"` was not enforced: the server returned no tool call')
17
+ elif isinstance(tc, dict):
18
+ want = (tc.get("function") or tc).get("name")
19
+ if not calls:
20
+ out.append(f"`tool_choice` names `{want}`, but the server returned no tool call")
21
+ elif any(n != want for n in names):
22
+ out.append(f"`tool_choice` names `{want}`, but the server returned "
23
+ + ", ".join(f"`{n}`" for n in names if n != want))
24
+ elif tc == "none" and calls:
25
+ out.append('`tool_choice: "none"`, but the server returned tool call(s) ' + ", ".join(f"`{n}`" for n in names))
26
+ if tc == "required" or isinstance(tc, dict): # forced calls bypass the parser: check what came back
27
+ import json as _json
28
+ for c in calls:
29
+ try:
30
+ _json.loads(c.get("arguments") or "")
31
+ except ValueError:
32
+ out.append(f"the forced call `{c.get('name')}` has arguments that are not valid JSON: "
33
+ f"{(c.get('arguments') or '')[:60]!r}")
34
+ ids = [c.get("id") for c in calls]
35
+ if calls and "id" in calls[0]: # captured from the server, which assigns ids
36
+ missing = [c.get("name") for c in calls if not c.get("id")]
37
+ if missing:
38
+ out.append("tool call(s) " + ", ".join(f"`{n}`" for n in missing) + " came back without an `id`, so the "
39
+ "client can't match the tool result to the call")
40
+ elif len(set(ids)) < len(ids):
41
+ out.append("several tool calls share one `id`, so the client can't tell their results apart")
42
+ if fin == "tool_calls" and not calls:
43
+ out.append('`finish_reason` is "tool_calls" but no tool call came back, so clients take the tool branch '
44
+ 'and find nothing to run')
45
+ return out
46
+
47
+
48
+ def _shown(got):
49
+ return {k: v for k, v in got.items() if k not in ("prompt_token_ids", "reasoning_fields", "problems")}
50
+
51
+
52
+ def replay_deltas(engine, fmt, text, tools, chunks, exp, texts=None):
53
+ """Replay the parser with the server's own delta boundaries (and, with `texts`, the delta texts the
54
+ server's parser saw when they lag the token ids)."""
55
+ from .diagnose import _markers, _safe, compare_expected, configure
56
+ configure(fmt)
57
+ markers = _markers(fmt)
58
+ groups = [engine.pieces(markers, c) for c in chunks]
59
+ kw = {"texts": texts} if texts else {}
60
+ got, crash = _safe(engine.run_stream, engine.parser_name(fmt), markers, text, tools, lambda p, m: groups, **kw)
61
+ from .diagnose import shape_issues
62
+ diff = [crash] if crash else ((compare_expected(exp, got, tools) if exp else []) + shape_issues(got))
63
+ return {"deltas": chunks, "got": got, "diff": diff}
64
+
65
+
66
+ def analyze(engine, engine_name, version, text, *, out, parser=None, tools=None, request=None, server=None,
67
+ server_got=None, stream_got=None, chunks=None, multi=0, notes=None, reasoning_parser=None,
68
+ prompt_think=False, name=None, markdown=False, prompt_state=None, held=None, version_tuple=None):
69
+ """Returns (exit_code, result, terminal_text, report_path). exit 0: correct, 1: a problem, 2: does not apply."""
70
+ from .diagnose import compare_expected, diagnose, to_markdown as diag_md
71
+ from .ui import resolve_parser, summary
72
+ notes = list(notes or [])
73
+ request = request or {}
74
+ broken = list(dict.fromkeys(contract(request, server_got) + contract(request, stream_got)))
75
+ contract_text = ("\n".join(["✗ The server broke the request's tool-call contract:"] + [f" • {b}" for b in broken]
76
+ + ["", "This is request handling (constrained decoding or response assembly), not the "
77
+ "tool parser. Report it upstream with your request and the raw output saved here."])
78
+ if broken else "")
79
+ fmt, note = resolve_parser(engine, parser, text)
80
+ if note == "plain-text":
81
+ short = " ".join(text.split())
82
+ if broken:
83
+ return 1, None, contract_text + f"\n\nThe model's raw output is plain text (\"{short[:80]}\"): the call " \
84
+ f"was never forced.", None
85
+ return 1, None, (f"✗ The model wrote no tool call: its output is plain text (\"{short[:80]}"
86
+ f"{'...' if len(short) > 80 else ''}\"). The server's parser has nothing to parse, so the "
87
+ f"cause is the prompt, the chat template or the model, not the server.\n\nWhat to do:\n"
88
+ f" • Check that the chat template renders your tools (the model's official template).\n"
89
+ f" • Try `tool_choice: \"required\"` to force a call."), None
90
+ if note:
91
+ notes.append(note)
92
+ if not reasoning_parser and any((x or {}).get("reasoning") for x in (server_got, stream_got)) and "</think>" in text:
93
+ reasoning_parser = "qwen3"
94
+ notes.append("your server returned reasoning_content but no --reasoning-parser was given: assuming "
95
+ "<think>...</think> reasoning (qwen3); pass --reasoning-parser NAME for an exact check")
96
+ if reasoning_parser:
97
+ closed = prompt_state == "closed" and "<think>" not in text
98
+ auto_think = not closed and "</think>" in text and not text.lstrip().startswith("<think>")
99
+ if auto_think and not prompt_think and prompt_state != "open":
100
+ notes.append("the output has </think> without <think>: assuming the chat template opens thinking "
101
+ "in the prompt")
102
+ engine.set_request_options(reasoning_parser=reasoning_parser,
103
+ prompt_think=not closed and (prompt_think or auto_think or prompt_state == "open"),
104
+ prompt_closed=closed,
105
+ chat_template_kwargs=request.get("chat_template_kwargs") or {"enable_thinking": True})
106
+ else:
107
+ engine.set_request_options(reasoning_parser=None, prompt_think=False, prompt_closed=False,
108
+ chat_template_kwargs=request.get("chat_template_kwargs"))
109
+ tc = request.get("tool_choice")
110
+ if hasattr(engine, "parser_used") and not engine.parser_used(fmt, tc):
111
+ msg = ('With `tool_choice: "none"` the server parses no tool calls, and none came back: nothing is wrong '
112
+ "here." if tc == "none" else
113
+ f"With tool_choice {json.dumps(tc)}, {engine_name} {version} does not run the "
114
+ f"{engine.parser_name(fmt)} parser: it constrains the output and reads the calls itself. The server "
115
+ f"honoured the tool_choice, and the parser check does not apply.")
116
+ from .causes import explain
117
+ extra = [c for c in explain({"parser": engine.parser_name(fmt), "expected": None}, request=request,
118
+ engine_name=engine_name, version=version, text=text, server_got=server_got,
119
+ stream_got=stream_got, prompt_state=prompt_state) if c.get("note")]
120
+ tail = "".join(f"\n Note: {c['why']}" for c in extra) + "".join(
121
+ f"\n\nWhat to do:\n" + "\n".join(f" • {a}" for c in extra for a in c["advice"]) for _ in [0] if extra)
122
+ return (1, None, contract_text + tail, None) if broken else (2, None, msg + tail, None)
123
+ import sys
124
+ if sys.stderr.isatty():
125
+ print(f"Checking the {engine.parser_name(fmt)} parser on {engine_name} {version}: no streaming, then 27 "
126
+ f"stream splits ...", file=sys.stderr, flush=True)
127
+ r = diagnose(engine, fmt, text, tools)
128
+ r["contract"] = broken
129
+ r["reasoning_parser"] = reasoning_parser
130
+ found_diffs = list(r.get("non_streaming_vs_output") or []) + [e for x in r.get("streaming") or [] for e in x["errors"]]
131
+ thinking = ("reasoning_content", "the end of the thinking")
132
+ if reasoning_parser and found_diffs and not any(k in d for d in found_diffs if not d.startswith(thinking)
133
+ for k in ("call", "argument", "crash")):
134
+ # only the split between thinking and answer is wrong: that is the reasoning parser's job
135
+ r["verdict"] = r["verdict"].replace(f"the {r['parser']} parser", f"the {reasoning_parser} reasoning parser")
136
+ r["component"] = f"{reasoning_parser} reasoning parser"
137
+ exp = r.get("expected")
138
+ server_diff = stream_diff = exact = None
139
+ if server_got is not None and exp:
140
+ server_diff = compare_expected(exp, server_got, tools)
141
+ r["server_returned"], r["server_vs_output"] = _shown(server_got), server_diff
142
+ if stream_got is not None and exp:
143
+ from .diagnose import shape_issues
144
+ stream_diff = compare_expected(exp, stream_got, tools) + shape_issues(stream_got)
145
+ r["server_streamed"], r["server_streamed_vs_output"] = _shown(stream_got), stream_diff
146
+ if chunks:
147
+ exact = replay_deltas(engine, r["format"], text, tools, chunks, exp, texts=held)
148
+ exact["multi_token_deltas"] = multi
149
+ r["exact_deltas"] = exact
150
+ from .causes import explain
151
+ found = explain(r, request=request, engine_name=engine_name, version=version, text=text, server_got=server_got,
152
+ stream_got=stream_got, server_diff=server_diff, stream_diff=stream_diff, exact=exact,
153
+ prompt_state=prompt_state, held=held)
154
+ for c in found:
155
+ if c.get("verdict"):
156
+ r["verdict_parser"], r["verdict"] = r["verdict"], c["verdict"]
157
+ r["causes"] = [c for c in found if c.get("why")]
158
+ r["advice"] = list(dict.fromkeys([a for c in found for a in c["advice"]] + list(r.get("advice") or [])))
159
+ os.makedirs(out, exist_ok=True)
160
+ md = diag_md(engine_name, version, r, text)
161
+ base = os.path.join(out, name or f"{engine_name}-{version}-{r['parser']}-output")
162
+ open(base + ".md", "w").write(md)
163
+ json.dump(r, open(base + ".json", "w"), ensure_ascii=False, indent=1, default=str)
164
+ term = md if markdown else summary(r, engine_name=engine_name, version=version, server=server,
165
+ server_got=server_got, server_diff=server_diff, notes=notes,
166
+ stream_got=stream_got, stream_diff=stream_diff, exact=exact,
167
+ report=os.path.abspath(base + ".md"), contract=broken)
168
+ bad = server_diff or stream_diff or (exact and exact["diff"]) or broken
169
+ code = 0 if "handles this output correctly" in r["verdict"] and not bad else 1
170
+ r["_server_diff"], r["_stream_diff"] = server_diff, stream_diff
171
+ return code, r, term, base + ".md"
@@ -0,0 +1,221 @@
1
+ """Get the model's raw output (special tokens kept) from a server response.
2
+
3
+ Easiest: tcdebug --server http://host:8000 --request failing_request.json (sends it once, decodes on
4
+ the server). Offline: save a response to a request sent with "return_token_ids": true and run
5
+ tcdebug --parser X --response resp.json --tokenizer <model>.
6
+ """
7
+ from __future__ import annotations
8
+
9
+
10
+ def token_ids_from_response(resp):
11
+ """The output token ids of the first choice, from a chat completion response (or a bare list)."""
12
+ if isinstance(resp, list) and all(isinstance(x, int) for x in resp):
13
+ return resp
14
+ choice = (resp.get("choices") or [{}])[0]
15
+ for key in ("token_ids", "response_token_ids", "output_token_ids", "output_ids"):
16
+ ids = choice.get(key) or resp.get(key)
17
+ if ids:
18
+ return ids[0] if ids and isinstance(ids[0], list) else ids
19
+ raise ValueError('no token ids in this response: send the request with "return_token_ids": true')
20
+
21
+
22
+ def raw_output_from_response(resp, tokenizer_name, tokenizer=None):
23
+ ids = token_ids_from_response(resp)
24
+ if tokenizer is None:
25
+ if not tokenizer_name:
26
+ raise SystemExit("--response needs --tokenizer <the model's Hugging Face id or local path>")
27
+ from transformers import AutoTokenizer
28
+ tokenizer = AutoTokenizer.from_pretrained(tokenizer_name)
29
+ return tokenizer.decode(ids, skip_special_tokens=False)
30
+
31
+
32
+ # --- Live capture: ask the user's own server for the raw output -------------------------------------------
33
+
34
+ def _http(url, payload=None, api_key=None, timeout=600):
35
+ import json as _j
36
+ import urllib.request
37
+ req = urllib.request.Request(url, data=None if payload is None else _j.dumps(payload).encode(),
38
+ headers={"Content-Type": "application/json",
39
+ **({"Authorization": f"Bearer {api_key}"} if api_key else {})})
40
+ with urllib.request.urlopen(req, timeout=timeout) as r:
41
+ return _j.loads(r.read().decode())
42
+
43
+
44
+ def _try(url, payload=None, api_key=None):
45
+ try:
46
+ return _http(url, payload, api_key, timeout=30)
47
+ except Exception:
48
+ return None
49
+
50
+
51
+ def server_info(base, api_key=None):
52
+ """Engine, version, parsers and model of a running vLLM or SGLang server (whatever it exposes)."""
53
+ base = base.rstrip("/").removesuffix("/v1")
54
+ info = {"base": base, "engine": None, "version": None, "parser": None, "reasoning_parser": None, "model": None}
55
+ mi = _try(base + "/model_info", api_key=api_key)
56
+ if isinstance(mi, dict) and "tool_call_parser" in mi: # SGLang
57
+ si = _try(base + "/server_info", api_key=api_key) or _try(base + "/get_server_info", api_key=api_key) or {}
58
+ info.update(engine="sglang", version=si.get("version"), parser=mi.get("tool_call_parser"),
59
+ reasoning_parser=mi.get("reasoning_parser"))
60
+ else:
61
+ v = _try(base + "/version", api_key=api_key)
62
+ if isinstance(v, dict) and "version" in v:
63
+ info.update(engine="vllm", version=v["version"])
64
+ models = _try(base + "/v1/models", api_key=api_key)
65
+ if isinstance(models, dict) and models.get("data"):
66
+ info["model"] = models["data"][0].get("id")
67
+ return info
68
+
69
+
70
+ def capture(base, request, api_key=None, model=None):
71
+ """Send the request once, non-streaming, asking for the output token ids; decode them on the server
72
+ with special tokens kept. Returns (raw_text, server_response)."""
73
+ base = base.rstrip("/").removesuffix("/v1")
74
+ req = dict(request)
75
+ req.pop("stream_options", None)
76
+ req.update(stream=False, return_token_ids=True)
77
+ if model and not req.get("model"):
78
+ req["model"] = model
79
+ resp = _http(base + "/v1/chat/completions", req, api_key)
80
+ try:
81
+ ids = token_ids_from_response(resp)
82
+ except ValueError:
83
+ raise SystemExit("The server returned no token ids. vLLM 0.10.2+ and SGLang 0.5.17+ return them for "
84
+ '"return_token_ids": true. On older versions, save the raw output and use --output.')
85
+ d = _http(base + "/detokenize", {"model": req.get("model"), "tokens": ids, "skip_special_tokens": False}, api_key)
86
+ return d.get("prompt", d.get("text")), resp
87
+
88
+
89
+ def prompt_state(base, prompt_ids, model=None, api_key=None):
90
+ """How the rendered prompt leaves the thinking: "open" (the template opened <think>), "closed" (it wrote
91
+ <think></think>, i.e. thinking off), or None. Read from the end of the prompt ids the server reports."""
92
+ import re
93
+ if not prompt_ids:
94
+ return None
95
+ try:
96
+ tail = detokenize(base.rstrip("/").removesuffix("/v1"), list(prompt_ids)[-16:], model, api_key) or ""
97
+ except Exception:
98
+ return None
99
+ tail = tail.rstrip()
100
+ if re.search(r"</think>$", tail):
101
+ return "closed"
102
+ if re.search(r"<think>$", tail):
103
+ return "open"
104
+ return None
105
+
106
+
107
+ def server_result(resp):
108
+ """What the server returned to the client (non-streaming), in the shape the diagnosis uses."""
109
+ msg = ((resp.get("choices") or [{}])[0]).get("message") or {}
110
+ calls = [{"name": (c.get("function") or {}).get("name"), "arguments": (c.get("function") or {}).get("arguments"),
111
+ "id": c.get("id")} for c in msg.get("tool_calls") or []]
112
+ return {"content": msg.get("content"), "reasoning": msg.get("reasoning_content") or msg.get("reasoning"),
113
+ "calls": calls, "finish_reason": ((resp.get("choices") or [{}])[0]).get("finish_reason"),
114
+ "reasoning_fields": sorted(k for k in ("reasoning", "reasoning_content") if msg.get(k)),
115
+ "prompt_token_ids": resp.get("prompt_token_ids")}
116
+
117
+
118
+ def _sse(url, payload, api_key=None, timeout=600):
119
+ import json as _j
120
+ import urllib.request
121
+ req = urllib.request.Request(url, data=_j.dumps(payload).encode(),
122
+ headers={"Content-Type": "application/json", "Accept": "text/event-stream",
123
+ **({"Authorization": f"Bearer {api_key}"} if api_key else {})})
124
+ with urllib.request.urlopen(req, timeout=timeout) as r:
125
+ for line in r:
126
+ line = line.decode().strip()
127
+ if line.startswith("data:") and line[5:].strip() not in ("", "[DONE]"):
128
+ yield _j.loads(line[5:])
129
+
130
+
131
+ def capture_stream(base, request, api_key=None, model=None, token_ids=True):
132
+ """Send the request streaming, as the client does. Returns what the client received and, where the
133
+ server sends them (vLLM), the token ids of every delta: the server's exact delta boundaries."""
134
+ base = base.rstrip("/").removesuffix("/v1")
135
+ req = dict(request, stream=True)
136
+ if token_ids:
137
+ req["return_token_ids"] = True
138
+ if model and not req.get("model"):
139
+ req["model"] = model
140
+ content, reasoning, calls, chunk_ids, finish, fields, prompt_ids = "", "", [], [], None, set(), None
141
+ counts = {}
142
+ for ev in _sse(base + "/v1/chat/completions", req, api_key):
143
+ prompt_ids = prompt_ids or ev.get("prompt_token_ids")
144
+ for ch in ev.get("choices") or []:
145
+ if ch.get("index", 0) != 0:
146
+ continue
147
+ if ch.get("token_ids"):
148
+ chunk_ids.append(list(ch["token_ids"]))
149
+ finish = ch.get("finish_reason") or finish
150
+ d = ch.get("delta") or {}
151
+ content += d.get("content") or ""
152
+ reasoning += d.get("reasoning_content") or d.get("reasoning") or ""
153
+ fields |= {k for k in ("reasoning", "reasoning_content") if d.get(k)}
154
+ for tc in d.get("tool_calls") or []:
155
+ i = tc.get("index", len(calls))
156
+ while len(calls) <= i:
157
+ calls.append({"name": None, "arguments": "", "id": None})
158
+ seen = counts.setdefault(i, {"ids": 0, "type": False, "first_id": None})
159
+ if seen["first_id"] is None:
160
+ seen["first_id"] = bool(tc.get("id"))
161
+ seen["ids"] += bool(tc.get("id"))
162
+ seen["type"] |= tc.get("type") == "function"
163
+ calls[i]["id"] = calls[i]["id"] or tc.get("id")
164
+ f = tc.get("function") or {}
165
+ calls[i]["name"] = (calls[i]["name"] or "") + f["name"] if f.get("name") else calls[i]["name"] # clients concatenate, as the openai SDK does
166
+ calls[i]["arguments"] += f.get("arguments") or ""
167
+ problems = [] # the same per-call checks the replay keeps
168
+ for i, c in sorted(counts.items()):
169
+ if c["ids"] > 1:
170
+ problems.append(f"call {i}: id sent {c['ids']} times")
171
+ elif c["ids"] == 0:
172
+ problems.append(f"call {i}: no id sent")
173
+ elif not c["first_id"]:
174
+ problems.append(f"call {i}: id missing from the call's first delta")
175
+ if not c["type"]:
176
+ problems.append(f'call {i}: type "function" never sent')
177
+ return ({"content": content or None, "reasoning": reasoning or None, "calls": calls, "finish_reason": finish,
178
+ "reasoning_fields": sorted(fields), "prompt_token_ids": prompt_ids, "problems": problems}, chunk_ids)
179
+
180
+
181
+ def detokenize(base, ids, model=None, api_key=None):
182
+ base = base.rstrip("/").removesuffix("/v1")
183
+ d = _http(base + "/detokenize", {"model": model, "tokens": ids, "skip_special_tokens": False}, api_key)
184
+ return d.get("prompt", d.get("text"))
185
+
186
+
187
+ def delta_texts(base, chunk_ids, model=None, api_key=None):
188
+ """The raw text of each delta, special tokens kept. Decoded cumulatively, as the server's incremental
189
+ detokenizer does, so a character split across deltas lands where the server put it."""
190
+ out, ids, prev = [], [], ""
191
+ for c in chunk_ids:
192
+ ids += c
193
+ cur = detokenize(base, ids, model, api_key)
194
+ if cur.endswith("�"): # incomplete UTF-8: the server holds these bytes back too
195
+ out.append("")
196
+ continue
197
+ out.append(cur[len(prev):])
198
+ prev = cur
199
+ return [t for t in out if t]
200
+
201
+
202
+ def stop_hold(request):
203
+ """vLLM holds back the last len(longest stop string) - 1 characters of the text until the end of the
204
+ stream, so each delta's text lags its token ids (the output processor's stop-string buffer)."""
205
+ stops = request.get("stop") or []
206
+ stops = [stops] if isinstance(stops, str) else [x for x in stops if x]
207
+ if not stops or request.get("include_stop_str_in_output"):
208
+ return 0
209
+ return max(map(len, stops)) - 1
210
+
211
+
212
+ def held_texts(chunks, hold):
213
+ """The delta texts the server's parser saw, given each delta's full text and the stop-string hold."""
214
+ out, full, sent = [], "", 0
215
+ for i, c in enumerate(chunks):
216
+ full += c
217
+ upto = len(full) if i == len(chunks) - 1 else max(sent, len(full) - hold)
218
+ out.append(full[sent:upto])
219
+ sent = upto
220
+ return out
221
+
@@ -0,0 +1,84 @@
1
+ """Test cases: what the model meant, independent of any output format.
2
+
3
+ Each case targets a failure mode seen in real GitHub issues (see FINDINGS.md):
4
+ text around calls, several calls, nested or tricky arguments, empty arguments.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass, field
9
+
10
+
11
+ @dataclass
12
+ class Call:
13
+ name: str
14
+ args: dict
15
+
16
+
17
+ @dataclass
18
+ class Case:
19
+ id: str
20
+ calls: list[Call]
21
+ before: str = "" # content the model writes before the first call
22
+ after: str = "" # content after the last call (most formats never have it)
23
+ reasoning: str = "" # thinking text, for reasoning-parser runs
24
+ thinking: bool | None = None # reasoning cases: True = thinking on, False = thinking turned off
25
+ note: str = ""
26
+ tags: list[str] = field(default_factory=list)
27
+
28
+
29
+ W = Call("get_weather", {"city": "Paris", "unit": "celsius"})
30
+ CASES = [
31
+ Case("single", [W], note="one call, nothing else"),
32
+ Case("text-before", [W], before="Let me check the weather for you.", tags=["content"],
33
+ note="text before the call must stay in content"),
34
+ Case("text-after", [W], after="I will report back once it returns.", tags=["content"],
35
+ note="text after the call must stay in content, not leak into arguments"),
36
+ Case("two-calls", [W, Call("get_time", {"timezone": "Europe/Paris"})], tags=["multi"],
37
+ note="both calls must come back, in order"),
38
+ Case("three-calls-text", [W, Call("get_time", {"timezone": "UTC"}), Call("get_weather", {"city": "Tokyo", "unit": "celsius"})],
39
+ before="Checking three things.", tags=["multi", "content"]),
40
+ Case("nested-args", [Call("create_event", {"title": "Sync", "attendees": [{"name": "Ana", "email": "ana@x.io"}],
41
+ "options": {"remind": True, "minutes": [5, 30]}})],
42
+ tags=["args"], note="nested objects and arrays"),
43
+ Case("negative-and-float", [Call("move", {"dx": -3, "dy": 2.5, "scale": -0.75, "steps": 0})], tags=["args"],
44
+ note="negative numbers, floats, zero"),
45
+ Case("unicode-quotes", [Call("search", {"query": "café \"best\" 東京 🍣", "path": "C:\\data\\x"})], tags=["args"],
46
+ note="unicode, emoji, escaped quotes and backslashes"),
47
+ Case("empty-args", [Call("list_files", {})], tags=["args"], note="a tool that takes no parameters"),
48
+ Case("bool-null", [Call("toggle", {"on": False, "limit": None, "ids": []})], tags=["args"],
49
+ note="false, null and an empty list (limit is integer-or-null, so null is unambiguous in every format)"),
50
+ Case("json-looking-text", [W], before="Here is JSON: {\"a\": 1}. Now the call.", tags=["content"],
51
+ note="braces in prose must not be mistaken for a call"),
52
+ Case("no-call", [], before="I can answer without tools: it is sunny in Paris.", tags=["content"],
53
+ note="plain answer, no call"),
54
+ ]
55
+
56
+ TOOLS = [
57
+ {"type": "function", "function": {"name": n, "description": n, "parameters": {"type": "object", "properties": p}}}
58
+ for n, p in [
59
+ ("get_weather", {"city": {"type": "string"}, "unit": {"type": "string"}}),
60
+ ("get_time", {"timezone": {"type": "string"}}),
61
+ ("create_event", {"title": {"type": "string"}, "attendees": {"type": "array"}, "options": {"type": "object"}}),
62
+ ("move", {"dx": {"type": "number"}, "dy": {"type": "number"}, "scale": {"type": "number"}, "steps": {"type": "integer"}}),
63
+ ("search", {"query": {"type": "string"}, "path": {"type": "string"}}),
64
+ ("list_files", {}),
65
+ ("toggle", {"on": {"type": "boolean"}, "limit": {"type": ["integer", "null"]}, "ids": {"type": "array"}}),
66
+ ]
67
+ ]
68
+
69
+
70
+ # Reasoning cases: where thinking ends and the answer and tool calls begin.
71
+ REASONING_CASES = [
72
+ Case("think-answer", [], before="It is sunny in Paris.", reasoning="The user wants the weather. I know it.",
73
+ thinking=True, note="thinking, then a plain answer"),
74
+ Case("think-call", [W], reasoning="I need the weather tool for Paris.", thinking=True,
75
+ note="thinking, then a tool call"),
76
+ Case("think-text-call", [W], before="Let me check.", reasoning="Use the weather tool.", thinking=True,
77
+ note="thinking, a sentence, then a tool call"),
78
+ Case("think-two-calls", [W, Call("get_time", {"timezone": "Europe/Paris"})],
79
+ reasoning="Weather first, then the time.", thinking=True, note="thinking, then two calls"),
80
+ Case("empty-think-call", [W], reasoning="", thinking=True, note="an empty thinking block, then a call"),
81
+ Case("no-think-call", [W], thinking=False, note="thinking turned off (enable_thinking=false), then a call"),
82
+ Case("no-think-answer", [], before="It is sunny in Paris.", thinking=False,
83
+ note="thinking turned off, plain answer"),
84
+ ]
@@ -0,0 +1,150 @@
1
+ """Named causes: situations where the parser check alone would point at the wrong thing, or where the request,
2
+ the chat template or the model explains what the client got. Each one says why, and what to change.
3
+
4
+ Every cause here came from a real report (vLLM issue numbers in comments) and is checked on vLLM's real server in
5
+ validation/slice/.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import re
11
+
12
+
13
+ def _v(version):
14
+ m = re.match(r"(\d+)\.(\d+)\.?(\d*)", str(version or ""))
15
+ return tuple(int(x or 0) for x in m.groups()) if m else (0, 0, 0)
16
+
17
+
18
+ def _hermes_required_one_call(engine_name):
19
+ """vLLM's hermes structural tag for tool_choice "required" allows no separator between calls, so the
20
+ model can't start a second call after the first (vllm#60769). Read from the installed engine."""
21
+ if engine_name != "vllm":
22
+ return False
23
+ try:
24
+ import importlib.util
25
+ base = os.path.dirname(importlib.util.find_spec("vllm").origin)
26
+ src = open(os.path.join(base, "tool_parsers", "structural_tag_registry.py")).read()
27
+ except (OSError, AttributeError, ImportError):
28
+ return False
29
+ for head in ("def _hermes_style_structural_tag(", '@register_vllm_structural_tag("hermes")'):
30
+ i = src.find(head)
31
+ if i < 0:
32
+ continue
33
+ start = src.find("def ", i) + 4
34
+ body = re.split(r"\n(?=def |@)", src[start:], maxsplit=1)[0]
35
+ if re.search(r'else:\s*suffix_tag = TagsWithSeparatorFormat\(\s*tags=[^,]+,\s*separator=""', body):
36
+ return True
37
+ return False
38
+
39
+
40
+ def explain(r, *, request, engine_name, version, text, server_got=None, stream_got=None, server_diff=None,
41
+ stream_diff=None, exact=None, prompt_state=None, held=None):
42
+ """Returns a list of {"why": str, "advice": [str], "verdict": optional replacement headline, "note": bool}."""
43
+ out = []
44
+ request = request or {}
45
+ got = stream_got or server_got or {}
46
+ exp = r.get("expected") or {}
47
+ rp = r.get("reasoning_parser")
48
+ tc = request.get("tool_choice")
49
+ calls = got.get("calls") or []
50
+ finish = got.get("finish_reason")
51
+ diffs = list(server_diff or []) + list(stream_diff or [])
52
+ body = text.split("</think>", 1)[-1] if rp else text
53
+
54
+ # The model wrote malformed call markup: neither reading finds a valid call, the parser guesses one (vllm#56077).
55
+ ns = r.get("non_streaming") or {}
56
+ start = next((m for m in ("<tool_call>", "<function_calls>", "<|tool_call_begin|>") if m in body), None)
57
+ if (exp and not exp.get("calls") and not exp.get("quoted") and start and not exp.get("format")
58
+ and not exp.get("calls_in_thinking") and start in (exp.get("content") or "")
59
+ and not (finish == "length" and body.rstrip().endswith(start))):
60
+ snippet = " ".join(body[body.find(start):].split("</tool_call>")[0].split())
61
+ else:
62
+ snippet = ""
63
+ # a call attempt (a function or a JSON name), not a marker quoted in prose, and nothing more specific found
64
+ if snippet and re.search(r'<function=|\{\s*"name"', snippet) and "stray" not in r.get("verdict", ""):
65
+ guessed = ", ".join(f"`{' '.join(str(c.get('name')).split())[:60]}`" for c in (ns.get("calls") or calls))
66
+ then = (f"The {r['parser']} parser guesses {guessed} from it" if guessed else
67
+ f"The {r['parser']} parser drops it, so the client gets no call" +
68
+ ("" if (ns.get("content") or "").strip() else " and no text"))
69
+ if finish != "length":
70
+ out.append({"verdict": f"The model's output is malformed: `{snippet[:80]}` is not a valid {r['parser']} "
71
+ f"tool call, so no call can be read from it. {then}; the cause is the generation, "
72
+ f"not the parser.",
73
+ "why": "", "advice": [
74
+ "Check the raw output at temperature 0. If it is malformed only with speculative decoding "
75
+ "(ngram, MTP, EAGLE) or a quantized checkpoint, turn that off for tool calls and report it "
76
+ "to vLLM as a generation bug, with the raw output saved here."]})
77
+
78
+ # The output was cut off by max_tokens (vllm#47137, vllm#35221).
79
+ if finish == "length":
80
+ inside_call = start and not re.search(r"</tool_call>\s*$", body.strip()) and body.rfind(start) > body.rfind("</tool_call>")
81
+ inside_think = rp and "</think>" not in text and (exp.get("reasoning") or "").strip()
82
+ where = ("inside a tool call, so there is no complete call to return" if inside_call else
83
+ "inside the thinking, before any answer" if inside_think else "before the model finished")
84
+ out.append({"why": f"The output was cut off by `max_tokens` (finish_reason \"length\") {where}.",
85
+ "advice": ["Raise `max_tokens` (and any thinking budget) for tool-calling requests."]})
86
+
87
+ # The thinking never ended and the model stopped: there is no answer (vllm#55420).
88
+ elif (rp and "</think>" not in text and (exp.get("reasoning") or "").strip() and not (exp.get("content") or "").strip()
89
+ and not exp.get("calls_in_thinking") and finish in (None, "stop")):
90
+ out.append({"why": "The model ended inside its thinking: it never wrote </think>, so there is no answer and "
91
+ "content is empty. The server returned what the model wrote; the cause is the model, which "
92
+ "sampled its end-of-turn token while still thinking.",
93
+ "advice": ["Retry the request; if it keeps happening, lower the temperature, turn thinking off for "
94
+ "these turns, or set a thinking budget so the model has to close its thinking."]})
95
+
96
+ # The template closed the thinking but the reasoning parser was not told (vllm#53284).
97
+ if (rp and prompt_state == "closed" and "<think>" not in text and (exp.get("content") or "").strip()
98
+ and any("not returned as content" in d or d.startswith(("reasoning_content", "the end of the thinking")) for d in
99
+ diffs + list(r.get("non_streaming_vs_output") or []))):
100
+ kw = request.get("chat_template_kwargs") or {}
101
+ if kw.get("enable_thinking") is not False:
102
+ out.append({"why": f"Your chat template already closed the thinking (the prompt ends with "
103
+ f"<think></think>), but the {rp} reasoning parser only reads "
104
+ f"`enable_thinking` from chat_template_kwargs, so it still expects thinking and returns "
105
+ f"the whole answer as reasoning.",
106
+ "advice": ['Send `"chat_template_kwargs": {"enable_thinking": false}` whenever the template '
107
+ "turns thinking off (reasoning_effort none, a /no_think tag, or tools)."]})
108
+
109
+ # Stop strings make vLLM hold back text, so the reasoning parser sees </think>'s token before its text (vllm#38789).
110
+ if held and stream_diff:
111
+ stops = request.get("stop")
112
+ out.append({"why": f"Your request sets `stop` ({stops!r}), so vLLM holds back the end of every streamed delta "
113
+ f"until the stream ends. The {rp or r['parser']} parser then sees a token before its text "
114
+ f"(here </think>) and puts it in the wrong place. Without streaming the result is right.",
115
+ "advice": ["Drop `stop` for streamed requests (the model's own end token already stops it), or "
116
+ "send them with `\"stream\": false`."]})
117
+
118
+ # tool_choice "required" after the tools returned (vllm#36233).
119
+ msgs = request.get("messages") or []
120
+ if tc == "required" and calls and msgs and msgs[-1].get("role") == "tool":
121
+ out.append({"note": True,
122
+ "why": 'With `tool_choice: "required"` the server has to return a tool call on every turn, also '
123
+ "after your tools returned, so the model can't answer in text.",
124
+ "advice": ['Send `tool_choice: "auto"` on the turns after tool results.']})
125
+
126
+ # tool_choice "required" with the hermes grammar allows one call (vllm#60769).
127
+ if (tc == "required" and len(calls) == 1 and r.get("parser") in ("hermes", "qwen25")
128
+ and _hermes_required_one_call(engine_name)):
129
+ out.append({"note": True,
130
+ "why": f'With `tool_choice: "required"`, {engine_name} {version}\'s hermes grammar allows no '
131
+ f"newline between calls, so the model can't write a second call: you get one call where "
132
+ f"it would write several (vllm#60769).",
133
+ "advice": ['If you need several calls in one turn, send `tool_choice: "auto"`.']})
134
+
135
+ # tool_choice null without streaming drops the calls (vllm#63346).
136
+ if ("tool_choice" in request and tc is None and server_got is not None and exp.get("calls")
137
+ and not (server_got.get("calls") or [])):
138
+ out.append({"why": f"Your request sends `tool_choice: null`. {engine_name} {version} treats that as no tool "
139
+ f"choice without streaming and drops the calls (streaming keeps them).",
140
+ "advice": ['Send `tool_choice: "auto"`, or leave the field out.']})
141
+
142
+ # vLLM 0.16+ sends the thinking as `reasoning` only (vllm#37558).
143
+ fields = got.get("reasoning_fields")
144
+ if fields == ["reasoning"] and (got.get("reasoning") or "").strip():
145
+ out.append({"note": True,
146
+ "why": "Your server sends the thinking in the `reasoning` field only (vLLM 0.16+ dropped "
147
+ "`reasoning_content`). Clients that read `reasoning_content` (Spring AI, older SDKs and UIs) "
148
+ "show it as empty.",
149
+ "advice": ["Read `reasoning` in your client, or update it to a version that does."]})
150
+ return out