#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Run hypothesis-generation experiments with resumable, cached calls. Examples -------- Offline smoke test (no API key needed): python scripts/run_experiments.py --methods direct,hypoagent --limit 2 --mode offline Full main experiment: python scripts/run_experiments.py --methods direct,cot,rag,multi_agent,hypoagent --workers 6 Full ablation (all variants derived from the final architecture): python scripts/run_experiments.py \ --methods hypoagent,hypoagent_no_gap,hypoagent_no_cards,hypoagent_no_debate,hypoagent_no_trace \ --workers 6 Replay the exact cached outputs (no network): python scripts/run_experiments.py --methods ... --mode replay --overwrite """ from __future__ import annotations import argparse import json import sys import time from concurrent.futures import ThreadPoolExecutor, as_completed from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) from hypoagent.config import Config # noqa: E402 from hypoagent.kb import KnowledgeBase # noqa: E402 from hypoagent.llm import LLMClient # noqa: E402 from hypoagent.pipeline import ( # noqa: E402 GENERATIONS_DIR, METHOD_LABELS, METHODS, load_questions, run_one_to_disk, ) def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--methods", default=",".join(METHODS), help="comma-separated method names") parser.add_argument("--qids", default="", help="comma-separated question ids (default: all)") parser.add_argument("--limit", type=int, default=0, help="only the first N questions") parser.add_argument("--workers", type=int, default=3, help="parallel (question, method) tasks") parser.add_argument("--top-k", type=int, default=8, help="number of literature abstracts") parser.add_argument("--mode", default="", choices=["", "auto", "live", "replay", "offline"]) parser.add_argument("--overwrite", action="store_true", help="ignore existing generations") parser.add_argument("--dry-run", action="store_true", help="show the plan and exit") return parser.parse_args() def main() -> int: args = parse_args() methods = [m.strip() for m in args.methods.split(",") if m.strip()] unknown = [m for m in methods if m not in METHODS] if unknown: raise SystemExit(f"Unknown methods: {unknown}; choose from {METHODS}") questions = load_questions() if args.qids: wanted = {q.strip() for q in args.qids.split(",") if q.strip()} questions = [q for q in questions if q["qid"] in wanted] if args.limit: questions = questions[: args.limit] if not questions: raise SystemExit("No questions selected") config = Config() if args.mode: config.mode = args.mode if config.mode == "offline": config.provider = "offline" tasks = [] for question in questions: for method in methods: path = GENERATIONS_DIR / question["qid"] / f"{method}.json" if path.exists() and not args.overwrite: continue tasks.append((method, question)) print("=" * 78) print("HypoAgent-Bio experiment runner") print("=" * 78) print(json.dumps(config.describe(), ensure_ascii=False, indent=2)) print(f"questions={len(questions)} methods={methods}") print(f"pending tasks={len(tasks)} (existing results are reused unless --overwrite)") if args.dry_run: for method, question in tasks: print(f" {question['qid']} {METHOD_LABELS[method]}") return 0 if not tasks: print("Nothing to do. Use --overwrite to regenerate.") return 0 kb = KnowledgeBase() print(f"KB: {json.dumps(kb.stats(), ensure_ascii=False)}") client = LLMClient(config) started = time.time() errors = [] done = 0 with ThreadPoolExecutor(max_workers=max(1, args.workers)) as pool: futures = { pool.submit(run_one_to_disk, method, question, kb, client, args.top_k, args.overwrite): (method, question) for method, question in tasks } for future in as_completed(futures): method, question = futures[future] done += 1 try: record = future.result() status = "ERROR" if record.get("error") else "ok" if record.get("error"): errors.append((question["qid"], method, record["error"])) print( f"[{done:>3}/{len(tasks)}] {question['qid']} {METHOD_LABELS[method]:<18} " f"{status:<5} calls={len(record.get('calls', []))} " f"latency={record.get('latency_s', 0):.1f}s", flush=True, ) except Exception as exc: # noqa: BLE001 errors.append((question["qid"], method, f"{type(exc).__name__}: {exc}")) print(f"[{done:>3}/{len(tasks)}] {question['qid']} {method} FAILED: {exc}", flush=True) elapsed = time.time() - started print("-" * 78) print(f"finished {len(tasks)} tasks in {elapsed / 60:.1f} min; errors={len(errors)}") for qid, method, error in errors: print(f" ! {qid} {method}: {error[:300]}") return 1 if errors else 0 if __name__ == "__main__": raise SystemExit(main())