Download testing/agent_evaluation/models.py from yuhanqin/ut-evaluation: direct link, hf CLI and curl.
- Browser
- Download file 18.7 kB
-
https://huggingface.co/datasets/yuhanqin/ut-evaluation/resolve/main/testing/agent_evaluation/models.py
- Command line
-
hf download hf://datasets/yuhanqin/ut-evaluation/testing/agent_evaluation/models.py
-
curl -L -o models.py https://huggingface.co/datasets/yuhanqin/ut-evaluation/resolve/main/testing/agent_evaluation/models.py
18.7 kB
| """Dataset-agnostic domain objects shared by the evaluation runtime.""" | |
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| from dataclasses import dataclass, field, fields, is_dataclass | |
| from pathlib import Path | |
| from types import MappingProxyType | |
| from collections.abc import Mapping, Sequence | |
| from typing import Any, TYPE_CHECKING | |
| if TYPE_CHECKING: | |
| from .evaluators.contracts import EvaluatorResult | |
| # Domain identity and result fields have dedicated attributes on | |
| # ``EvaluatorResult``/``ScoreRecord``. Keeping the reservation in one leaf | |
| # module lets every boundary discard stale carrier-shaped copies uniformly. | |
| STRUCTURED_METADATA_FIELDS = frozenset({ | |
| "evaluator_id", "family", "engine", "result_kind", "scope", | |
| "evaluator_version", "testpoint_id", "metric", "unit", "value", | |
| "status", "score", "label", "explanation", "evidence_refs", | |
| }) | |
| def deep_freeze(value: Any) -> Any: | |
| """Recursively normalize domain values to immutable containers.""" | |
| if isinstance(value, Mapping): | |
| return MappingProxyType({key: deep_freeze(item) for key, item in value.items()}) | |
| if isinstance(value, (list, tuple)): | |
| return tuple(deep_freeze(item) for item in value) | |
| if isinstance(value, (set, frozenset)): | |
| return frozenset(deep_freeze(item) for item in value) | |
| return value | |
| def deep_thaw(value: Any) -> Any: | |
| """Return JSON-friendly mutable containers at an adapter boundary.""" | |
| if isinstance(value, Mapping): | |
| return {key: deep_thaw(item) for key, item in value.items()} | |
| if isinstance(value, (list, tuple, set, frozenset)): | |
| return [deep_thaw(item) for item in value] | |
| if is_dataclass(value): | |
| return {item.name: deep_thaw(getattr(value, item.name)) for item in fields(value)} | |
| return value | |
| def _json(value: Any) -> Any: | |
| if is_dataclass(value): | |
| return {item.name: _json(getattr(value, item.name)) for item in fields(value)} | |
| if hasattr(value, "to_dict"): | |
| return value.to_dict() | |
| if hasattr(value, "as_dict"): | |
| return value.as_dict() | |
| if isinstance(value, Path): | |
| return value.as_posix() | |
| if isinstance(value, (list, tuple)): | |
| return [_json(item) for item in value] | |
| if isinstance(value, Mapping): | |
| return {str(key): _json(item) for key, item in value.items()} | |
| return value | |
| def _decode_artifact_refs(value: Any) -> list[str]: | |
| if value is None: | |
| return [] | |
| if not isinstance(value, (list, tuple)): | |
| raise TypeError("task artifact artifact_refs must be a list") | |
| if any(not isinstance(item, str) or not item for item in value): | |
| raise ValueError("task artifact artifact_refs must contain non-empty strings") | |
| return list(value) | |
| def _decode_metadata(value: Any) -> dict[str, Any]: | |
| if value is None: | |
| return {} | |
| if not isinstance(value, Mapping): | |
| raise TypeError("task artifact metadata must be an object") | |
| return dict(value) | |
| def stable_hash(data: bytes) -> str: | |
| return hashlib.sha256(data).hexdigest() | |
| class SkillReference: | |
| skill_id: str | |
| version: str | |
| entrypoint: str | |
| entrypoint_hash: str | |
| bundle_hash: str | |
| def to_dict(self) -> dict[str, Any]: | |
| return _json(self) | |
| class SkillBundle(SkillReference): | |
| """Loaded skill content made available to task adapters.""" | |
| content: str = "" | |
| root: str = "" | |
| def load(cls, path: str | Path, version: str = "working") -> "SkillBundle": | |
| entrypoint = Path(path).resolve() | |
| if entrypoint.is_dir(): | |
| entrypoint = entrypoint / "SKILL.md" | |
| if not entrypoint.is_file(): | |
| raise FileNotFoundError(f"Skill entrypoint does not exist: {entrypoint}") | |
| content = entrypoint.read_text(encoding="utf-8") | |
| skill_id = entrypoint.parent.name | |
| for line in content.splitlines(): | |
| if line.startswith("name:"): | |
| skill_id = line.split(":", 1)[1].strip() or skill_id | |
| break | |
| root = entrypoint.parent | |
| digest = hashlib.sha256() | |
| files = sorted( | |
| file_path for file_path in root.rglob("*") | |
| if file_path.is_file() | |
| and not any(part.startswith(".") or part == "__pycache__" for part in file_path.relative_to(root).parts) | |
| and file_path.suffix != ".pyc" | |
| and file_path.relative_to(root).as_posix() != "skill.yaml" | |
| ) | |
| for file_path in files: | |
| relative = file_path.relative_to(root).as_posix().encode("utf-8") | |
| data = file_path.read_bytes() | |
| digest.update(len(relative).to_bytes(8, "big")); digest.update(relative) | |
| digest.update(len(data).to_bytes(8, "big")); digest.update(data) | |
| return cls(skill_id, version, entrypoint.as_posix(), stable_hash(entrypoint.read_bytes()), digest.hexdigest(), content, root.as_posix()) | |
| def ref_dict(self) -> dict[str, Any]: | |
| return {"skill_id": self.skill_id, "version": self.version, "entrypoint": self.entrypoint, | |
| "entrypoint_hash": self.entrypoint_hash, "bundle_hash": self.bundle_hash} | |
| def to_dict(self) -> dict[str, Any]: | |
| return _json(self) | |
| class TaskArtifact: | |
| run_id: str | |
| case_id: str | |
| status: str | |
| output: Any | |
| artifact_refs: list[str] = field(default_factory=list) | |
| metadata: dict[str, Any] = field(default_factory=dict) | |
| execution: "ExecutionEvidence | None" = None | |
| trace_ref: "TraceRef | None" = None | |
| def __post_init__(self) -> None: | |
| object.__setattr__(self, "output", deep_freeze(self.output)) | |
| object.__setattr__(self, "artifact_refs", tuple(str(item) for item in self.artifact_refs)) | |
| object.__setattr__(self, "metadata", deep_freeze(self.metadata)) | |
| def to_dict(self) -> dict[str, Any]: | |
| return _json(self) | |
| def from_dict(cls, value: "TaskArtifact | Mapping[str, Any]") -> "TaskArtifact": | |
| """Decode the typed task result carried through experiment backends.""" | |
| if isinstance(value, cls): | |
| return value | |
| if not isinstance(value, Mapping): | |
| raise TypeError("task artifact must be a TaskArtifact or object") | |
| allowed_keys = { | |
| "run_id", "case_id", "status", "output", "artifact_refs", | |
| "metadata", "execution", "trace_ref", | |
| } | |
| unknown_keys = set(value) - allowed_keys | |
| if unknown_keys: | |
| raise ValueError(f"task artifact contains unknown fields: {sorted(unknown_keys)}") | |
| execution_value = value.get("execution") | |
| if isinstance(execution_value, ExecutionEvidence): | |
| execution = execution_value | |
| elif isinstance(execution_value, Mapping): | |
| execution = ExecutionEvidence(**dict(execution_value)) | |
| elif execution_value is None: | |
| execution = None | |
| else: | |
| raise TypeError("task artifact execution must be an object or null") | |
| trace_value = value.get("trace_ref") | |
| if isinstance(trace_value, TraceRef): | |
| trace_ref = trace_value | |
| elif isinstance(trace_value, Mapping): | |
| project = trace_value.get("project") | |
| session_id = trace_value.get("session_id") | |
| if not isinstance(project, str) or not project.strip() or not isinstance(session_id, str) or not session_id.strip(): | |
| raise ValueError("task artifact trace_ref requires non-empty project and session_id") | |
| trace_ref = TraceRef(project=project, session_id=session_id) | |
| elif trace_value is None: | |
| trace_ref = None | |
| else: | |
| raise TypeError("task artifact trace_ref must be an object or null") | |
| return cls( | |
| run_id=str(value.get("run_id", "unknown")), | |
| case_id=str(value.get("case_id", "unknown")), | |
| status=str(value.get("status", "failed")), | |
| output=value.get("output"), | |
| artifact_refs=_decode_artifact_refs(value.get("artifact_refs", [])), | |
| metadata=_decode_metadata(value.get("metadata", {})), | |
| execution=execution, | |
| trace_ref=trace_ref, | |
| ) | |
| class ExecutionEvidence: | |
| """Facts observed by an execution adapter, independent of storage backend.""" | |
| final_output: str = "" | |
| tool_calls: list[dict[str, Any]] = field(default_factory=list) | |
| validation: list[dict[str, Any]] = field(default_factory=list) | |
| changed_files: list[str] = field(default_factory=list) | |
| duration_seconds: float | None = None | |
| task_workspace: str | None = None | |
| returncode: int | None = None | |
| def __post_init__(self) -> None: | |
| for name in ("tool_calls", "validation", "changed_files"): | |
| value = getattr(self, name) | |
| if value is not None: | |
| object.__setattr__(self, name, deep_freeze(value)) | |
| def to_dict(self) -> dict[str, Any]: | |
| return _json(self) | |
| class TraceRef: | |
| """The minimum reference needed by a post-run trace reader.""" | |
| project: str | |
| session_id: str | |
| def to_dict(self) -> dict[str, Any]: | |
| return _json(self) | |
| class TestPoint: | |
| test_point_id: str | |
| kind: str | |
| ordinal: int | |
| name: str | |
| previous_test_point_id: str | None | |
| requirement: str | |
| weight: float = 1.0 | |
| def to_dict(self) -> dict[str, Any]: | |
| return _json(self) | |
| class TestPointSet: | |
| skill_id: str | |
| skill_version: str | |
| skill_bundle_hash: str | |
| compiler_version: str | |
| test_points: list[TestPoint] | |
| set_hash: str = "" | |
| def __post_init__(self) -> None: | |
| object.__setattr__(self, "test_points", tuple(self.test_points)) | |
| if self.set_hash: | |
| return | |
| payload = json.dumps({ | |
| "skill_id": self.skill_id, | |
| "skill_version": self.skill_version, | |
| "skill_bundle_hash": self.skill_bundle_hash, | |
| "compiler_version": self.compiler_version, | |
| "test_points": [point.to_dict() for point in self.test_points], | |
| }, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode() | |
| object.__setattr__(self, "set_hash", stable_hash(payload)) | |
| def to_dict(self) -> dict[str, Any]: | |
| return _json(self) | |
| class ScoreIdentity: | |
| run_id: str | |
| case_id: str | |
| evaluator_id: str | |
| family: str | |
| engine: str | |
| scope: str | |
| evaluator_version: str | |
| testpoint_id: str | None = None | |
| def to_dict(self) -> dict[str, Any]: | |
| return _json(self) | |
| class ScoreRecord: | |
| """Canonical audit record of one typed evaluator result. | |
| The constructor deliberately mirrors the domain shape: identity and the | |
| tagged result are stored once, with backend provenance kept separately. | |
| Flat artifact fields are read-only projections below. | |
| """ | |
| score_id: str | |
| identity: ScoreIdentity | |
| result: "EvaluatorResult" | |
| provenance: Mapping[str, Any] = field(default_factory=dict) | |
| def __post_init__(self) -> None: | |
| if not isinstance(self.identity, ScoreIdentity): | |
| raise TypeError("ScoreRecord identity must be ScoreIdentity") | |
| from .evaluators.contracts import EvaluatorResult | |
| if not isinstance(self.result, EvaluatorResult): | |
| raise TypeError("ScoreRecord result must be an EvaluatorResult") | |
| object.__setattr__(self, "provenance", deep_freeze(self.provenance)) | |
| def from_dict(cls, value: Mapping[str, Any]) -> ScoreRecord: | |
| """Restore the flat audit format through the normal domain validators.""" | |
| from .evaluators.contracts import evaluator_result | |
| identity = ScoreIdentity(**{f.name: value[f.name] for f in fields(ScoreIdentity)}) | |
| result = evaluator_result(**{name: value[name] for name in ( | |
| "score", "label", "explanation", "status", "result_kind", "value", "metric", "unit", "evidence_refs", | |
| )}) | |
| return cls(value["score_id"], identity, result, value["metadata"]) | |
| def run_id(self) -> str: return self.identity.run_id | |
| def case_id(self) -> str: return self.identity.case_id | |
| def evaluator_id(self) -> str: return self.identity.evaluator_id | |
| def engine(self) -> str: return self.identity.engine | |
| def family(self) -> str: return self.identity.family | |
| def scope(self) -> str: return self.identity.scope | |
| def evaluator_version(self) -> str: return self.identity.evaluator_version | |
| def testpoint_id(self) -> str | None: return self.identity.testpoint_id | |
| def score(self) -> float | None: return getattr(self.result, "score", None) | |
| def label(self) -> str: | |
| # Measurements intentionally have no semantic label field. Emit the | |
| # conventional carrier label only at the flat projection boundary. | |
| if self.result_kind == "measurement": | |
| return "measurement" | |
| return getattr(self.result, "label", "") | |
| def status(self) -> str: return str(self.result.status) | |
| def explanation(self) -> str: return self.result.explanation | |
| def evidence_refs(self) -> tuple[str, ...]: return self.result.evidence_refs | |
| def result_kind(self) -> str: return str(self.result.result_kind) | |
| def value(self) -> Any: return getattr(self.result, "value", None) | |
| def metric(self) -> str | None: return getattr(self.result, "metric", None) | |
| def unit(self) -> str | None: return getattr(self.result, "unit", None) | |
| def metadata(self) -> Mapping[str, Any]: return self.provenance | |
| def source(self) -> str: | |
| return str(self.provenance.get("source", "experiment")) | |
| def to_dict(self) -> dict[str, Any]: | |
| # Keep the on-disk shape flat and stable even though memory is nested. | |
| return { | |
| "score_id": self.score_id, "run_id": self.run_id, | |
| "case_id": self.case_id, "evaluator_id": self.evaluator_id, | |
| "engine": self.engine, "family": self.family, "scope": self.scope, | |
| "evaluator_version": self.evaluator_version, | |
| "testpoint_id": self.testpoint_id, "result_kind": self.result_kind, | |
| "status": self.status, "score": self.score, "label": self.label, | |
| "explanation": self.explanation, "evidence_refs": list(self.evidence_refs), | |
| "value": deep_thaw(self.value), "metric": self.metric, "unit": self.unit, | |
| "metadata": deep_thaw(self.provenance), | |
| } | |
| def score_statistics(scores: Sequence[ScoreRecord]) -> dict[str, Any]: | |
| """Shared domain counts; missing assessment evidence stays in the denominator.""" | |
| assessments = [s for s in scores if s.result_kind == "assessment"] | |
| diagnostics = [s for s in scores if s.result_kind == "diagnostic"] | |
| return { | |
| "score_count": len(scores), | |
| "assessment_count": len(assessments), | |
| "measurement_count": sum(s.result_kind == "measurement" for s in scores), | |
| "diagnostic_count": len(diagnostics), | |
| "diagnosed_count": sum(s.label == "diagnosed" for s in diagnostics), | |
| "diagnostic_not_selected_count": sum(s.label == "not_selected" for s in diagnostics), | |
| "diagnostic_incomplete_count": sum(s.label == "incomplete" for s in diagnostics), | |
| "diagnostic_error_count": sum(s.label == "error" or s.status == "error" for s in diagnostics), | |
| "execution_score_count": sum(s.family == "execution" for s in scores), | |
| "trace_score_count": sum(s.family == "trace" for s in scores), | |
| "generic_evaluator_count": len({s.evaluator_id for s in scores if s.scope == "generic"}), | |
| "skill_evaluator_count": len({s.evaluator_id for s in scores if s.scope == "skill"}), | |
| "pass_rate": sum(s.status == "success" and s.score == 1 for s in assessments) / len(assessments) if assessments else 0.0, | |
| "failed_count": sum(s.status == "success" and s.score == 0 for s in assessments), | |
| "incomplete_count": sum(s.status in {"incomplete", "unavailable", "error"} for s in assessments), | |
| } | |
| class BackendRunResult: | |
| """Backend-neutral outcome returned by ``ExperimentBackend.run``.""" | |
| backend_name: str | |
| experiment_id: str | |
| runs: tuple[TaskArtifact, ...] = () | |
| scores: tuple[ScoreRecord, ...] = () | |
| run_count: int = 0 | |
| evaluation_count: int = 0 | |
| failed_evaluation_count: int = 0 | |
| published_result_count: int = 0 | |
| metadata: Mapping[str, Any] = field(default_factory=dict) | |
| def __post_init__(self) -> None: | |
| if not self.backend_name or not self.experiment_id: | |
| raise ValueError("backend result requires backend_name and experiment_id") | |
| for field_name in ( | |
| "run_count", | |
| "evaluation_count", | |
| "failed_evaluation_count", | |
| "published_result_count", | |
| ): | |
| value = getattr(self, field_name) | |
| if isinstance(value, bool) or not isinstance(value, int) or value < 0: | |
| raise ValueError(f"backend result {field_name} must be a non-negative integer") | |
| object.__setattr__(self, "runs", tuple(self.runs)) | |
| object.__setattr__(self, "scores", tuple(self.scores)) | |
| object.__setattr__(self, "metadata", deep_freeze(self.metadata)) | |
| class FeedbackRecord: | |
| feedback_id: str | |
| run_id: str | |
| case_id: str | |
| evaluator_id: str | |
| failure_type: str | |
| root_cause: str | |
| explanation: str | |
| evidence_refs: list[str] | |
| suggested_change: str | None = None | |
| def __post_init__(self) -> None: | |
| object.__setattr__(self, "evidence_refs", tuple(str(item) for item in self.evidence_refs)) | |
| def to_dict(self) -> dict[str, Any]: | |
| return _json(self) | |
| def write_jsonl(path: str | Path, rows: list[Any]) -> None: | |
| target = Path(path) | |
| target.parent.mkdir(parents=True, exist_ok=True) | |
| def record(row: Any) -> Any: | |
| # Domain records own their public artifact shape. In particular, | |
| # ScoreRecord deliberately stores identity/result/provenance as a | |
| # nested in-memory model but exposes a stable flat JSONL record. | |
| to_dict = getattr(row, "to_dict", None) | |
| return to_dict() if callable(to_dict) else _json(row) | |
| target.write_text( | |
| "".join( | |
| json.dumps(record(row), ensure_ascii=False, sort_keys=True) + "\n" | |
| for row in rows | |
| ), | |
| encoding="utf-8", | |
| ) | |