"""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)