File size: 7,357 Bytes
d280328 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 | #!/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())
|