#!/usr/bin/env python3 """Minimal, dependency-free harness for crypto-accounting-bench. Iterates the tasks, sends each `prompt.md` to a model of your choice, parses the returned JSON, and scores it deterministically against `expected_answer.json`. python examples/run_benchmark.py --tasks tasks --out results.json `--model-command` receives the prompt on stdin and must print the model's JSON answer on stdout, so any provider or local runtime can be plugged in without this script depending on one. With no `--model-command` the script runs a scoring self-test on the expected answers (which must score 1.0). No network access, credentials or private files are required. """ import argparse, json, os, re, subprocess, sys from decimal import Decimal def load(path): with open(path, encoding="utf-8") as f: return json.load(f) def parse_answer(text): """Pull the first JSON object out of a model response.""" text = text.strip() fence = re.search(r"```(?:json)?\s*(.*?)```", text, re.S) if fence: text = fence.group(1).strip() start = text.find("{") if start < 0: raise ValueError("no JSON object in model output") depth, in_str, esc = 0, False, False for i, ch in enumerate(text[start:], start): if in_str: if esc: esc = False elif ch == chr(92): esc = True elif ch == '"': in_str = False continue if ch == '"': in_str = True elif ch == "{": depth += 1 elif ch == "}": depth -= 1 if depth == 0: return json.loads(text[start:i + 1]) raise ValueError("unterminated JSON object") def norm(lines): out = [] for l in lines or []: try: amt = Decimal(str(l.get("amountBase", "0"))) except Exception: amt = Decimal(0) if amt == 0: continue out.append((str(l.get("ledgerAccountName", "")).strip(), str(l.get("drCr", "")).strip(), amt)) return out def currency_pairs(lines): out = set() for line in lines or []: try: amount = Decimal(str(line.get("amountBase", "0"))) except Exception: continue if amount != 0: out.add((str(line.get("ledgerAccountName", "")).strip(), str(line.get("currency", "")).strip())) return out def score(answer, expected): """Deterministic per-criterion scoring. Mirrors the rubric criteria that can be decided mechanically. Criteria that require judgement (treatment narratives) are approximated by the deciding account being correct - documented in README.md under `Evaluation`. """ got = norm((answer.get("journalEntry") or {}).get("lines")) want = norm(expected["journalEntry"]["lines"]) got_names = {n for n, _, _ in got} want_names = {n for n, _, _ in want} key = set(expected["keyLineAccounts"]) got_raw = (answer.get("journalEntry") or {}).get("lines") or [] want_raw = expected["journalEntry"]["lines"] facts = { "deciding_account": key.issubset(got_names), "counter_account": want_names.issubset(got_names), "drcr": {(n, d) for n, d, _ in want} <= {(n, d) for n, d, _ in got}, "amount": {(n, a) for n, _, a in want} <= {(n, a) for n, _, a in got}, "complete": sorted(got) == sorted(want), "quantity": str(answer.get("assetQuantity", "")).strip() == expected["assetQuantity"], "currency": currency_pairs(want_raw) <= currency_pairs(got_raw), } facts["balanced"] = (sum(a for _, d, a in got if d == "Debit") == sum(a for _, d, a in got if d == "Credit")) and bool(got) facts["pass_eligible"] = all(facts[name] for name in ("complete", "quantity", "currency", "balanced")) total = 0.0 for c in expected["rubric"]["criteria"]: cid = c["id"] if "amount" in cid or "valuation" in cid or "basis" in cid: ok = facts["amount"] elif "drcr" in cid or "direction" in cid or "balance_side" in cid: ok = facts["drcr"] elif "complete" in cid: ok = facts["complete"] elif "counter" in cid or "proceeds" in cid or "acquired" in cid or "disposed" in cid: ok = facts["counter_account"] else: ok = facts["deciding_account"] total += c["weight"] * (1.0 if ok else 0.0) return round(total, 6), facts def main(): ap = argparse.ArgumentParser() ap.add_argument("--tasks", default="tasks") ap.add_argument("--out", default="results.json") ap.add_argument("--model-command", default=None, help="shell command; receives the prompt on stdin, prints JSON") ap.add_argument("--attempts", type=int, default=1) a = ap.parse_args() rows = [] for pid in sorted(os.listdir(a.tasks)): d = os.path.join(a.tasks, pid) if not os.path.isdir(d): continue expected = load(os.path.join(d, "expected_answer.json")) prompt = open(os.path.join(d, "prompt.md"), encoding="utf-8").read() best, per = 0.0, [] for _ in range(a.attempts): if a.model_command: p = subprocess.run(a.model_command, shell=True, input=prompt, capture_output=True, text=True) try: ans = parse_answer(p.stdout) except Exception as e: per.append({"score": 0.0, "error": str(e)}) continue else: ans = {"journalEntry": expected["journalEntry"], "assetQuantity": expected["assetQuantity"]} s, facts = score(ans, expected) per.append({"score": s, "facts": facts}) best = max(best, s) passed = any(x.get("score") == 1.0 and (x.get("facts") or {}).get("pass_eligible", False) for x in per) rows.append({"task_id": pid, "family": expected["rubric"]["family"], "attempts": per, "best": best, "passed": passed}) print(f"{pid} best={best:.3f} {'PASS' if passed else 'fail'}") n = len(rows) or 1 summary = { "tasks": len(rows), "attempts_per_task": a.attempts, "mean_score": round(sum(sum(x["score"] for x in r["attempts"]) / max(1, len(r["attempts"])) for r in rows) / n, 4), "best_at_k": round(sum(r["best"] for r in rows) / n, 4), "pass_at_k": round(sum(1 for r in rows if r["passed"]) / n, 4), "by_family": {}, } for r in rows: f = summary["by_family"].setdefault(r["family"], {"tasks": 0, "passed": 0}) f["tasks"] += 1 f["passed"] += int(r["passed"]) with open(a.out, "w", encoding="utf-8") as f: json.dump({"summary": summary, "results": rows}, f, indent=2) print("\n" + json.dumps(summary, indent=2)) if not a.model_command and summary["mean_score"] != 1.0: print("SELF-TEST FAILED: expected answers must score 1.0", file=sys.stderr) return 1 return 0 if __name__ == "__main__": raise SystemExit(main())