"""Parse model tool calls and check them against BFCL ground truth (AST style). Supported call formats - Qwen3.5: value - JSON: {"name": ..., "arguments": {...}} (Granite, Qwen3, many others) - OpenAI: [{"type": "function", "function": {"name": ..., "arguments": ""}}], e.g. in a ```json block - Pythonic: <|tool_call_start|>[name(a=1, b="x"), other(...)]<|tool_call_end|> (LFM2/LFM2.5) Checking follows BFCL's AST rules in simplified form: - function names compared after mapping "." to "_" - every argument the model gives must be a known gold parameter with an accepted value - gold parameters the model omits must be optional ("" among accepted values) - strings compared case-insensitively, ignoring spaces and the punctuation BFCL strips - numbers: int and float accepted interchangeably when equal - parallel categories: calls matched as a multiset, order free - irrelevance: correct when the model makes no call """ from __future__ import annotations import ast import json import re from collections.abc import Iterable # --------------------------------------------------------------------------- # Schema conversion (BFCL -> JSON schema used by chat templates) # --------------------------------------------------------------------------- _TYPE_MAP = {"dict": "object", "float": "number", "tuple": "array", "any": "string"} def to_json_schema(node): if isinstance(node, dict): out = {} for k, v in node.items(): if k == "type" and isinstance(v, str): out[k] = _TYPE_MAP.get(v, v) else: out[k] = to_json_schema(v) return out if isinstance(node, list): return [to_json_schema(x) for x in node] return node def to_tools(functions: list[dict]) -> list[dict]: return [{"type": "function", "function": {"name": f["name"], "description": f.get("description", ""), "parameters": to_json_schema(f["parameters"])}} for f in functions] # --------------------------------------------------------------------------- # Parsing # --------------------------------------------------------------------------- def _coerce(text: str): t = text.strip() try: return json.loads(t) except (json.JSONDecodeError, ValueError): pass try: return ast.literal_eval(t) except (ValueError, SyntaxError): return t def _parse_qwen_xml(text: str) -> list[dict]: calls = [] for fm in re.finditer(r"\s]+)>(.*?)", text, flags=re.DOTALL): args = {} for pm in re.finditer(r"\s]+)>\n?(.*?)\n?", fm.group(2), flags=re.DOTALL): args[pm.group(1)] = _coerce(pm.group(2)) calls.append({"name": fm.group(1), "arguments": args}) return calls def _parse_json_calls(text: str) -> list[dict]: blocks = re.findall(r"(.*?)(?:|$)", text, flags=re.DOTALL) or [text] calls = [] for b in blocks: b = b.strip() dec = json.JSONDecoder() i = 0 while i < len(b): j = b.find("{", i) k = b.find("[", i) starts = [x for x in (j, k) if x >= 0] if not starts: break s = min(starts) try: obj, end = dec.raw_decode(b, s) except json.JSONDecodeError: i = s + 1 continue objs = obj if isinstance(obj, list) else [obj] for o in objs: if isinstance(o, dict) and "name" not in o and isinstance(o.get("function"), dict): o = o["function"] # OpenAI style: {"type": "function", "function": {"name", "arguments"}} if isinstance(o, dict) and "name" in o: a = o.get("arguments", o.get("parameters", {})) if isinstance(a, str): a = _coerce(a) calls.append({"name": o["name"], "arguments": a if isinstance(a, dict) else {}}) i = end return calls def _dotted(node) -> str | None: if isinstance(node, ast.Name): return node.id if isinstance(node, ast.Attribute): base = _dotted(node.value) return f"{base}.{node.attr}" if base else None return None def _parse_pythonic(text: str) -> list[dict]: m = re.search(r"<\|tool_call_start\|>(.*?)(?:<\|tool_call_end\|>|$)", text, flags=re.DOTALL) body = (m.group(1) if m else text).strip() if not body.startswith("["): body = "[" + body + "]" try: tree = ast.parse(body, mode="eval") except SyntaxError: return [] calls = [] elts = tree.body.elts if isinstance(tree.body, (ast.List, ast.Tuple)) else [tree.body] for e in elts: if not isinstance(e, ast.Call): continue name = _dotted(e.func) if not name: continue args = {} for kw in e.keywords: try: args[kw.arg] = ast.literal_eval(kw.value) except ValueError: args[kw.arg] = ast.unparse(kw.value) calls.append({"name": name, "arguments": args}) return calls END_OF_TURN = ("", "", "", "") def parse_calls(text: str) -> list[dict]: # Some models (Gemma-based) keep writing after their turn ends, e.g. an invented tool # response. Only the text before the end of the model's turn is its answer. for marker in END_OF_TURN: text = text.split(marker)[0] if "" in text: return _parse_pythonic(text) if "" in text or re.search(r'\{\s*"name"\s*:', text) or re.search(r'"function"\s*:\s*\{', text): return _parse_json_calls(text) return [] # --------------------------------------------------------------------------- # Checking # --------------------------------------------------------------------------- def _norm_name(n: str) -> str: return n.replace(".", "_") def _norm_str(s: str) -> str: return re.sub(r"[ ,./\-_*^]", "", s).lower() def _value_ok(v, accepted: Iterable) -> bool: for a in accepted: if a == "": continue if isinstance(a, bool) or isinstance(v, bool): if a is v or (isinstance(v, str) and v.lower() == str(a).lower()): return True continue if isinstance(a, (int, float)) and isinstance(v, (int, float)): if float(a) == float(v): return True continue if isinstance(a, (int, float)) and isinstance(v, str): try: if float(v) == float(a): return True except ValueError: pass continue if isinstance(a, str) and isinstance(v, str): if _norm_str(a) == _norm_str(v): return True continue if isinstance(a, list) and isinstance(v, (list, tuple)): if len(a) == len(v) and all(_value_ok(x, [y]) for x, y in zip(v, a)): return True continue if isinstance(a, dict) and isinstance(v, dict): if set(v) <= set(a) and all(_value_ok(v[k], a[k]) for k in v) and \ all("" in a[k] for k in set(a) - set(v)): return True continue return False def call_matches(call: dict, gold: dict) -> bool: (gname, gargs), = gold.items() if _norm_name(call["name"]) != _norm_name(gname): return False args = call.get("arguments") or {} for k, v in args.items(): if k not in gargs or not _value_ok(v, gargs[k]): return False return all("" in acc for k, acc in gargs.items() if k not in args) def check(category: str, calls: list[dict], ground_truth: list[dict] | None) -> bool: if category == "irrelevance": return len(calls) == 0 if len(calls) != len(ground_truth): return False if category in ("simple", "multiple"): return call_matches(calls[0], ground_truth[0]) # parallel: find a perfect matching (small sizes, greedy with backtracking) def match(i: int, used: set) -> bool: if i == len(ground_truth): return True for j, c in enumerate(calls): if j not in used and call_matches(c, ground_truth[i]): if match(i + 1, used | {j}): return True return False return match(0, set())