Download testing/agent_evaluation/evaluators/runtime.py from yuhanqin/ut-evaluation: direct link, hf CLI and curl.
- Browser
- Download file 14.2 kB
-
https://huggingface.co/datasets/yuhanqin/ut-evaluation/resolve/main/testing/agent_evaluation/evaluators/runtime.py
- Command line
-
hf download hf://datasets/yuhanqin/ut-evaluation/testing/agent_evaluation/evaluators/runtime.py
-
curl -L -o runtime.py https://huggingface.co/datasets/yuhanqin/ut-evaluation/resolve/main/testing/agent_evaluation/evaluators/runtime.py
14.2 kB
| """Build and execute evaluators through one experiment-scoped runtime seam.""" | |
| from __future__ import annotations | |
| from dataclasses import dataclass, field, replace | |
| import uuid | |
| from typing import Any, Mapping | |
| from ..datasets.models import EvaluationCase | |
| from ..config import SkillEvaluationConfig | |
| from ..instrumentation import InstrumentationRuntime, build_instrumentation | |
| from ..models import (ScoreRecord, SkillBundle, TaskArtifact, TestPoint, | |
| TestPointSet, STRUCTURED_METADATA_FIELDS, deep_freeze, deep_thaw) | |
| from ..ports import LLMCompletionBackend, TraceStore | |
| from .contracts import ( | |
| EvaluationContext, EvaluatorDefinition, EvaluatorEngine, EvaluatorFamily, | |
| EvaluatorResult, Expansion, LLMJudgeRequest, ResultKind, ResultStatus, | |
| evaluator_result, incomplete_result, validate_evaluator_result, | |
| ) | |
| from .judge import LLMBackendResolver, LLMJudgeExecutor, _validate_judge | |
| class EvaluationServices: | |
| """Experiment-scoped services used while binding evaluator rules. | |
| The LLM dependency is resolved per evaluator at bind time. A single | |
| default backend may still be shared, while overrides remain local to the | |
| bound evaluator rather than leaking into every rule. | |
| """ | |
| trace_store: TraceStore | None = None | |
| llm_backend_resolver: LLMBackendResolver | None = None | |
| instrumentation: InstrumentationRuntime | None = None | |
| def resolve_backend( | |
| self, | |
| evaluator_id: str, | |
| runtime_config: Mapping[str, Any] | None = None, | |
| ) -> LLMCompletionBackend: | |
| if self.llm_backend_resolver is not None: | |
| return self.llm_backend_resolver.resolve(evaluator_id, runtime_config) | |
| raise ValueError("an LLM evaluator is configured but no LLM backend was provided") | |
| class BoundEvaluator: | |
| """Immutable evaluator with all dependencies bound at construction time.""" | |
| definition: EvaluatorDefinition | |
| params: Any | |
| skill: SkillBundle | |
| testpoint_set: TestPointSet | |
| services: EvaluationServices | |
| testpoint: TestPoint | None = None | |
| judge_executor: "LLMJudgeExecutor | None" = field(default=None, compare=False, repr=False) | |
| annotate: bool = False | |
| def evaluator_id(self) -> str: | |
| suffix = f":{self.testpoint.test_point_id}" if self.testpoint is not None else "" | |
| return f"{self.family}.{self.definition.evaluator_id}{suffix}" | |
| def family(self) -> EvaluatorFamily: | |
| return self.definition.family | |
| def engine(self) -> EvaluatorEngine: | |
| return self.definition.engine | |
| def result_kind(self) -> ResultKind: | |
| return self.definition.result_kind | |
| def metadata(self) -> Mapping[str, Any]: | |
| """Runtime dependency metadata, excluding the static evaluator contract.""" | |
| value: dict[str, Any] = {} | |
| if self.judge_executor is not None: | |
| value.update(self.judge_executor.metadata()) | |
| return deep_freeze(value) | |
| def evaluate( | |
| self, artifact: TaskArtifact, case: EvaluationCase | |
| ) -> EvaluatorResult: | |
| return _invoke_rule(self, artifact=artifact, case=case) | |
| def to_dict(self) -> dict[str, Any]: | |
| result = { | |
| "evaluator_id": self.evaluator_id, | |
| "engine": self.engine, | |
| "family": self.family, | |
| "result_kind": self.result_kind, | |
| "required_evidence": sorted(self.definition.required_evidence), | |
| "annotate": self.annotate, | |
| } | |
| result["params"] = self.params.to_dict() if hasattr(self.params, "to_dict") else deep_thaw(self.params) | |
| if self.testpoint is not None: | |
| result["testpoint"] = self.testpoint.to_dict() | |
| result.update({ | |
| "evaluator_version": self.definition.version, | |
| "scope": self.definition.scope, | |
| "expansion": self.definition.expansion, | |
| "aggregation": self.definition.aggregation, | |
| "direction": self.definition.direction, | |
| "metadata": deep_thaw(self.metadata), | |
| }) | |
| if self.definition.judge is not None: | |
| result["judge"] = self.definition.judge.to_dict() | |
| return result | |
| def score_record(result: EvaluatorResult, artifact: TaskArtifact, | |
| evaluator: BoundEvaluator) -> ScoreRecord: | |
| """Create the canonical record for persistence, feedback and artifacts.""" | |
| if not isinstance(result, EvaluatorResult): | |
| raise TypeError("score_record requires EvaluatorResult") | |
| if not isinstance(evaluator, BoundEvaluator): | |
| raise TypeError("score_record requires BoundEvaluator") | |
| validate_evaluator_result(result, evaluator.definition) | |
| metadata = { | |
| key: value | |
| for key, value in {**dict(evaluator.metadata), **dict(result.metadata or {})}.items() | |
| if key not in STRUCTURED_METADATA_FIELDS | |
| } | |
| metadata.setdefault("source", "experiment") | |
| from ..models import ScoreIdentity | |
| identity = ScoreIdentity( | |
| run_id=artifact.run_id, | |
| case_id=artifact.case_id, | |
| evaluator_id=evaluator.evaluator_id, | |
| family=str(evaluator.family), | |
| engine=str(evaluator.engine), | |
| scope=str(evaluator.definition.scope), | |
| evaluator_version=evaluator.definition.version, | |
| testpoint_id=evaluator.testpoint.test_point_id if evaluator.testpoint is not None else None, | |
| ) | |
| return ScoreRecord(f"score-{uuid.uuid4().hex[:12]}", identity, result, metadata) | |
| _EVENT_EVIDENCE = frozenset({ | |
| "testpoint_state", "event_timestamp", "event_span_owner", | |
| }) | |
| def _validate_params_schema(definition: EvaluatorDefinition, params: dict[str, Any]) -> None: | |
| if not definition.params_schema: | |
| return | |
| try: | |
| from jsonschema import Draft202012Validator | |
| except ImportError as exc: # pragma: no cover - shared dependency | |
| raise RuntimeError("evaluator params require jsonschema") from exc | |
| errors = sorted( | |
| Draft202012Validator(definition.params_schema).iter_errors(params), | |
| key=lambda error: list(error.path), | |
| ) | |
| if errors: | |
| error = errors[0] | |
| location = ".".join(str(item) for item in error.path) or "params" | |
| raise ValueError(f"{definition.evaluator_id}.{location}: {error.message}") | |
| def _missing_trace_result( | |
| definition: EvaluatorDefinition, | |
| params: Any, | |
| point: TestPoint | None, | |
| ) -> EvaluatorResult: | |
| explanation = "Persisted spans not found or TraceRef/TraceStore is missing" | |
| refs = ["trace_ref", "trace.subject.spans"] | |
| if definition.result_kind == ResultKind.MEASUREMENT: | |
| return evaluator_result( | |
| score=None, | |
| label="unavailable", | |
| explanation=explanation, | |
| evidence_refs=refs, | |
| status=ResultStatus.UNAVAILABLE.value, | |
| metadata={"attribution_status": "trace_missing"}, | |
| metric=definition.metric, | |
| unit=definition.unit, | |
| result_kind=ResultKind.MEASUREMENT, | |
| ) | |
| if definition.result_kind == ResultKind.DIAGNOSTIC: | |
| selection = { | |
| "testpoint_id": point.test_point_id if point is not None else None, | |
| "duration_seconds": None, | |
| "min_duration_seconds": getattr(params, "min_duration_seconds", None), | |
| "max_testpoints_per_case": getattr(params, "max_testpoints_per_case", None), | |
| "rank": None, | |
| "eligible": False, | |
| "selected": False, | |
| "reason": "trace_missing", | |
| } | |
| return evaluator_result( | |
| score=None, | |
| label="incomplete", | |
| explanation=explanation, | |
| evidence_refs=refs, | |
| status=ResultStatus.INCOMPLETE.value, | |
| metadata={ | |
| "selection": selection, | |
| "evidence_completeness": "insufficient", | |
| }, | |
| result_kind=ResultKind.DIAGNOSTIC, | |
| ) | |
| return incomplete_result(explanation, evidence_refs=refs) | |
| def _invoke_rule(evaluator: BoundEvaluator, *, artifact: TaskArtifact, | |
| case: EvaluationCase) -> EvaluatorResult: | |
| definition = evaluator.definition | |
| trace = None | |
| if definition.family == EvaluatorFamily.TRACE: | |
| if evaluator.services.trace_store is not None and artifact.trace_ref is not None: | |
| trace = evaluator.services.trace_store.read( | |
| artifact.trace_ref, | |
| instrumentation=evaluator.services.instrumentation, | |
| ) | |
| if trace is None: | |
| return _missing_trace_result(definition, evaluator.params, evaluator.testpoint) | |
| context = EvaluationContext( | |
| case=case, | |
| artifact=artifact, | |
| skill=evaluator.skill, | |
| testpoint_set=evaluator.testpoint_set, | |
| trace=trace, | |
| testpoint=evaluator.testpoint, | |
| ) | |
| result = definition.rule(context, evaluator.params) | |
| if definition.judge is not None: | |
| if isinstance(result, EvaluatorResult): | |
| return validate_evaluator_result(result, definition) | |
| if not isinstance(result, LLMJudgeRequest): | |
| raise TypeError("LLM evaluator rule must return EvaluatorResult or LLMJudgeRequest") | |
| if evaluator.judge_executor is None: # pragma: no cover - guarded while building | |
| raise ValueError("an LLM evaluator is configured but no LLM backend was provided") | |
| result = evaluator.judge_executor.evaluate(result) | |
| return validate_evaluator_result(result, definition) | |
| def _bind_evaluator( | |
| definition: EvaluatorDefinition, | |
| *, | |
| params: Any, | |
| point: TestPoint | None, | |
| services: EvaluationServices, | |
| runtime_config: Mapping[str, Any] | None, | |
| skill: SkillBundle, | |
| testpoint_set: TestPointSet, | |
| annotate: bool, | |
| ) -> BoundEvaluator: | |
| full_id = f"{definition.family}.{definition.evaluator_id}" | |
| if point is not None: | |
| full_id += f":{point.test_point_id}" | |
| judge_executor = None | |
| if definition.judge is not None: | |
| judge_executor = LLMJudgeExecutor( | |
| backend=services.resolve_backend(full_id, runtime_config), | |
| judge=definition.judge, | |
| result_kind=definition.result_kind, | |
| evaluator_version=definition.version, | |
| ) | |
| return BoundEvaluator( | |
| definition=definition, | |
| params=params, | |
| skill=skill, | |
| testpoint_set=testpoint_set, | |
| services=services, | |
| testpoint=point, | |
| judge_executor=judge_executor, | |
| annotate=annotate, | |
| ) | |
| def build_evaluators( | |
| *, | |
| skill: SkillBundle, | |
| profile: SkillEvaluationConfig, | |
| testpoint_set: TestPointSet, | |
| runtime: EvaluationServices | None = None, | |
| registry: Any = None, | |
| ) -> list[BoundEvaluator]: | |
| """Validate, expand, and bind the complete evaluator set.""" | |
| from .registry import DEFAULT_REGISTRY | |
| services = runtime or EvaluationServices() | |
| evaluator_registry = registry or DEFAULT_REGISTRY | |
| instrumentation = build_instrumentation( | |
| profile.instrumentation.protocol, | |
| profile.instrumentation.event_carriers, | |
| ) | |
| if services.instrumentation is not None and services.instrumentation != instrumentation: | |
| raise ValueError("evaluation services instrumentation does not match the profile") | |
| services = replace(services, instrumentation=instrumentation) | |
| evaluators: list[BoundEvaluator] = [] | |
| seen: set[str] = set() | |
| for family in (EvaluatorFamily.EXECUTION, EvaluatorFamily.TRACE): | |
| for entry in profile.evaluators_for(str(family)): | |
| definition = evaluator_registry.get(str(family), entry.evaluator_id) | |
| if definition is None: | |
| raise ValueError(f"unknown {family} evaluator: {entry.evaluator_id}") | |
| if definition.family != family: | |
| raise ValueError( | |
| f"{family}.{entry.evaluator_id} family does not match its registry definition " | |
| f"({definition.family})" | |
| ) | |
| _validate_judge(definition) | |
| params = deep_thaw(entry.params) | |
| _validate_params_schema(definition, params) | |
| if definition.normalize_params is not None: | |
| typed_params = definition.normalize_params(params) | |
| else: | |
| typed_params = definition.params_type(**params) | |
| if not isinstance(typed_params, definition.params_type): | |
| raise TypeError( | |
| f"{family}.{entry.evaluator_id} params normalizer must return " | |
| f"{definition.params_type.__name__}" | |
| ) | |
| if definition.judge is None and entry.llm is not None: | |
| raise ValueError(f"{family}.{entry.evaluator_id}.llm is only valid for LLM evaluators") | |
| if definition.judge is not None and services.llm_backend_resolver is None: | |
| raise ValueError( | |
| f"{family}.{entry.evaluator_id} uses the LLM engine but no LLM backend was provided" | |
| ) | |
| if definition.required_evidence & _EVENT_EVIDENCE and not instrumentation.readers: | |
| raise ValueError(f"{family}.{entry.evaluator_id} requires an eval-event carrier") | |
| points = testpoint_set.test_points if definition.expansion == Expansion.TESTPOINT else (None,) | |
| if definition.expansion == Expansion.TESTPOINT and not points: | |
| raise ValueError(f"{family}.{entry.evaluator_id} cannot expand an empty TestPointSet") | |
| for point in points: | |
| evaluator = _bind_evaluator( | |
| definition, | |
| params=typed_params, | |
| point=point, | |
| services=services, | |
| runtime_config=entry.llm, | |
| skill=skill, | |
| testpoint_set=testpoint_set, | |
| annotate=entry.annotate, | |
| ) | |
| if evaluator.evaluator_id in seen: | |
| raise ValueError(f"duplicate evaluator id: {evaluator.evaluator_id}") | |
| seen.add(evaluator.evaluator_id) | |
| evaluators.append(evaluator) | |
| if not evaluators: | |
| raise ValueError("skill.yaml must configure at least one evaluator") | |
| return evaluators | |