Shayan Darabi
Claude Opus 5.5
Add LangGraph + OpenAI GAIA agent for the Unit 4 final project
912dd45 Download run_local.py from ShayanDarabi/Final_Assignment_Template: direct link, hf CLI and curl.
- Browser
- Download file 3.49 kB
-
https://huggingface.co/spaces/ShayanDarabi/Final_Assignment_Template/resolve/main/run_local.py
- Command line
-
hf download hf://spaces/ShayanDarabi/Final_Assignment_Template/run_local.py
-
curl -L -o run_local.py https://huggingface.co/spaces/ShayanDarabi/Final_Assignment_Template/resolve/main/run_local.py
3.49 kB
| """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() | |