birgermoell's picture
Add 108 offline Harbor tasks for class-test
cf66d45 verified
Raw History Blame Contribute Delete
5.04 kB
#!/usr/bin/env python3
"""Verifier for Renaissance Labs practice environments. Standard library only.
Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1].
The reward is the weighted share of checks that pass. A missing, unreadable or non-object
answer scores 0. Each check addresses one value in the answer by a dotted path.
Check types
int exact integer (a float with integral value is accepted; booleans are not)
number within abs_tol of value (default 1e-9); booleans and strings are rejected
str equal after trimming and case-folding
bool exact boolean
list ordered list; items compared as int/number/str according to "item" (default str)
set unordered collection of distinct strings (or ints)
custom a function in validators.py: name(answer, args) -> bool or float in [0, 1]
"""
import argparse, json, math, os, sys
MISSING = object()
def lookup(obj, path):
cur = obj
for part in path.split("."):
if isinstance(cur, dict):
if part not in cur: return MISSING
cur = cur[part]
elif isinstance(cur, list):
try: cur = cur[int(part)]
except (ValueError, IndexError): return MISSING
else:
return MISSING
return cur
def is_num(x):
return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x)))
def eq_int(got, want):
return is_num(got) and float(got) == float(int(got)) and int(got) == want
def eq_num(got, want, tol):
return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12
def eq_str(got, want):
return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold()
def eq_item(got, want, kind, tol):
if kind == "int": return eq_int(got, want)
if kind == "number": return eq_num(got, want, tol)
return eq_str(got, want)
def run_check(answer, chk, validators):
t = chk["type"]
if t == "custom":
fn = getattr(validators, chk["name"], None) if validators else None
if fn is None: return 0.0
try: r = fn(answer, chk.get("args", {}))
except Exception: return 0.0
if r is True: return 1.0
if r is False or r is None: return 0.0
return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0
got = lookup(answer, chk["path"])
if got is MISSING: return 0.0
want, tol = chk["value"], chk.get("abs_tol", 1e-9)
if t == "int": ok = eq_int(got, want)
elif t == "number": ok = eq_num(got, want, tol)
elif t == "str": ok = eq_str(got, want)
elif t == "bool": ok = isinstance(got, bool) and got is want
elif t == "list":
ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want))
elif t == "set":
kind = chk.get("item", "str")
if not isinstance(got, list): ok = False
else:
norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None)
g = [norm(x) for x in got]; w = [norm(x) for x in want]
ok = None not in g and len(g) == len(set(g)) and set(g) == set(w)
else: ok = False
return 1.0 if ok else 0.0
def grade(answer, checks, validators=None):
"""Return (reward, details). answer is the parsed JSON, or None if it could not be read."""
if not isinstance(answer, dict):
return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks]
total = sum(c.get("weight", 1.0) for c in checks)
got, details = 0.0, []
for c in checks:
s = run_check(answer, c, validators)
got += s * c.get("weight", 1.0)
details.append({"check": c.get("path", c.get("name")), "score": s})
return (round(got / total, 6) if total else 0.0), details
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--answer", default="/app/answer.json")
ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json"))
ap.add_argument("--out", default="/logs/verifier")
a = ap.parse_args()
checks = json.load(open(a.checks))
try:
with open(a.answer) as f: answer = json.load(f)
except Exception:
answer = None
validators = None
here = os.path.dirname(os.path.abspath(__file__))
if os.path.exists(os.path.join(here, "validators.py")):
sys.path.insert(0, here)
import validators # noqa
reward, details = grade(answer, checks, validators)
os.makedirs(a.out, exist_ok=True)
with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward))
with open(os.path.join(a.out, "reward.json"), "w") as f:
json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f)
print("reward", reward)
if __name__ == "__main__":
main()