diff --git a/src/chemenu/evals/loader.py b/src/chemenu/evals/loader.py new file mode 100644 index 0000000..ecec050 --- /dev/null +++ b/src/chemenu/evals/loader.py @@ -0,0 +1,120 @@ +"""Load eval sets and recorded responses from disk.""" + +import importlib +import re +from pathlib import Path +from typing import Any, cast + +import yaml +from pydantic import BaseModel, ValidationError + +from chemenu.evals.graders import describe_validation_error +from chemenu.evals.model import EvalCase, EvalSet, ResponseError, SetSpec + + +class EvalSetError(Exception): + """An eval set cannot be loaded; the message names the cause and file.""" + + +class _Loader(yaml.SafeLoader): + """SafeLoader that knows only the YAML 1.2 booleans. + + ``yes``, ``no``, ``on`` and ``off`` stay strings. + """ + + +_BOOL_TAG = "tag:yaml.org,2002:bool" +_BOOL_12 = re.compile(r"^(?:true|True|TRUE|false|False|FALSE)$") +_resolvers: dict[str, list[tuple[str, re.Pattern[str]]]] = { + first: [(tag, regexp) for tag, regexp in entries if tag != _BOOL_TAG] + for first, entries in yaml.SafeLoader.yaml_implicit_resolvers.items() +} +for _first in "tTfF": + _resolvers.setdefault(_first, []).append((_BOOL_TAG, _BOOL_12)) +_Loader.yaml_implicit_resolvers = _resolvers + + +def _read_yaml(path: Path) -> dict[str, Any]: + try: + text = path.read_text(encoding="utf-8-sig") + except FileNotFoundError: + raise EvalSetError(f"{path}: file is missing") from None + except (OSError, UnicodeDecodeError) as exc: + raise EvalSetError(f"{path}: cannot read file: {exc}") from exc + try: + data: object = yaml.load(text, Loader=_Loader) # noqa: S506 # _Loader extends SafeLoader + except yaml.YAMLError as exc: + raise EvalSetError(f"{path}: invalid YAML: {' '.join(str(exc).split())}") from exc + if not isinstance(data, dict): + raise EvalSetError(f"{path}: content must be a mapping") + return cast("dict[str, Any]", data) + + +def _resolve_output_model(spec: str, path: Path) -> type[BaseModel]: + module_name, sep, class_name = spec.partition(":") + if not sep or not module_name or not class_name: + raise EvalSetError(f"{path}: output_model {spec!r} must have the form 'module:Class'") + try: + module = importlib.import_module(module_name) + except Exception as exc: + raise EvalSetError(f"{path}: output_model {spec!r}: cannot import module: {exc}") from exc + try: + model: object = getattr(module, class_name) + except AttributeError: + raise EvalSetError(f"{path}: output_model {spec!r}: class not found in module") from None + if not (isinstance(model, type) and issubclass(model, BaseModel)): + raise EvalSetError(f"{path}: output_model {spec!r} is not a subclass of pydantic.BaseModel") + return model + + +def load_eval_set(directory: Path) -> EvalSet: + spec_path = directory / "eval.yaml" + try: + spec = SetSpec.model_validate(_read_yaml(spec_path), strict=True) + except ValidationError as exc: + raise EvalSetError( + f"{spec_path}: invalid content: {describe_validation_error(exc)}" + ) from exc + output_model = _resolve_output_model(spec.output_model, spec_path) + + cases_dir = directory / "cases" + if not cases_dir.is_dir(): + raise EvalSetError(f"{cases_dir}: cases directory is missing") + cases: list[EvalCase] = [] + for stray in sorted(cases_dir.iterdir()): + if not stray.name.startswith(".") and stray.suffix != ".yaml": + raise EvalSetError(f"{stray}: case files must end in .yaml") + for case_path in sorted(cases_dir.glob("*.yaml"), key=lambda p: p.stem): + data = _read_yaml(case_path) + if "id" in data: + raise EvalSetError(f"{case_path}: invalid case: 'id' is the file name, not a field") + try: + cases.append(EvalCase.model_validate({"id": case_path.stem, **data}, strict=True)) + except ValidationError as exc: + raise EvalSetError( + f"{case_path}: invalid case: {describe_validation_error(exc)}" + ) from exc + if not cases: + raise EvalSetError(f"{cases_dir}: no cases found (empty set)") + return EvalSet( + name=spec.name, + threshold=spec.threshold, + output_model=output_model, + cases=tuple(cases), + ) + + +class RecordedResponses: + """Recorded raw model responses, one ``.json`` file per case.""" + + def __init__(self, directory: Path) -> None: + self._directory = directory + + def response_for(self, case_id: str) -> str | None: + path = self._directory / f"{case_id}.json" + try: + return path.read_text(encoding="utf-8-sig") + except FileNotFoundError: + return None + except (OSError, UnicodeDecodeError) as exc: + raise ResponseError(f"{path}: {exc}") from exc diff --git a/tests/evals/test_loader.py b/tests/evals/test_loader.py new file mode 100644 index 0000000..e9108b3 --- /dev/null +++ b/tests/evals/test_loader.py @@ -0,0 +1,145 @@ +from pathlib import Path + +import pytest + +from chemenu.evals.example import ExampleOutput +from chemenu.evals.loader import EvalSetError, RecordedResponses, load_eval_set +from chemenu.evals.model import ContainsCheck, EqualsCheck, ResponseError + +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"] +""" + + +def make_set(root: Path, eval_yaml: str = EVAL_YAML, cases: dict[str, str] | None = None) -> Path: + root.mkdir(parents=True, exist_ok=True) + (root / "eval.yaml").write_text(eval_yaml, encoding="utf-8") + (root / "cases").mkdir(exist_ok=True) + selected = cases if cases is not None else {"b": CASE_YAML, "a": CASE_YAML} + for stem, text in selected.items(): + (root / "cases" / f"{stem}.yaml").write_text(text, encoding="utf-8") + return root + + +def test_loads_cases_sorted_by_file_stem(tmp_path: Path) -> None: + root = make_set(tmp_path, cases={"b": CASE_YAML, "a": CASE_YAML, "c": CASE_YAML}) + eval_set = load_eval_set(root) + assert eval_set.name == "demo" + assert eval_set.threshold == 0.8 + assert eval_set.output_model is ExampleOutput + assert [case.id for case in eval_set.cases] == ["a", "b", "c"] + assert isinstance(eval_set.cases, tuple) + + +@pytest.mark.parametrize( + "output_model", + [ + "nocolon", + "no.such.module:X", + "chemenu.evals.example:Missing", + "pathlib:Path", + ], +) +def test_unknown_output_model_raises(tmp_path: Path, output_model: str) -> None: + eval_yaml = EVAL_YAML.replace("chemenu.evals.example:ExampleOutput", output_model) + with pytest.raises(EvalSetError, match="output_model"): + load_eval_set(make_set(tmp_path, eval_yaml)) + + +def test_empty_set_raises(tmp_path: Path) -> None: + with pytest.raises(EvalSetError, match="cases"): + load_eval_set(make_set(tmp_path, cases={})) + + +def test_missing_cases_dir_raises(tmp_path: Path) -> None: + (tmp_path / "eval.yaml").write_text(EVAL_YAML, encoding="utf-8") + with pytest.raises(EvalSetError, match="cases"): + load_eval_set(tmp_path) + + +def test_missing_eval_yaml_raises(tmp_path: Path) -> None: + with pytest.raises(EvalSetError, match=r"eval\.yaml"): + load_eval_set(tmp_path) + + +@pytest.mark.parametrize( + "bad", + [ + "input: [", + "- just\n- a list\n", + 'input: {}\nexpect: []\nid: "x"\n', + 'input: {}\nexpect: [{grader: "nope"}]\n', + ], +) +def test_invalid_case_raises(tmp_path: Path, bad: str) -> None: + root = make_set(tmp_path, cases={"bad": bad}) + with pytest.raises(EvalSetError, match=r"bad\.yaml") as info: + load_eval_set(root) + assert "\n" not in str(info.value).strip() + assert "errors.pydantic.dev" not in str(info.value) + + +def test_invalid_eval_yaml_raises(tmp_path: Path) -> None: + with pytest.raises(EvalSetError, match=r"eval\.yaml"): + load_eval_set(make_set(tmp_path / "one", 'name: "x"\n')) + with pytest.raises(EvalSetError, match=r"eval\.yaml"): + load_eval_set(make_set(tmp_path / "two", "a: [")) + + +def test_recorded_response_is_raw_text(tmp_path: Path) -> None: + raw = ' {"language": "de",\n "entities": ["รค"]} \n' + (tmp_path / "a.json").write_text(raw, encoding="utf-8") + assert RecordedResponses(tmp_path).response_for("a") == raw + + +def test_missing_recorded_response_is_none(tmp_path: Path) -> None: + assert RecordedResponses(tmp_path).response_for("a") is None + + +def test_recorded_response_strips_bom(tmp_path: Path) -> None: + (tmp_path / "a.json").write_bytes(b"\xef\xbb\xbf" + b'{"language": "de"}') + assert RecordedResponses(tmp_path).response_for("a") == '{"language": "de"}' + + +def test_unreadable_recorded_response_raises(tmp_path: Path) -> None: + (tmp_path / "a.json").write_bytes(b"\xff\xfe\x00{") + (tmp_path / "b.json").mkdir() + for case_id in ("a", "b"): + with pytest.raises(ResponseError, match=case_id): + RecordedResponses(tmp_path).response_for(case_id) + + +def test_non_yaml_file_in_cases_raises(tmp_path: Path) -> None: + root = make_set(tmp_path) + (root / "cases" / "x.yml").write_text(CASE_YAML, encoding="utf-8") + with pytest.raises(EvalSetError, match=r"x\.yml.*must end in \.yaml"): + load_eval_set(root) + + +def test_unquoted_no_stays_string(tmp_path: Path) -> None: + case = CASE_YAML.replace('value: "de"', "value: no").replace('items: ["a"]', "items: [yes, on]") + eval_set = load_eval_set(make_set(tmp_path, cases={"a": case})) + first, second = eval_set.cases[0].expect + assert isinstance(first, EqualsCheck) + assert first.value == "no" + assert isinstance(second, ContainsCheck) + assert second.items == ["yes", "on"] + case = CASE_YAML.replace('value: "de"', "value: true") + eval_set = load_eval_set(make_set(tmp_path / "t", cases={"a": case})) + first = eval_set.cases[0].expect[0] + assert isinstance(first, EqualsCheck) + assert first.value is True