#!/usr/bin/env python3 """Score the multi-tool set with the SAME slot and recall functions as score.py. python3 mt_score.py --ref compositional/test.jsonl --pred preds.jsonl [--route qrm_preds.jsonl] [--out-json x.json] Answer metrics (per 2-/3-backend group and overall): slot accuracy = every number in the reference answer and the module name appear in the prediction; rec80; mean content recall. Routing (optional): the predicted call list must equal the reference call set (tool and parameters, order ignored); also reports backend-set accuracy ignoring parameters. """ import argparse, json, collections, sys, os sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from score import slot_match, recall, wilson def calls_of(x): if isinstance(x, str): from mt_e2e import parse_calls x = parse_calls(x) or None if isinstance(x, dict): x = [x] if not isinstance(x, list): return None try: return sorted(json.dumps({"tool": c["tool"], "parameters": c.get("parameters") or {}}, sort_keys=True) for c in x) except Exception: return None def main(): ap = argparse.ArgumentParser() ap.add_argument("--ref", required=True); ap.add_argument("--pred"); ap.add_argument("--route") ap.add_argument("--out-json") a = ap.parse_args() ref = {json.loads(l)["question_hash"]: json.loads(l) for l in open(a.ref)} out = {"ref": a.ref, "n": len(ref)} if a.pred: preds = {} for l in open(a.pred): d = json.loads(l); preds[d["question_hash"]] = d.get("prediction", "") g = collections.defaultdict(lambda: collections.Counter()) for h, r in ref.items(): for key in ("all", f"{r['n_calls']}-backend"): p = preds.get(h, ""); s = g[key]; s["n"] += 1 sm = slot_match(p, r["answer"], r["module_name"]) if sm is not None: s["slot_n"] += 1; s["slot_ok"] += bool(sm) rc = recall(p, r["answer"]) if rc is not None: s["rec_n"] += 1; s["rec_sum"] += rc; s["rec80"] += rc >= 0.8 out["missing"] = len(set(ref) - set(preds)); out["answer"] = {} for k, s in sorted(g.items()): lo, hi = wilson(s["slot_ok"], s["slot_n"]) out["answer"][k] = {"n": s["n"], "slot_ok": s["slot_ok"], "slot_n": s["slot_n"], "slot": 100 * s["slot_ok"] / max(1, s["slot_n"]), "slot_ci": [lo, hi], "rec80": 100 * s["rec80"] / max(1, s["rec_n"]), "recall": 100 * s["rec_sum"] / max(1, s["rec_n"])} print(f"{k:10} n={s['n']:4} slot {s['slot_ok']}/{s['slot_n']} = {out['answer'][k]['slot']:.1f}% [{lo:.1f}, {hi:.1f}]" f" rec80 {out['answer'][k]['rec80']:.1f}% recall {out['answer'][k]['recall']:.1f}%") if a.route: rp = {} for l in open(a.route): d = json.loads(l); rp[d["question_hash"]] = d.get("raw", d.get("calls")) exact = tools_only = 0 for h, r in ref.items(): gt = calls_of(r["stage1_target"]); pr = calls_of(rp.get(h)) exact += pr == gt tools_only += pr is not None and sorted(json.loads(c)["tool"] for c in pr) == sorted(json.loads(c)["tool"] for c in gt) n = len(ref); lo, hi = wilson(exact, n) out["routing"] = {"exact": exact, "tools_only": tools_only, "n": n, "exact_pct": 100 * exact / n, "ci": [lo, hi]} print(f"routing exact {exact}/{n} = {100*exact/n:.1f}% [{lo:.1f}, {hi:.1f}] backend set {tools_only}/{n} = {100*tools_only/n:.1f}%") if a.out_json: json.dump(out, open(a.out_json, "w"), indent=1) if __name__ == "__main__": main()