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>
90 lines
2.0 KiB
Python
90 lines
2.0 KiB
Python
"""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.
|
|
"""
|
|
...
|