#!/usr/bin/env python3 """End-to-end multi-tool evaluation helpers (router-predicted calls). calls : python3 mt_e2e.py calls --ref splits/mt/test.jsonl --route qrm_mt_test.jsonl --out splits/mt/e2e_calls.jsonl -> unique (design_id, tool, parameters) the router asked for, to execute with mt_ground.py build : python3 mt_e2e.py build --ref splits/mt/test.jsonl --route qrm_mt_test.jsonl \ --results splits/mt/e2e_results.jsonl --out splits/mt/test_e2e.jsonl -> copy of the reference set whose tool_result/stage2_context are rebuilt from the PREDICTED calls' results (same block format and cap as mt_qa.py); the reference answer is unchanged, so a wrong or missing call costs the answer its values. """ import argparse, hashlib, json, sys, os sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from mt_qa import cap, TOTAL_CAP def parse_calls(raw): if not raw: return [] t = raw i = min([k for k in (t.find("["), t.find("{")) if k >= 0], default=-1) if i < 0: return [] try: x, _ = json.JSONDecoder().raw_decode(t[i:]) except Exception: return [] if isinstance(x, dict): x = [x] out = [] for c in x if isinstance(x, list) else []: if isinstance(c, dict) and (c.get("tool") or c.get("tool_name")): out.append({"tool": c.get("tool") or c.get("tool_name"), "parameters": c.get("parameters") or {}}) return out[:4] def key(did, c): return hashlib.sha256(json.dumps([did, {"tool": c["tool"], "parameters": c["parameters"]}], sort_keys=True).encode()).hexdigest()[:16] def main(): ap = argparse.ArgumentParser(); ap.add_argument("mode", choices=["calls", "build"]) ap.add_argument("--ref", required=True); ap.add_argument("--route", required=True) ap.add_argument("--results"); ap.add_argument("--out", required=True) a = ap.parse_args() ref = [json.loads(l) for l in open(a.ref)] route = {json.loads(l)["question_hash"]: json.loads(l)["raw"] for l in open(a.route)} if a.mode == "calls": seen = {} for r in ref: for c in parse_calls(route.get(r["question_hash"])): k = key(r["design_id"], c); seen[k] = {"key": k, "design_id": r["design_id"], **c} with open(a.out, "w") as f: for c in seen.values(): f.write(json.dumps(c) + "\n") print("unique predicted calls", len(seen)); return res = {json.loads(l)["key"]: json.loads(l)["result"] for l in open(a.results)} n_empty = 0 with open(a.out, "w") as f: for r in ref: cl = parse_calls(route.get(r["question_hash"])) if not cl: tr = "(no backend was called)"; n_empty += 1 else: per = TOTAL_CAP // len(cl) - 40 tr = "\n\n".join(f"[{c['tool']} {json.dumps(c['parameters'])}]\n" + cap(json.dumps(res.get(key(r['design_id'], c), {"status": "error", "error": "not executed"}), indent=2), per) for c in cl) f.write(json.dumps(dict(r, tool_result=tr, stage2_context=f"Question: {r['question']}\n\n{tr}", predicted_calls=cl)) + "\n") print("built", len(ref), "records;", n_empty, "with no parsable call") if __name__ == "__main__": main()