"""Tool-call parsers.
Every parser takes the model's visible answer text (reasoning already removed) plus the tool
schemas, and returns (calls, malformed) where calls is a list of {"name", "arguments"} dicts and
malformed counts tool-call-looking fragments it could not parse.
- qwen_strict: exactly the format Qwen3.6's chat template asks for
(value).
Surrounding text is allowed (vLLM's and mlx_lm's parsers allow it too).
- gemma_strict: exactly the format our Gemma system prompt asks for: ```tool_call fences holding
one JSON object {"name", "arguments"}.
- lenient: additionally recovers calls from missing closing tags, JSON inside ,
other code fences, bare JSON objects, single-quoted pseudo-JSON, trailing commas and
name/arguments key aliases. It only extracts; it never edits values.
- mlx_lm_qwen: what `mlx_lm.server` would return, using mlx_lm's own qwen3_coder parser.
"""
import ast
import importlib.util
import json
import re
from pathlib import Path
# --------------------------------------------------------------------------- helpers
STRING_TYPES = {"string", "str", "text", "enum"}
def param_types(tools):
out = {}
for t in tools:
f = t["function"]
out[f["name"]] = {k: v.get("type", "string") for k, v in f["parameters"]["properties"].items()}
return out
def _trim_one_newline(v):
if v.startswith("\n"):
v = v[1:]
if v.endswith("\n"):
v = v[:-1]
return v
def _convert(raw, typ, lenient):
"""Template rule: strings are written raw, everything else as JSON (tojson)."""
if typ in STRING_TYPES:
return raw
s = raw.strip()
try:
return json.loads(s)
except json.JSONDecodeError:
if lenient:
obj = _loads_loose(s)
if obj is not _FAIL:
return obj
return raw # the model wrote a bad value: keep it, the scorer will mark the arg wrong
_FAIL = object()
def _loads_loose(s):
"""json.loads, then Python-literal syntax (single quotes, True/None), then trailing commas."""
for cand in (s, re.sub(r",\s*([}\]])", r"\1", s)):
try:
return json.loads(cand)
except json.JSONDecodeError:
pass
py = re.sub(r"\btrue\b", "True", re.sub(r"\bfalse\b", "False", re.sub(r"\bnull\b", "None", cand)))
try:
return ast.literal_eval(py)
except (ValueError, SyntaxError, MemoryError, RecursionError, TypeError):
pass
return _FAIL
def _as_call(obj):
"""Accept {"name", "arguments"} and common aliases; return None if not call-shaped."""
if not isinstance(obj, dict):
return None
if isinstance(obj.get("function"), dict):
obj = obj["function"]
name = obj.get("name", obj.get("tool", obj.get("function")))
args = obj.get("arguments", obj.get("parameters", obj.get("args", {})))
if isinstance(args, str):
parsed = _loads_loose(args)
args = parsed if parsed is not _FAIL else args
if not isinstance(name, str) or not isinstance(args, dict):
return None
return {"name": name.strip(), "arguments": args}
def _balanced_objects(text):
"""Yield every top-level {...} or [...] substring with balanced brackets (string-aware)."""
i, n = 0, len(text)
while i < n:
if text[i] in "{[":
open_c = text[i]
close_c = "}" if open_c == "{" else "]"
depth, j, quote = 0, i, None
while j < n:
c = text[j]
if quote:
if c == "\\":
j += 1
elif c == quote:
quote = None
elif c in "\"'":
quote = c
elif c == open_c:
depth += 1
elif c == close_c:
depth -= 1
if depth == 0:
break
j += 1
if depth == 0 and j < n:
yield text[i:j + 1]
i = j + 1
continue
i += 1
def _calls_from_json_text(text):
calls = []
for frag in _balanced_objects(text):
obj = _loads_loose(frag)
items = obj if isinstance(obj, list) else [obj]
for it in items:
c = _as_call(it)
if c:
calls.append(c)
return calls
FENCE = re.compile(r"```[ \t]*([A-Za-z_]*)[ \t]*\n(.*?)(?:```|\Z)", re.S)
# --------------------------------------------------------------------------- Qwen (template format)
QWEN_BLOCK = re.compile(
r"\s*\n]+)>\n?((?:\s*\n]+>.*?)*)\s*\s*",
re.S,
)
QWEN_PARAM = re.compile(r"\n]+)>(.*?)", re.S)
def qwen_strict(text, tools):
types = param_types(tools)
calls = []
for m in QWEN_BLOCK.finditer(text):
name = m.group(1).strip()
args = {}
for p in QWEN_PARAM.finditer(m.group(2)):
k = p.group(1).strip()
args[k] = _convert(_trim_one_newline(p.group(2)), types.get(name, {}).get(k, "object"), False)
calls.append({"name": name, "arguments": args})
malformed = max(0, text.count("") - len(calls))
if not calls and " blocks in a segment, tolerating missing /."""
calls = []
for fm in re.finditer(r"\n]+)>(.*?)(?=", fm.group(2))[0]
args = {}
for pm in re.finditer(r"\n]+)>(.*?)(?=|" in text or "", text)
for seg in segs[1:] if "" in text else segs:
seg = seg.split("")[0]
got = _qwen_xml_lenient(seg, types) if " to (or end of output) is
handed to the qwen3_coder parser; a parse exception drops that call."""
mod = _load_mlx_qwen3_coder()
calls, bad = [], 0
for seg in text.split(mod.tool_call_start)[1:]:
seg = seg.split(mod.tool_call_end)[0]
try:
parsed = mod.parse_tool_call(seg, tools)
except Exception: # server catches ValueError/JSONDecodeError; anything else would 500
bad += 1
continue
for p in parsed if isinstance(parsed, list) else [parsed]:
calls.append({"name": p["name"], "arguments": p["arguments"]})
return calls, bad
PARSERS = {
"qwen": {"strict": qwen_strict, "lenient": lenient, "mlx_lm": mlx_lm_qwen},
"gemma": {"strict": gemma_strict, "lenient": lenient},
}
def looks_like_tool_call(text):
return bool(re.search(r"|