Add eval set and recorded response loader
load_eval_set turns a set directory into an EvalSet; every load failure becomes an EvalSetError naming the file. RecordedResponses returns raw response text or None. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4a6e4ef2a8
commit
77097dd81c
2 files changed
+265
No files matched your search
@@ -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 ``<id>.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
|
||||
Reference in new issue
Block a user