#!/usr/bin/env python3 """WildTrace — model evaluation harness (evidence-withheld). Runs ANY model over the 481 tasks and writes its raw answers. The model sees ONLY the document + question (the clues and rubric are never shown). Documents longer than the model's context cap are scored 0 (out_of_context_scope) WITHOUT being sent. Plug in your own model by either: (a) editing `config.json` to point at any OpenAI-compatible /chat/completions endpoint (base_url + api_key_env + model), the default path; or (b) replacing the body of `call_model()` below with any callable you like. Output: results/.responses.json — feed this to run_judge.py to score it. Usage: export API_KEY=sk-... python run_eval.py --config config.json --data ../data/wildtrace_strict481.with_answers.json \ --corpus ../corpus --out ../results/mymodel.responses.json Resumable: re-run to retry transient failures (only out_of_context_scope is terminal). """ import argparse, json, os, re, time, urllib.request, urllib.error from concurrent.futures import ThreadPoolExecutor, as_completed from threading import Lock # ── exact evaluation prompt (changing this materially shifts scores — keep verbatim) ── EVAL_PROMPT = ("Answer using ONLY the document below. Include every specific detail from the text.\n\n" "Question: {q}\n\nDocument:\n{ctx}") # ── per-model context caps, in CHARACTERS (EN docs / CJK docs). These are the values used in # the paper; a doc longer than the cap is out_of_context_scope (scored 0). For a NEW model, # add an entry with its real native window (probe it — do NOT inherit an older version's cap), # or rely on "default". ~3.3 chars/token (EN), ~1.5 chars/token (CJK). ── def load_caps(cfg): caps = dict(DEFAULT_CAPS); caps.update(cfg.get("context_caps", {})) return caps DEFAULT_CAPS = { "default": {"en": 2_850_000, "cjk": 850_000}, "gpt-4.1": {"en": 2_850_000, "cjk": 850_000}, "gpt-5.1": {"en": 1_050_000, "cjk": 320_000}, "gpt-5.4": {"en": 2_850_000, "cjk": 850_000}, "gpt-5.5": {"en": 2_850_000, "cjk": 850_000}, "qwen3.5-plus": {"en": 2_850_000, "cjk": 850_000}, "qwen3.6-plus": {"en": 2_850_000, "cjk": 850_000}, "qwen3-max": {"en": 690_000, "cjk": 210_000}, "qwen3.7-max": {"en": 2_850_000, "cjk": 850_000}, "qwen3.7-plus": {"en": 2_850_000, "cjk": 850_000}, "gemini-2.5-pro": {"en": 2_850_000, "cjk": 850_000}, "gemini-3.1": {"en": 2_850_000, "cjk": 850_000}, "deepseek-v3.2": {"en": 1_200_000, "cjk": 400_000}, "deepseek-v4": {"en": 2_850_000, "cjk": 850_000}, "minimax-m2.7": {"en": 570_000, "cjk": 220_000}, "claude-opus-4.6": {"en": 2_850_000, "cjk": 850_000}, "claude-opus-4.8": {"en": 2_850_000, "cjk": 850_000}, "kimi-k2.6": {"en": 1_000_000, "cjk": 320_000}, "glm-5.2": {"en": 2_850_000, "cjk": 850_000}, "doubao-seed-2.1": {"en": 1_000_000, "cjk": 320_000}, } def is_cjk(text): return sum(1 for ch in text[:4000] if "一" <= ch <= "鿿") > 20 def post(url, key, payload, timeout): last = None for attempt in range(5): if attempt: time.sleep(min(60, 12 * 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()), None except urllib.error.HTTPError as e: body = e.read().decode("utf-8", "replace")[:300] last = f"HTTP {e.code}: {body}" if "rate limit" in body.lower() or "429" in body or "http code: 5" in body: time.sleep(45) except Exception as e: last = f"{type(e).__name__}: {str(e)[:200]}" return None, last def call_model(prompt, cfg): """Return (response_text, error). REPLACE THIS BODY to use a non-OpenAI backend. Default: OpenAI-compatible /chat/completions. Reasoning models need a large completion budget (truncated reasoning deflates scores ~7pp). Some models reject `temperature` (e.g. Anthropic Opus, GPT-5.4) — set "send_temperature": false in config for those. """ payload = {"model": cfg["model"], "messages": [{"role": "user", "content": prompt}], "max_tokens": cfg.get("max_tokens", 32768)} if cfg.get("send_temperature", True): payload["temperature"] = cfg.get("temperature", 0.1) data, err = post(cfg["base_url"], os.environ[cfg["api_key_env"]], payload, cfg.get("timeout_s", 900)) if err: return None, err txt = data.get("choices", [{}])[0].get("message", {}).get("content", "") if not txt and isinstance(data.get("content"), list): # Anthropic-native content blocks txt = "".join(b.get("text", "") for b in data["content"] if b.get("type") == "text") if not txt or len(txt) < 10: return None, "empty_response" return txt, None def main(): ap = argparse.ArgumentParser() ap.add_argument("--config", default="config.json") ap.add_argument("--data", required=True, help="wildtrace_strict481.with_answers.json (or questions_only.jsonl)") ap.add_argument("--corpus", required=True, help="path to corpus/ directory") ap.add_argument("--out", required=True, help="output responses json") ap.add_argument("--workers", type=int, default=4) args = ap.parse_args() cfg = json.load(open(args.config)) caps = load_caps(cfg) cap_key = cfg["model"] if cfg["model"] in caps else cfg.get("cap_key", "default") 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} done = {} if os.path.exists(args.out): for r in json.load(open(args.out)): resp = r["model_response"] if resp and (not resp.startswith("[ERROR") or resp.startswith("[ERROR out_of_context_scope")): done[r["question_id"]] = r # terminal: keep; transient errors retry work = [qid for qid in rows if qid not in done] _docs, lock = {}, Lock() def doc(cf): if cf not in _docs: _docs[cf] = open(os.path.join(args.corpus, os.path.basename(cf)), encoding="utf-8", errors="ignore").read() return _docs[cf] work.sort(key=lambda q: len(doc(rows[q].get("corpus_file", "")))) # short docs first print(f"model={cfg['model']} cap_key={cap_key} | to do={len(work)} (done={len(done)})", flush=True) def run(qid): r = rows[qid]; gt = r.get("ground_truth", {}) q = r.get("question_text") or gt.get("question_text") text = doc(r["corpus_file"]) cap = caps[cap_key]["cjk" if is_cjk(text) else "en"] if len(text) > cap: return qid, {"question_id": qid, "paradigm": r.get("paradigm"), "model_response": f"[ERROR out_of_context_scope doc={len(text)} cap={cap}]", "doc_chars": len(text), "cap_chars": cap}, "oos" resp, err = call_model(EVAL_PROMPT.format(q=q, ctx=text[:cap]), cfg) if resp is None: return qid, None, f"FAIL {str(err)[:60]}" # transient -> not persisted, retries on resume return qid, {"question_id": qid, "paradigm": r.get("paradigm"), "model_response": resp, "doc_chars": len(text), "cap_chars": cap}, "ok" n = 0 with ThreadPoolExecutor(max_workers=args.workers) as ex: for fut in as_completed([ex.submit(run, q) for q in work]): qid, row, tag = fut.result(); n += 1 if row: with lock: done[qid] = row json.dump(list(done.values()), open(args.out, "w"), ensure_ascii=False, indent=2) if n % 20 == 0 or tag.startswith("FAIL"): print(f"[{n}/{len(work)}] {qid[:40]} -> {tag}", flush=True) print(f"DONE: {len(done)}/{len(rows)} -> {args.out}", flush=True) if __name__ == "__main__": main()