"""Grading: canonical argument comparison and per-case verdicts.""" from __future__ import annotations import math import re from dataclasses import dataclass from typing import Any, Mapping, Sequence from .parse import answer_text, parse_output from .schema import Case, CaseResult, ExpectCall, ExpectNoCall, Protocol from .tools import REGISTRY, canonical_name @dataclass(frozen=True) class ArgMatch: ok: bool missing: tuple[str, ...] = () mismatched: tuple[str, ...] = () extra: tuple[str, ...] = () def describe(self) -> str: parts = [] if self.missing: parts.append("missing=" + ",".join(self.missing)) if self.mismatched: parts.append("mismatched=" + ",".join(self.mismatched)) if self.extra: parts.append("extra=" + ",".join(self.extra)) return "; ".join(parts) def _normalize(tool: str, key: str, value: Any) -> Any: spec = REGISTRY.get(canonical_name(tool)) if spec is None: return re.sub(r"\s+", " ", str(value)).strip().lower() normalizer = spec.normalizers.get(key) if normalizer is None: return re.sub(r"\s+", " ", str(value)).strip().lower() return normalizer(value) def _equal(left: Any, right: Any) -> bool: if isinstance(left, float) and isinstance(right, float): return math.isclose(left, right, rel_tol=1e-6, abs_tol=1e-6) if isinstance(left, (int, float)) and isinstance(right, (int, float)): return math.isclose(float(left), float(right), rel_tol=1e-6, abs_tol=1e-6) if isinstance(left, list) and isinstance(right, list): return len(left) == len(right) and all(_equal(a, b) for a, b in zip(left, right)) if isinstance(left, Mapping) and isinstance(right, Mapping): return set(left) == set(right) and all(_equal(left[k], right[k]) for k in left) return left == right def match_args(tool: str, expected: Mapping[str, Any], predicted: Mapping[str, Any]) -> ArgMatch: missing: list[str] = [] mismatched: list[str] = [] for key, value in expected.items(): if key not in predicted: missing.append(key) continue try: left = _normalize(tool, key, value) right = _normalize(tool, key, predicted[key]) except Exception: left, right = value, predicted[key] if not _equal(left, right): mismatched.append(key) spec = REGISTRY.get(canonical_name(tool)) allowed = set(spec.parameters) if spec else set(expected) extra = tuple(sorted(key for key in predicted if key not in expected and key not in allowed)) optional_extra = tuple(sorted(key for key in predicted if key not in expected and key in allowed)) return ArgMatch( ok=not missing and not mismatched, missing=tuple(missing), mismatched=tuple(mismatched), extra=extra + optional_extra, ) def _answer_matches(expect: ExpectNoCall, text: str) -> bool | None: if not expect.answer_contains_any and not expect.answer_contains_all: return None haystack = text.lower() if expect.answer_contains_all and not all(needle.lower() in haystack for needle in expect.answer_contains_all): return False if expect.answer_contains_any: return any(any(needle.lower() in haystack for needle in group) for group in expect.answer_contains_any) return True def grade_case(case: Case, protocol: Protocol, raw_output: str) -> CaseResult: parsed = parse_output(raw_output) calls = parsed.calls called = bool(calls) text = answer_text(raw_output) base = dict( case_id=case.id, protocol=protocol, lang=case.lang, category=case.category, difficulty=case.difficulty, malformed=parsed.malformed, output=raw_output, ) if isinstance(case.expect, ExpectCall): if len(calls) != 1: detail = "no call emitted" if not calls else f"{len(calls)} calls emitted (expected 1)" return CaseResult(passed=False, called=called, expected_call=True, name_correct=False, args_exact=False, answer_ok=None, detail=detail, **base) call = calls[0] name_correct = call.name == canonical_name(case.expect.name) args = match_args(case.expect.name, case.expect.args, call.args) if name_correct else ArgMatch(ok=False, mismatched=("name",)) detail = "" if (name_correct and args.ok) else f"predicted={call.canonical()}" + (f" ({args.describe()})" if args.describe() else "") return CaseResult( passed=bool(name_correct and args.ok), called=True, expected_call=True, name_correct=name_correct, args_exact=args.ok, answer_ok=None, detail=detail, **base, ) answer_ok = _answer_matches(case.expect, text) passed = not calls and answer_ok is not False detail = "" if calls: detail = "spurious call: " + "; ".join(c.canonical() for c in calls) elif answer_ok is False: detail = "answer failed constraint: " + text[:160] return CaseResult( passed=passed, called=called, expected_call=False, name_correct=not calls, args_exact=not calls, answer_ok=answer_ok, detail=detail, **base, ) def wilson_interval(successes: int, total: int, z: float = 1.96) -> tuple[float, float]: if total == 0: return (0.0, 0.0) phat = successes / total denominator = 1 + z * z / total center = (phat + z * z / (2 * total)) / denominator spread = z * math.sqrt(phat * (1 - phat) / total + z * z / (4 * total * total)) / denominator return (max(0.0, center - spread), min(1.0, center + spread)) def rate(numerator: int, denominator: int) -> float: return round(numerator / denominator, 4) if denominator else 0.0 def _group_summary(results: Sequence[CaseResult]) -> dict[str, Any]: positives = [r for r in results if r.expected_call] negatives = [r for r in results if not r.expected_call] answered = [r for r in negatives if r.answer_ok is not None] lo, hi = wilson_interval(sum(1 for r in results if r.passed), len(results)) return { "cases": len(results), "score": rate(sum(1 for r in results if r.passed), len(results)), "score_ci95": [round(lo, 4), round(hi, 4)], "correct_call_when_expected": rate(sum(1 for r in positives if r.passed), len(positives)), "correct_abstention": rate(sum(1 for r in negatives if r.passed), len(negatives)), "spurious_call_rate": rate(sum(1 for r in negatives if r.called), len(negatives)), "name_accuracy": rate(sum(1 for r in positives if r.name_correct), len(positives)), "args_accuracy": rate(sum(1 for r in positives if r.args_exact), len(positives)), "answer_constraint_accuracy": rate(sum(1 for r in answered if r.answer_ok), len(answered)), "malformed_rate": rate(sum(1 for r in results if r.malformed), len(results)), } def summarize(results: Sequence[CaseResult], model_id: str = "", protocol: Protocol | None = None) -> dict[str, Any]: def slice_by(key: str) -> dict[str, Any]: values: dict[str, list[CaseResult]] = {} for result in results: values.setdefault(getattr(result, key), []).append(result) return {name: _group_summary(group) for name, group in sorted(values.items())} return { "benchmark": "ToolUse.1", "model": model_id, "protocol": protocol or "all", "n_cases": len(results), "overall": _group_summary(results), "by_protocol": slice_by("protocol"), "by_language": slice_by("lang"), "by_category": slice_by("category"), "by_difficulty": slice_by("difficulty"), }