Eval-Gerüst gegen aufgezeichnete Antworten #10
No files matched your search
@@ -10,6 +10,9 @@ dependencies = [
|
||||
"pyyaml>=6.0.4",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
chemenu-eval = "chemenu.evals.cli:main"
|
||||
|
||||
[build-system]
|
||||
requires = ["uv_build>=0.13.7,<0.14"]
|
||||
build-backend = "uv_build"
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Command line entry point: ``chemenu-eval <set>``."""
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
from collections.abc import Sequence
|
||||
from pathlib import Path
|
||||
|
||||
from chemenu.evals.loader import EvalSetError, RecordedResponses, load_eval_set
|
||||
from chemenu.evals.runner import format_report, run_eval_set
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
"""Exit code: 0 passed, 1 not passed, 2 set cannot be loaded or call is wrong."""
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="chemenu-eval",
|
||||
description="Score an eval set against its recorded responses.",
|
||||
)
|
||||
parser.add_argument("eval_set", help="directory of the eval set")
|
||||
args = parser.parse_args(argv)
|
||||
directory = Path(args.eval_set)
|
||||
try:
|
||||
eval_set = load_eval_set(directory)
|
||||
except EvalSetError as exc:
|
||||
print(f"chemenu-eval: {exc}", file=sys.stderr)
|
||||
return 2
|
||||
result = run_eval_set(eval_set, RecordedResponses(directory / "recorded"))
|
||||
print(format_report(result))
|
||||
return 0 if result.passed else 1
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Run an eval set and format the report."""
|
||||
|
||||
from chemenu.evals.graders import score_case
|
||||
from chemenu.evals.model import CaseResult, EvalSet, ResponseError, ResponseSource, SetResult
|
||||
|
||||
|
||||
def run_eval_set(eval_set: EvalSet, responses: ResponseSource) -> SetResult:
|
||||
"""Score every case, in case order."""
|
||||
cases: list[CaseResult] = []
|
||||
for case in eval_set.cases:
|
||||
try:
|
||||
raw = responses.response_for(case.id)
|
||||
except ResponseError as exc:
|
||||
cases.append(CaseResult(case.id, 0.0, False, (), f"cannot read response: {exc}"))
|
||||
continue
|
||||
cases.append(score_case(case, raw, eval_set.output_model, eval_set.threshold))
|
||||
return SetResult(eval_set.name, eval_set.threshold, tuple(cases))
|
||||
|
||||
|
||||
def _reason(case: CaseResult) -> str:
|
||||
if case.error is not None:
|
||||
reason = case.error
|
||||
else:
|
||||
reason = "; ".join(f"{c.label}: {c.detail}" for c in case.checks if not c.passed)
|
||||
# Validation messages span several lines; keep one report line per case.
|
||||
return " ".join(reason.split())
|
||||
|
||||
|
||||
def format_report(result: SetResult) -> str:
|
||||
"""One line per case, then a summary line."""
|
||||
lines: list[str] = []
|
||||
for case in result.cases:
|
||||
line = f"{'PASS' if case.passed else 'FAIL'} {case.case_id} {case.score:.2f}"
|
||||
reason = _reason(case)
|
||||
if reason:
|
||||
line += f" {reason}"
|
||||
lines.append(line)
|
||||
passed = sum(case.passed for case in result.cases)
|
||||
lines.append(
|
||||
f"{result.name}: {passed}/{len(result.cases)} passed, "
|
||||
f"mean {result.mean_score:.2f}, threshold {result.threshold}"
|
||||
)
|
||||
return "\n".join(lines)
|
||||
@@ -0,0 +1,98 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from chemenu.evals.cli import main
|
||||
|
||||
EVAL_YAML = """\
|
||||
name: "demo"
|
||||
threshold: 0.8
|
||||
output_model: "chemenu.evals.example:ExampleOutput"
|
||||
"""
|
||||
|
||||
CASE_YAML = """\
|
||||
input:
|
||||
text: "Hallo"
|
||||
expect:
|
||||
- grader: "equals"
|
||||
path: "/language"
|
||||
value: "de"
|
||||
- grader: "contains"
|
||||
path: "/entities"
|
||||
items: ["a"]
|
||||
"""
|
||||
|
||||
GOOD = '{"language": "de", "entities": ["a"]}'
|
||||
BAD = '{"language": "en", "entities": []}'
|
||||
|
||||
|
||||
def make_recorded(root: Path, data: dict[str, str]) -> Path:
|
||||
(root / "cases").mkdir(parents=True)
|
||||
(root / "eval.yaml").write_text(EVAL_YAML, encoding="utf-8")
|
||||
for stem in ("a", "b"):
|
||||
(root / "cases" / f"{stem}.yaml").write_text(CASE_YAML, encoding="utf-8")
|
||||
(root / "recorded").mkdir()
|
||||
for stem, text in data.items():
|
||||
(root / "recorded" / f"{stem}.json").write_text(text, encoding="utf-8")
|
||||
return root
|
||||
|
||||
|
||||
def test_exit_0_when_all_pass(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
|
||||
make_recorded(tmp_path, {"a": GOOD, "b": GOOD})
|
||||
assert main([str(tmp_path)]) == 0
|
||||
out = capsys.readouterr().out
|
||||
assert "PASS a 1.00" in out
|
||||
assert "demo: 2/2 passed, mean 1.00, threshold 0.8" in out
|
||||
|
||||
|
||||
def test_exit_1_below_threshold(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
|
||||
make_recorded(tmp_path, {"a": GOOD, "b": BAD})
|
||||
assert main([str(tmp_path)]) == 1
|
||||
assert "FAIL b 0.00" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_exit_1_on_missing_response(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
|
||||
make_recorded(tmp_path, {"a": GOOD})
|
||||
assert main([str(tmp_path)]) == 1
|
||||
assert "FAIL b 0.00 missing response" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_exit_2_on_load_error(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
|
||||
assert main([str(tmp_path)]) == 2
|
||||
captured = capsys.readouterr()
|
||||
assert captured.err.startswith("chemenu-eval: ")
|
||||
assert "eval.yaml" in captured.err
|
||||
assert captured.out == ""
|
||||
|
||||
|
||||
def test_exit_1_on_unreadable_response(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
|
||||
make_recorded(tmp_path, {"a": GOOD})
|
||||
(tmp_path / "recorded" / "b.json").write_bytes(b"\xff\xfe\x00{")
|
||||
assert main([str(tmp_path)]) == 1
|
||||
assert "FAIL b 0.00 cannot read response" in capsys.readouterr().out
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", ["{bad", '{"language": "de"}'])
|
||||
def test_exit_1_on_invalid_response(
|
||||
tmp_path: Path, capsys: pytest.CaptureFixture[str], raw: str
|
||||
) -> None:
|
||||
make_recorded(tmp_path, {"a": GOOD, "b": raw})
|
||||
assert main([str(tmp_path)]) == 1
|
||||
assert "FAIL b 0.00 invalid response" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_exit_2_on_unknown_output_model(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
|
||||
make_recorded(tmp_path, {})
|
||||
(tmp_path / "eval.yaml").write_text(
|
||||
EVAL_YAML.replace("ExampleOutput", "Missing"), encoding="utf-8"
|
||||
)
|
||||
assert main([str(tmp_path)]) == 2
|
||||
assert "output_model" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_exit_2_on_empty_set(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
|
||||
make_recorded(tmp_path, {})
|
||||
for case in (tmp_path / "cases").iterdir():
|
||||
case.unlink()
|
||||
assert main([str(tmp_path)]) == 2
|
||||
assert "no cases found" in capsys.readouterr().err
|
||||
@@ -0,0 +1,78 @@
|
||||
from pathlib import Path
|
||||
|
||||
from chemenu.evals.loader import load_eval_set
|
||||
from chemenu.evals.model import ResponseError
|
||||
from chemenu.evals.runner import format_report, run_eval_set
|
||||
|
||||
EVAL_YAML = """\
|
||||
name: "demo"
|
||||
threshold: 0.8
|
||||
output_model: "chemenu.evals.example:ExampleOutput"
|
||||
"""
|
||||
|
||||
CASE_YAML = """\
|
||||
input:
|
||||
text: "Hallo"
|
||||
expect:
|
||||
- grader: "equals"
|
||||
path: "/language"
|
||||
value: "de"
|
||||
- grader: "contains"
|
||||
path: "/entities"
|
||||
items: ["a"]
|
||||
"""
|
||||
|
||||
GOOD = '{"language": "de", "entities": ["a"]}'
|
||||
HALF = '{"language": "en", "entities": ["a"]}'
|
||||
|
||||
|
||||
def make_set(root: Path, cases: list[str]) -> Path:
|
||||
(root / "cases").mkdir(parents=True)
|
||||
(root / "eval.yaml").write_text(EVAL_YAML, encoding="utf-8")
|
||||
for stem in cases:
|
||||
(root / "cases" / f"{stem}.yaml").write_text(CASE_YAML, encoding="utf-8")
|
||||
return root
|
||||
|
||||
|
||||
class FakeResponses:
|
||||
def __init__(self, data: dict[str, str]) -> None:
|
||||
self._data = data
|
||||
|
||||
def response_for(self, case_id: str) -> str | None:
|
||||
return self._data.get(case_id)
|
||||
|
||||
|
||||
def test_scores_every_case(tmp_path: Path) -> None:
|
||||
eval_set = load_eval_set(make_set(tmp_path, ["b", "a"]))
|
||||
result = run_eval_set(eval_set, FakeResponses({"a": GOOD, "b": HALF}))
|
||||
assert result.name == "demo"
|
||||
assert result.threshold == 0.8
|
||||
assert [c.case_id for c in result.cases] == ["a", "b"]
|
||||
assert [c.score for c in result.cases] == [1.0, 0.5]
|
||||
assert not result.passed
|
||||
|
||||
|
||||
def test_report_lists_cases_and_total(tmp_path: Path) -> None:
|
||||
eval_set = load_eval_set(make_set(tmp_path, ["a", "b", "c"]))
|
||||
result = run_eval_set(eval_set, FakeResponses({"a": GOOD, "b": HALF, "c": "{bad"}))
|
||||
lines = format_report(result).splitlines()
|
||||
assert lines[0] == "PASS a 1.00"
|
||||
assert lines[1].startswith("FAIL b 0.50 equals /language: ")
|
||||
assert lines[2].startswith("FAIL c 0.00 invalid response: ")
|
||||
assert not result.passed
|
||||
assert lines[-1] == "demo: 1/3 passed, mean 0.50, threshold 0.8"
|
||||
assert len(lines) == 4
|
||||
assert all(line == line.rstrip() for line in lines)
|
||||
|
||||
|
||||
class _Unreadable:
|
||||
def response_for(self, case_id: str) -> str | None:
|
||||
raise ResponseError(f"{case_id}.json: boom")
|
||||
|
||||
|
||||
def test_unreadable_response_fails_case(tmp_path: Path) -> None:
|
||||
eval_set = load_eval_set(make_set(tmp_path, ["a"]))
|
||||
result = run_eval_set(eval_set, _Unreadable())
|
||||
assert not result.passed
|
||||
assert result.cases[0].error == "cannot read response: a.json: boom"
|
||||
assert result.cases[0].score == 0.0
|
||||
Reference in new issue
Block a user