File size: 4,897 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
"""Markdown and JSON reporting for evaluation runs."""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any, Mapping, Sequence

from .grade import summarize
from .schema import CaseResult

_METRIC_LABELS = (
    ("score", "Overall"),
    ("correct_call_when_expected", "Correct call when a tool applies"),
    ("correct_abstention", "Correct abstention when no tool applies"),
    ("spurious_call_rate", "Spurious-call rate (lower is better)"),
    ("name_accuracy", "Tool selected correctly"),
    ("args_accuracy", "Arguments exactly correct"),
    ("answer_constraint_accuracy", "Answer constraints satisfied"),
    ("malformed_rate", "Malformed output rate"),
)


def percent(value: float) -> str:
    return f"{value * 100:.1f}%"


def _metric_rows(summary: Mapping[str, Any]) -> list[str]:
    rows = ["| Metric | Score |", "|---|---|"]
    for key, label in _METRIC_LABELS:
        if key in summary:
            rows.append(f"| {label} | {percent(summary[key])} |")
    interval = summary.get("score_ci95")
    if interval:
        rows.append(f"| Overall 95% CI (Wilson) | {percent(interval[0])} – {percent(interval[1])} |")
    return rows


def _breakdown(title: str, groups: Mapping[str, Mapping[str, Any]]) -> list[str]:
    rows = [f"### {title}", "", "| Group | Cases | Score | Correct call | Abstention | Spurious calls |", "|---|---|---|---|---|---|"]
    for name, group in groups.items():
        rows.append(
            f"| {name} | {group['cases']} | {percent(group['score'])} | "
            f"{percent(group['correct_call_when_expected'])} | {percent(group['correct_abstention'])} | "
            f"{percent(group['spurious_call_rate'])} |"
        )
    rows.append("")
    return rows


def render_markdown(summary: Mapping[str, Any], report: Mapping[str, Any] | None = None) -> str:
    overall = summary["overall"]
    lines = [
        f"# ToolUse.1 — {summary.get('model') or 'unnamed model'}",
        "",
        f"- Protocol: **{summary.get('protocol')}**",
        f"- Cases scored: **{summary.get('n_cases')}**",
        "",
        "## Summary",
        "",
        *_metric_rows(overall),
        "",
    ]
    for key, title in (
        ("by_protocol", "By protocol"),
        ("by_language", "By language"),
        ("by_category", "By category"),
        ("by_difficulty", "By difficulty"),
    ):
        groups = summary.get(key) or {}
        if groups:
            lines.extend(_breakdown(title, groups))
    if report is not None:
        lines.extend(_failure_section(report))
    return "\n".join(lines).rstrip() + "\n"


def _failure_section(report: Mapping[str, Any], limit: int = 40) -> list[str]:
    failures = report.get("failures") or []
    if not failures:
        return []
    lines = ["### Failing cases", "", "| Case | Protocol | Expected | Predicted |", "|---|---|---|---|"]
    for item in failures[:limit]:
        predicted = str(item.get("detail") or item.get("output") or "").replace("|", "\\|").replace("\n", " ")
        lines.append(
            f"| {item.get('case_id')} | {item.get('protocol')} | "
            f"{'call' if item.get('expected_call') else 'no call'} | {predicted[:180]} |"
        )
    if len(failures) > limit:
        lines.append("")
        lines.append(f"_{len(failures) - limit} further failures omitted; see the raw results file._")
    lines.append("")
    return lines


def build_report(results: Sequence[CaseResult], model_id: str = "", protocol: str | None = None) -> dict[str, Any]:
    summary = summarize(results, model_id=model_id, protocol=protocol)  # type: ignore[arg-type]
    failures = [result.to_dict() for result in results if not result.passed]
    return {"summary": summary, "results": [result.to_dict() for result in results], "failures": failures}


def write_report(report: Mapping[str, Any], directory: Path, stem: str) -> dict[str, Path]:
    directory.mkdir(parents=True, exist_ok=True)
    json_path = directory / f"{stem}.json"
    markdown_path = directory / f"{stem}.md"
    json_path.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
    markdown_path.write_text(render_markdown(report["summary"], report), encoding="utf-8")
    return {"json": json_path, "markdown": markdown_path}


def leaderboard_row(report: Mapping[str, Any], model_id: str, link: str = "", protocol: str = "all", notes: str = "") -> dict[str, Any]:
    overall = report["summary"]["overall"]
    return {
        "model": model_id,
        "link": link,
        "protocol": protocol,
        "score": overall["score"],
        "score_ci95": overall["score_ci95"],
        "correct_call": overall["correct_call_when_expected"],
        "abstention": overall["correct_abstention"],
        "spurious_call_rate": overall["spurious_call_rate"],
        "n_cases": report["summary"]["n_cases"],
        "notes": notes,
    }