Add eval types and hard graders

Pure grading of recorded responses: equals and contains checks over
JSON Pointers, strict output-model validation, score per case.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
torbenandClaude Sonnet 5.5 committed 2026-12-02 18:09:51 +01:00
1 parent c4e8f35858
commit 76f2fbbf06
6 files changed
+318

No files matched your search

+1
View File
@@ -0,0 +1 @@
"""Eval harness: scores recorded model responses against hard checks."""
+15
View File
@@ -0,0 +1,15 @@
"""Example output model for the example set ``evals/example``.
This is a placeholder until real step building blocks exist.
"""
from pydantic import BaseModel, ConfigDict
class ExampleOutput(BaseModel):
"""Example output model, not part of the real pipeline."""
model_config = ConfigDict(strict=True, extra="forbid", frozen=True)
language: str
entities: list[str]
+102
View File
@@ -0,0 +1,102 @@
"""Hard graders: pure functions over JSON values."""
from pydantic import BaseModel, JsonValue, ValidationError
from chemenu.evals.model import (
CaseResult,
Check,
CheckResult,
ContainsCheck,
EqualsCheck,
EvalCase,
)
class PointerError(LookupError):
"""A JSON Pointer does not resolve in the document."""
def resolve_pointer(doc: JsonValue, pointer: str) -> JsonValue:
"""Resolve an RFC 6901 JSON Pointer."""
if pointer == "":
return doc
if not pointer.startswith("/"):
raise PointerError(f"pointer must be empty or start with '/': {pointer!r}")
current = doc
for raw in pointer[1:].split("/"):
token = raw.replace("~1", "/").replace("~0", "~")
if isinstance(current, dict):
if token not in current:
raise PointerError(f"key {token!r} not found (pointer {pointer!r})")
current = current[token]
elif isinstance(current, list):
if not (token.isascii() and token.isdecimal()) or (len(token) > 1 and token[0] == "0"):
raise PointerError(f"invalid list index {token!r} (pointer {pointer!r})")
index = int(token)
if index >= len(current):
raise PointerError(f"index {index} out of range (pointer {pointer!r})")
current = current[index]
else:
raise PointerError(f"cannot descend into scalar at {token!r} (pointer {pointer!r})")
return current
def _json_equal(a: JsonValue, b: JsonValue) -> bool:
"""Compare JSON values; bool equals only bool, unlike Python's ``==``."""
if isinstance(a, bool) or isinstance(b, bool):
return isinstance(a, bool) and isinstance(b, bool) and a == b
if isinstance(a, dict) and isinstance(b, dict):
return a.keys() == b.keys() and all(_json_equal(v, b[k]) for k, v in a.items())
if isinstance(a, list) and isinstance(b, list):
return len(a) == len(b) and all(_json_equal(x, y) for x, y in zip(a, b, strict=True))
if isinstance(a, dict | list) or isinstance(b, dict | list):
return False
return a == b
def grade(check: Check, output: JsonValue) -> CheckResult:
"""Run one check against the output."""
label = f"{check.grader} {check.path}"
try:
actual = resolve_pointer(output, check.path)
except PointerError as exc:
return CheckResult(label, False, str(exc))
match check:
case EqualsCheck():
if _json_equal(actual, check.value):
return CheckResult(label, True, "")
return CheckResult(label, False, f"expected {check.value!r}, got {actual!r}")
case ContainsCheck():
if not isinstance(actual, list):
return CheckResult(label, False, f"value is not a list: {actual!r}")
missing = [i for i in check.items if not any(_json_equal(i, x) for x in actual)]
if missing:
return CheckResult(label, False, f"missing: {missing!r}")
return CheckResult(label, True, "")
def describe_validation_error(exc: ValidationError) -> str:
"""One line per validation error, joined; no documentation links."""
parts: list[str] = []
for error in exc.errors(include_url=False):
location = ".".join(str(part) for part in error["loc"])
parts.append(f"{location}: {error['msg']}" if location else error["msg"])
return "; ".join(parts)
def score_case(
case: EvalCase, raw: str | None, output_model: type[BaseModel], threshold: float
) -> CaseResult:
"""Score one case against its recorded response."""
if raw is None:
return CaseResult(case.id, 0.0, False, (), "missing response")
try:
output = output_model.model_validate_json(raw, strict=True)
except ValidationError as exc:
return CaseResult(
case.id, 0.0, False, (), f"invalid response: {describe_validation_error(exc)}"
)
dumped: JsonValue = output.model_dump(mode="json", by_alias=True)
results = tuple(grade(check, dumped) for check in case.expect)
score = sum(r.passed for r in results) / len(results) if results else 1.0
return CaseResult(case.id, score, score >= threshold, results, None)
+89
View File
@@ -0,0 +1,89 @@
"""Types of the eval harness."""
from dataclasses import dataclass
from typing import Annotated, Literal, Protocol
from pydantic import BaseModel, ConfigDict, Field, JsonValue
class _Spec(BaseModel):
model_config = ConfigDict(strict=True, extra="forbid", frozen=True)
class EqualsCheck(_Spec):
grader: Literal["equals"]
path: str # JSON Pointer, RFC 6901
value: JsonValue
class ContainsCheck(_Spec):
grader: Literal["contains"]
path: str # points to a list
items: list[JsonValue]
Check = Annotated[EqualsCheck | ContainsCheck, Field(discriminator="grader")]
class EvalCase(_Spec):
id: str # file stem, set by the loader
input: dict[str, JsonValue]
expect: list[Check]
class SetSpec(_Spec): # content of eval.yaml
name: str
threshold: float = Field(ge=0, le=1)
output_model: str # "module:Class"
@dataclass(frozen=True)
class EvalSet:
name: str
threshold: float
output_model: type[BaseModel]
cases: tuple[EvalCase, ...] # sorted by id, never empty
@dataclass(frozen=True)
class CheckResult:
label: str # e.g. "contains /entities"
passed: bool
detail: str
@dataclass(frozen=True)
class CaseResult:
case_id: str
score: float
passed: bool
checks: tuple[CheckResult, ...]
error: str | None # missing response, invalid JSON, schema
@dataclass(frozen=True)
class SetResult:
name: str
threshold: float
cases: tuple[CaseResult, ...]
@property
def passed(self) -> bool:
return all(case.passed for case in self.cases)
@property
def mean_score(self) -> float:
return sum(case.score for case in self.cases) / len(self.cases) if self.cases else 0.0
class ResponseError(Exception):
"""A recorded response exists but cannot be read."""
class ResponseSource(Protocol):
def response_for(self, case_id: str) -> str | None:
"""Return the raw response; ``None`` if none exists.
Raises ``ResponseError`` if a response exists but cannot be read.
"""
...