#!/usr/bin/env python3 """WildTrace — rubric judge harness (3-judge non-contestant panel, averaged). Scores a model's answers (from run_eval.py) against each task's rubric. Each answer is graded by THREE non-contestant judges and the three scores are AVERAGED (simple mean, no same-family exclusion). out_of_context_scope answers stay 0 (the model could not ingest the evidence). Panel used in the paper (deliberately models NOT on the leaderboard): Claude-Sonnet-4.6 · Qwen3.5 · Gemini-2.5-Flash Supply your own judge endpoints in config.json -> "judges". OpenAI-compatible chat endpoints are the default; gateways that expose Gemini through native `contents`/`candidates` payloads can set `"api_type": "gemini_native"` on that judge. Using a single judge is supported (list one) but the paper headline is the 3-judge average. Output: results/.scores.json { "per_judge": {judge: {qid: score_0_1}}, "average": {qid: mean_score}, "overall": pct } Usage: export API_KEY=sk-... python run_judge.py --config config.json --data ../data/wildtrace_strict481.with_answers.json \ --responses ../results/mymodel.responses.json --out ../results/mymodel.scores.json """ import argparse, ast, json, os, re, time, urllib.request, urllib.error from concurrent.futures import ThreadPoolExecutor, as_completed from threading import Lock def post(url, key, payload, timeout=180): for attempt in range(4): if attempt: time.sleep(3 * attempt) try: req = urllib.request.Request(url, data=json.dumps(payload).encode(), headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"}) with urllib.request.urlopen(req, timeout=timeout) as r: return json.loads(r.read()) except Exception: pass return None def build_payload(judge_cfg, prompt): api_type = judge_cfg.get("api_type", "chat") max_tokens = judge_cfg.get("max_tokens", 16384) temperature = judge_cfg.get("temperature", 0.1) if api_type == "gemini_native": return { "model": judge_cfg["model"], "contents": [{"role": "user", "parts": [{"text": prompt}]}], "generationConfig": { "maxOutputTokens": max_tokens, "temperature": temperature, }, } return { "model": judge_cfg["model"], "messages": [{"role": "user", "content": prompt}], "max_tokens": max_tokens, "temperature": temperature, } def response_content(data): content = (data.get("choices", [{}])[0].get("message", {}) or {}).get("content", "") if not content and isinstance(data.get("content"), list): # Anthropic-native content blocks content = "".join(b.get("text", "") for b in data["content"] if b.get("type") == "text") if not content and isinstance(data.get("candidates"), list): # Gemini-native candidates parts = [] for cand in data["candidates"]: for part in ((cand.get("content") or {}).get("parts") or []): if part.get("text"): parts.append(part["text"]) content = "".join(parts) return content def build_judge_prompt(question, rubric, response): if isinstance(rubric, str): try: rubric = ast.literal_eval(rubric) except Exception: rubric = [] if not isinstance(rubric, list): rubric = [] rt = "".join(f'P{i+1} ({p.get("points", 0)}pts): {p.get("correct_criterion", "")[:260]}\n' for i, p in enumerate(rubric) if isinstance(p, dict)) return ("STRICT grader. Only award points for SPECIFIC details present.\n" f"QUESTION: {question[:600]}\nRUBRIC:\n{rt}\nRESPONSE:\n{response[:5000]}\n" 'Reply JSON: {"points_awarded":[],"total":}') def parse_total(content): if not content: return None t = re.sub(r"^```(?:json)?\s*", "", content.strip()); t = re.sub(r"\s*```$", "", t) m = re.search(r'\{.*"total".*\}', t, re.DOTALL) if not m: return None try: return float(json.loads(m.group())["total"]) except Exception: return None def judge_one(judge_cfg, key, question, rubric, response): """One judge's score in [0,1], or None on failure. total is a 0-100 sum -> /100, capped at 1.""" prompt = build_judge_prompt(question, rubric, response) data = post(judge_cfg["base_url"], key, build_payload(judge_cfg, prompt)) if not data: return None content = response_content(data) tot = parse_total(content) return None if tot is None else min(tot / 100.0, 1.0) def main(): ap = argparse.ArgumentParser() ap.add_argument("--config", default="config.json") ap.add_argument("--data", required=True) ap.add_argument("--responses", required=True) ap.add_argument("--out", required=True) ap.add_argument("--workers", type=int, default=8) args = ap.parse_args() cfg = json.load(open(args.config)) judges = cfg["judges"] # list of {name, base_url, model, api_key_env?, max_tokens?} rows = ([json.loads(l) for l in open(args.data) if l.strip()] if args.data.endswith(".jsonl") else json.load(open(args.data))) rows = {r["question_id"]: r for r in rows} responses = {r["question_id"]: r for r in json.load(open(args.responses))} out = json.load(open(args.out)) if os.path.exists(args.out) else {"per_judge": {}, "average": {}, "overall": None} per = out["per_judge"] for j in judges: per.setdefault(j["name"], {}) # work: (judge, qid) for non-oos answers not yet judged; oos -> score 0 directly oos = {qid for qid, r in responses.items() if str(r["model_response"]).startswith("[ERROR out_of_context_scope")} work = [] for j in judges: for qid, r in responses.items(): if qid in oos or qid not in rows: continue if str(r["model_response"]).startswith("[ERROR"): # transient eval failure: skip, not judged continue if per[j["name"]].get(qid) is None: work.append((j, qid)) print(f"judges={[j['name'] for j in judges]} | oos(score0)={len(oos)} | to judge={len(work)}", flush=True) lock = Lock(); n = [0] def run(item): j, qid = item r = rows[qid]; gt = r.get("ground_truth", {}) q = r.get("question_text") or gt.get("question_text") key = os.environ[j.get("api_key_env", cfg.get("api_key_env", "API_KEY"))] sc = judge_one(j, key, q, gt.get("scoring_rubric") or [], responses[qid]["model_response"]) with lock: per[j["name"]][qid] = sc; n[0] += 1 if n[0] % 100 == 0: json.dump(out, open(args.out, "w"), ensure_ascii=False, indent=2) print(f"{n[0]}/{len(work)}", flush=True) with ThreadPoolExecutor(max_workers=args.workers) as ex: list(as_completed([ex.submit(run, it) for it in work])) # aggregate: per task, average the available judge scores; oos -> 0 avg = {} all_qids = set(oos) | {qid for jn in per for qid in per[jn]} for qid in all_qids: if qid in oos: avg[qid] = 0.0; continue vals = [per[jn][qid] for jn in per if per[jn].get(qid) is not None] if vals: avg[qid] = sum(vals) / len(vals) out["average"] = avg out["overall"] = round(100 * sum(avg.values()) / len(avg), 2) if avg else None json.dump(out, open(args.out, "w"), ensure_ascii=False, indent=2) print(f"DONE: overall={out['overall']} over n={len(avg)} -> {args.out}", flush=True) if __name__ == "__main__": main()