"""Exact-match scoring of parsed tool calls against ground truth, with one failure label per miss. Failure labels (one per task, first that applies): truncated_by_cap thinking run hit the token cap before producing an answer malformed_output a call was needed but the output's tool-call text could not be parsed skipped_needed_call a call was needed but the model answered in text (or made only some calls) called_when_not_needed no tool was needed but the model called one wrong_tool a call used a tool name that the task did not need wrong_or_missing_arg right tool(s), but an expected argument is missing or has the wrong value hallucinated_arg right tool(s) and values, plus an argument not in the schema, or an optional argument the user never asked for set to a non-default value """ import ast import operator import re FAILURES = ["truncated_by_cap", "malformed_output", "skipped_needed_call", "called_when_not_needed", "wrong_tool", "wrong_or_missing_arg", "hallucinated_arg"] REL_TOL, ABS_TOL = 1e-3, 1e-6 def norm_str(s): return re.sub(r"\s+", " ", s).strip().casefold() def norm_time(s): """'9:15', '09:15' and '09:15:00' -> '09:15'; anything else is returned unchanged.""" m = re.fullmatch(r"(\d{1,2}):(\d{2})(?::00)?", s.strip()) return f"{int(m.group(1)):02d}:{m.group(2)}" if m else s.strip() def is_num(x): return isinstance(x, (int, float)) and not isinstance(x, bool) def num_eq(a, b): return abs(a - b) <= max(ABS_TOL, REL_TOL * abs(b)) _OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv, ast.Pow: operator.pow, ast.USub: operator.neg, ast.UAdd: operator.pos, ast.Mod: operator.mod} def safe_eval(expr): """Arithmetic only: numbers, + - * / ^ ** % and parentheses. Returns None if not evaluable.""" if not isinstance(expr, str): return None e = expr.replace("^", "**").replace("×", "*").replace("÷", "/").replace(",", "") e = re.sub(r"(\d+(?:\.\d+)?)\s*%", r"(\1/100)", e) # "18%" -> (18/100) try: tree = ast.parse(e, mode="eval") except SyntaxError: return None def ev(n): if isinstance(n, ast.Expression): return ev(n.body) if isinstance(n, ast.Constant) and is_num(n.value): return n.value if isinstance(n, ast.BinOp) and type(n.op) in _OPS: l, r = ev(n.left), ev(n.right) if isinstance(n.op, ast.Pow) and abs(r) > 64: raise ValueError return _OPS[type(n.op)](l, r) if isinstance(n, ast.UnaryOp) and type(n.op) in _OPS: return _OPS[type(n.op)](ev(n.operand)) raise ValueError try: return float(ev(tree)) except (ValueError, ZeroDivisionError, OverflowError, TypeError): return None def match_value(exp, got): """True if `got` satisfies the expected value or matcher `exp`.""" if isinstance(exp, dict) and len(exp) == 1 and next(iter(exp)).startswith("$"): (op, arg), = exp.items() if op == "$any": return any(match_value(a, got) for a in arg) if op == "$contains": return isinstance(got, str) and all(norm_str(w) in norm_str(got) for w in arg) if op == "$math": v = safe_eval(got) if isinstance(got, str) else (float(got) if is_num(got) else None) return v is not None and num_eq(v, arg) if op == "$city": return isinstance(got, str) and norm_str(got.split(",")[0]) == norm_str(arg) if op == "$time": return isinstance(got, str) and norm_time(got) == norm_time(arg) raise ValueError(f"unknown matcher {op}") if isinstance(exp, bool) or isinstance(got, bool): return exp is got if is_num(exp): return is_num(got) and num_eq(float(got), float(exp)) if isinstance(exp, str): return isinstance(got, str) and norm_str(got) == norm_str(exp) if isinstance(exp, list): if not isinstance(got, list) or len(got) != len(exp): return False remaining = list(got) for e in exp: # order-insensitive hit = next((i for i, g in enumerate(remaining) if match_value(e, g)), None) if hit is None: return False remaining.pop(hit) return True if isinstance(exp, dict): return isinstance(got, dict) and _dict_status(exp, got) == "ok" return exp == got def _empty(v): return v is None or v == "" or v == [] or v == {} def _dict_status(exp, got): """'ok' | 'wrong' (expected key missing/wrong) | 'extra' (unexpected non-empty key).""" for k, v in exp.items(): if k not in got or not match_value(v, got[k]): return "wrong" if any(k not in exp and not _empty(v) for k, v in got.items()): return "extra" return "ok" def call_status(exp_call, got_call, schema): """Compare one call with the right tool name. Returns 'ok' | 'wrong' | 'extra'.""" props = schema["function"]["parameters"]["properties"] args = got_call["arguments"] for k, v in exp_call["args"].items(): if k not in args: return "wrong" if isinstance(v, dict) and not next(iter(v), "").startswith("$"): st = _dict_status(v, args[k]) if isinstance(args[k], dict) else "wrong" if st != "ok": return st elif not match_value(v, args[k]): return "wrong" for k, v in args.items(): if k in exp_call["args"] or _empty(v): continue if k not in props: return "extra" # not in the schema at all if k in exp_call["allow_extra"]: continue if "default" in props[k] and match_value(props[k]["default"], v): continue return "extra" # optional arg the user never asked for, set to a non-default value return "ok" def _best_assignment(expected, got, schemas): """Pair each expected call with a distinct predicted call of the same name, preferring 'ok'. Returns list of statuses (one per expected call; 'missing' if no same-name call is left).""" rank = {"ok": 0, "extra": 1, "wrong": 2} best = None def rec(i, used, acc): nonlocal best if i == len(expected): key = tuple(rank.get(s, 3) for s in acc) if best is None or sum(key) < sum(best[0]): best = (key, list(acc)) return e = expected[i] options = [j for j, g in enumerate(got) if j not in used and g["name"] == e["name"]] if not options: rec(i + 1, used, acc + ["missing"]) for j in options: rec(i + 1, used | {j}, acc + [call_status(e, got[j], schemas[e["name"]])]) rec(0, frozenset(), []) return best[1] def score(task, calls, malformed, visible_text, truncated, schemas): """Returns (correct: bool, failure: str | None).""" expected = task["expected"] if truncated and not calls: return False, "truncated_by_cap" if not expected: if calls: return False, "called_when_not_needed" if not visible_text.strip(): return False, "malformed_output" if malformed else "skipped_needed_call" return True, None if not calls: return False, "malformed_output" if malformed else "skipped_needed_call" exp_names = [e["name"] for e in expected] if any(c["name"] not in exp_names for c in calls): return False, "wrong_tool" statuses = _best_assignment(expected, calls, schemas) if "missing" in statuses: return False, "malformed_output" if malformed else "skipped_needed_call" if len(calls) > len(expected): return False, "wrong_tool" # duplicate/extra call of a needed tool if "wrong" in statuses: return False, "wrong_or_missing_arg" if "extra" in statuses: return False, "hallucinated_arg" return True, None