"""Answer parsing shared by the task verifiers. Verifiers never trust the agent's format.""" import math import re from dataclasses import dataclass, field from typing import Callable @dataclass class TaskInstance: instruction: str files: dict[str, str] grade: Callable[[str], float] oracle: str # Plausible but wrong answers, used only by tests. wrong: list[str] = field(default_factory=list) # Extra data for tests and workspace graders (never shown to the agent). meta: dict = field(default_factory=dict) def norm(text: str) -> str: return " ".join(str(text).strip().strip("`'\"").lower().split()) def to_number(text: str): cleaned = re.sub(r"[\s,$€£%]", "", str(text)).strip("`'\"") cleaned = re.sub(r"(usd|eur|mm|mmol/l|g|s|sec|seconds)$", "", cleaned, flags=re.I) try: value = float(cleaned) except ValueError: return None return value if math.isfinite(value) else None def number_close(text: str, target: float, abs_tol: float = 0.0, rel_tol: float = 0.0) -> bool: value = to_number(text) if value is None: return False return abs(value - target) <= max(abs_tol, rel_tol * abs(target)) + 1e-9 def split_parts(text: str, count: int, sep: str = ","): parts = [p.strip() for p in str(text).strip().strip("`'\"").split(sep)] return parts if len(parts) == count else None def token_set(text: str): body = norm(text).strip("[](){}") if body == "": return None # an empty submission never matches, even when the answer is "none" if body in ("none", "no", "nothing"): return frozenset() return frozenset(t.strip().strip("'\"") for t in re.split(r"[,\s;]+", body) if t.strip()) def parts_score(text: str, checks: list[Callable[[str], bool]], sep: str = ",") -> float: """Mean of per-part checks; 0 when the part count is wrong.""" parts = split_parts(text, len(checks), sep) if parts is None and sep == ",": # tolerate thousands separators such as 12,345.67 parts = split_parts(re.sub(r"(?<=\d),(?=\d{3}(?!\d))", "", str(text)), len(checks), sep) if parts is None: return 0.0 return sum(1.0 for part, check in zip(parts, checks) if check(part)) / len(checks) def exact(target: str) -> Callable[[str], bool]: return lambda part: norm(part) == norm(target) def close(target: float, abs_tol: float = 0.0, rel_tol: float = 0.0) -> Callable[[str], bool]: return lambda part: number_close(part, target, abs_tol, rel_tol) def csv_text(header: list[str], rows: list[list]) -> str: lines = [",".join(header)] lines += [",".join(str(v) for v in row) for row in rows] return "\n".join(lines) + "\n"