ttttim3's picture
Update agent code
90d0b3d verified
Raw History Blame Contribute Delete
3.77 kB
"""Fetch the Unit 4 questions + attachments and answer them in parallel.
usage:
python run_all.py # answer every question that has no result yet
python run_all.py --force # re-answer everything
python run_all.py --only 3 12 19 # (re-)answer specific questions by number (1-20) or task_id
python run_all.py --workers 4
"""
from __future__ import annotations
import argparse
import json
import subprocess
import sys
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
import requests
API = "https://agents-course-unit4-scoring.hf.space"
ROOT = Path(__file__).parent
DATA, RESULTS, LOGS = ROOT / "data", ROOT / "results", ROOT / "logs"
def fetch_questions() -> list[dict]:
DATA.mkdir(exist_ok=True)
path = DATA / "questions.json"
if not path.exists():
r = requests.get(f"{API}/questions", timeout=60)
r.raise_for_status()
path.write_text(json.dumps(r.json(), ensure_ascii=False, indent=2))
questions = json.loads(path.read_text())
files = DATA / "files"
files.mkdir(exist_ok=True)
for q in questions:
name = q.get("file_name")
if name and not (files / name).exists():
r = requests.get(f"{API}/files/{q['task_id']}", timeout=120)
if r.ok:
(files / name).write_bytes(r.content)
else: # the scoring API has been failing to serve some attachments
print(f"WARNING: could not download {name}: {r.status_code} {r.text[:100]}", flush=True)
return questions
def run_one(idx: int, q: dict, max_steps: int, timeout: int) -> str:
LOGS.mkdir(exist_ok=True)
log = LOGS / f"{idx:02d}_{q['task_id']}.log"
(RESULTS / f"{q['task_id']}.json").unlink(missing_ok=True) # never report a stale result
with open(log, "w") as f:
try:
subprocess.run(
[sys.executable, str(ROOT / "run_one.py"), q["task_id"], str(max_steps)],
stdout=f, stderr=subprocess.STDOUT, timeout=timeout, cwd=ROOT,
env={**__import__("os").environ, "COLUMNS": "120", "PYTHONUNBUFFERED": "1"},
)
except subprocess.TimeoutExpired:
RESULTS.mkdir(exist_ok=True)
(RESULTS / f"{q['task_id']}.json").write_text(json.dumps(
{"task_id": q["task_id"], "question": q["question"], "answer": "", "error": f"timeout after {timeout}s"},
ensure_ascii=False, indent=2))
res = json.loads((RESULTS / f"{q['task_id']}.json").read_text())
return f"{idx:2d}. {res.get('answer')!r} ({res.get('seconds', '?')}s) {res.get('error', '')}"
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--only", nargs="*", default=None)
ap.add_argument("--force", action="store_true")
ap.add_argument("--workers", type=int, default=4)
ap.add_argument("--max-steps", type=int, default=20)
ap.add_argument("--timeout", type=int, default=1500)
args = ap.parse_args()
questions = fetch_questions()
todo = []
for idx, q in enumerate(questions, 1):
if args.only is not None and str(idx) not in args.only and q["task_id"] not in args.only:
continue
done = (RESULTS / f"{q['task_id']}.json").exists()
if done and not args.force and args.only is None:
continue
todo.append((idx, q))
print(f"Running {len(todo)} question(s) with {args.workers} workers...", flush=True)
with ThreadPoolExecutor(max_workers=args.workers) as pool:
futures = [pool.submit(run_one, idx, q, args.max_steps, args.timeout) for idx, q in todo]
for fut in as_completed(futures):
print(fut.result(), flush=True)
if __name__ == "__main__":
main()