Eval-Gerüst gegen aufgezeichnete Antworten #10

Merged
torben merged 9 commits from 4-eval-harness into main 2026-12-02 18:40:45 +00:00
6 changed files with 318 additions and 0 deletions
Showing only changes of commit 76f2fbbf06 - Show all commits

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.
"""
...
+110
View File
@@ -0,0 +1,110 @@
"""Tests for the eval graders."""
import pytest
from pydantic import BaseModel, ConfigDict, Field, JsonValue
from chemenu.evals.example import ExampleOutput
from chemenu.evals.graders import PointerError, grade, resolve_pointer, score_case
from chemenu.evals.model import ContainsCheck, EqualsCheck, EvalCase
GOOD = '{"language": "de", "entities": ["a", "b"]}'
def _case(*expect: EqualsCheck | ContainsCheck) -> EvalCase:
return EvalCase(id="c", input={}, expect=list(expect))
def test_equals_passes_on_match() -> None:
out: JsonValue = {"language": "de"}
result = grade(EqualsCheck(grader="equals", path="/language", value="de"), out)
assert result.passed
assert result.label == "equals /language"
def test_contains_reports_missing_item() -> None:
out: JsonValue = {"entities": ["a"]}
result = grade(ContainsCheck(grader="contains", path="/entities", items=["a", "z"]), out)
assert not result.passed
assert "'z'" in result.detail
assert "'a'" not in result.detail
def test_unresolvable_pointer_fails_only_that_check() -> None:
case = _case(
EqualsCheck(grader="equals", path="/nope", value=1),
EqualsCheck(grader="equals", path="/language", value="de"),
)
result = score_case(case, GOOD, ExampleOutput, 0.0)
assert result.error is None
assert [c.passed for c in result.checks] == [False, True]
assert result.score == 0.5
def test_missing_response_scores_zero() -> None:
result = score_case(_case(), None, ExampleOutput, 0.0)
assert (result.score, result.passed, result.checks) == (0.0, False, ())
assert result.error
def test_invalid_json_scores_zero() -> None:
result = score_case(_case(), "not json", ExampleOutput, 0.0)
assert (result.score, result.passed) == (0.0, False)
assert result.error
def test_schema_violation_scores_zero() -> None:
result = score_case(_case(), '{"language": "de"}', ExampleOutput, 0.0)
assert (result.score, result.passed) == (0.0, False)
assert result.error == "invalid response: entities: Field required"
def test_strict_rejects_coercion() -> None:
result = score_case(_case(), '{"language": 1, "entities": []}', ExampleOutput, 0.0)
assert result.score == 0.0
assert result.error
def test_score_is_share_of_passed_checks() -> None:
case = _case(
EqualsCheck(grader="equals", path="/language", value="de"),
EqualsCheck(grader="equals", path="/language", value="en"),
ContainsCheck(grader="contains", path="/entities", items=["a"]),
ContainsCheck(grader="contains", path="/entities", items=["q"]),
)
result = score_case(case, GOOD, ExampleOutput, 0.5)
assert result.score == 0.5
assert result.passed
assert not score_case(case, GOOD, ExampleOutput, 0.6).passed
def test_resolve_pointer_rfc6901() -> None:
doc: JsonValue = {"a/b": {"m~n": [10, 20]}, "": 1}
assert resolve_pointer(doc, "") == doc
assert resolve_pointer(doc, "/a~1b/m~0n/1") == 20
assert resolve_pointer(doc, "/") == 1
for bad in ("/a~1b/m~0n/2", "/a~1b/m~0n/01", "x", "/a~1b/m~0n/0/z"):
with pytest.raises(PointerError):
resolve_pointer(doc, bad)
def test_bool_is_not_equal_to_int() -> None:
eq_one = EqualsCheck(grader="equals", path="/a", value=1)
assert not grade(eq_one, {"a": True}).passed
assert not grade(ContainsCheck(grader="contains", path="/a", items=[0]), {"a": [False]}).passed
nested = EqualsCheck(grader="equals", path="", value={"a": [1]})
assert not grade(nested, {"a": [True]}).passed
assert grade(nested, {"a": [1]}).passed
assert grade(eq_one, {"a": 1.0}).passed
class _Aliased(BaseModel):
model_config = ConfigDict(strict=True, extra="forbid", frozen=True)
entity_list: list[str] = Field(alias="entityList")
def test_pointer_uses_field_alias() -> None:
case = _case(ContainsCheck(grader="contains", path="/entityList", items=["a"]))
result = score_case(case, '{"entityList": ["a"]}', _Aliased, 1.0)
assert result.error is None
assert result.passed
+1
View File
@@ -13,6 +13,7 @@ import pytest
"chemenu.application",
"chemenu.ports",
"chemenu.adapters",
"chemenu.evals",
],
)
def test_module_imports(module_name: str) -> None: