File size: 3,491 Bytes
912dd45 | 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 | """Run the agent over all questions locally — no submission.
Answers are cached in answers.json, so reruns only redo what you ask for.
Full traces go to traces/<n>.txt for debugging.
Usage:
python run_local.py # run every question not yet in the cache
python run_local.py --redo 4 12 # rerun specific questions (by number)
python run_local.py --all # rerun everything
python run_local.py --show # just print the table from the cache
"""
import json
import sys
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from langchain_core.messages import ToolMessage
from agent import format_trace, run_agent
from questions import get_questions
ROOT = Path(__file__).parent
CACHE = ROOT / "answers.json"
TRACES = ROOT / "traces"
WORKERS = 2 # questions in parallel; more gets us rate-limited by Wikipedia
def evidence_flags(trace: list) -> str:
"""Heuristics for 'how much should I trust this answer?' (no ground truth needed)."""
tool_msgs = [m for m in trace if isinstance(m, ToolMessage)]
flags = []
if not tool_msgs:
flags.append("NO-TOOLS") # answered from memory/reasoning only
errors = [m for m in tool_msgs
if str(m.content).lower().startswith(("error", "could not", "no results", "search failed"))]
if errors:
flags.append(f"{len(errors)}-TOOL-ERR")
flags.append(f"{len(tool_msgs)} calls")
return ", ".join(flags)
def solve(n: int, q: dict) -> dict:
try:
answer, trace = run_agent(q["question"], q["task_id"], q.get("file_name", ""))
flags = evidence_flags(trace)
trace_text = format_trace(trace, width=2000)
except Exception as e: # e.g. GraphRecursionError when it runs out of steps
answer, flags, trace_text = "", f"CRASH: {type(e).__name__}", repr(e)
TRACES.mkdir(exist_ok=True)
(TRACES / f"{n}.txt").write_text(f"QUESTION #{n}\n{q['question']}\n\n{trace_text}\n\nANSWER: {answer}\n")
return {"n": n, "task_id": q["task_id"], "question": q["question"],
"answer": answer, "flags": flags}
def print_table(cache: dict) -> None:
rows = sorted(cache.values(), key=lambda r: r["n"])
print(f"\n{'#':>3} {'answer':<45} {'evidence'}")
print("-" * 80)
for r in rows:
print(f"{r['n']:>3} {r['answer'][:45]:<45} {r['flags']}")
print(f"\n{len(rows)} answers cached in {CACHE.name}; traces in {TRACES.name}/")
def main() -> None:
args = sys.argv[1:]
cache = json.loads(CACHE.read_text()) if CACHE.exists() else {}
if "--show" in args:
return print_table(cache)
questions = get_questions()
numbered = {i: q for i, q in enumerate(questions, 1)}
if "--all" in args:
todo = list(numbered)
elif "--redo" in args:
todo = [int(a) for a in args[args.index("--redo") + 1:]]
else:
todo = [i for i, q in numbered.items() if q["task_id"] not in cache]
print(f"Running {len(todo)} question(s) with {WORKERS} workers: {todo}")
with ThreadPoolExecutor(WORKERS) as pool:
futures = [pool.submit(solve, n, numbered[n]) for n in todo]
for fut in as_completed(futures):
r = fut.result()
cache[r["task_id"]] = r
CACHE.write_text(json.dumps(cache, indent=2, ensure_ascii=False)) # save as we go
print(f" done #{r['n']:>2}: {r['answer'][:50]!r} ({r['flags']})")
print_table(cache)
if __name__ == "__main__":
main()
|