File size: 7,849 Bytes
2b42456
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
"""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"),
    }