from __future__ import annotations import argparse import json import os import re import shlex import subprocess import sys import tempfile from datetime import datetime from pathlib import Path from time import perf_counter from typing import Any from langchain_core.messages import HumanMessage, SystemMessage from langchain_core.tools import tool from langchain_openai import ChatOpenAI from langgraph.prebuilt import create_react_agent from .config import ( DATASET_ROOT, DEFAULT_RUNS_ROOT, METADATA_PATH, TASK_EXTRA_INSTRUCTIONS, TASK_OUTPUTS, ) def load_dotenv_files(paths: list[Path]) -> None: for path in paths: if not path.exists(): continue for raw_line in path.read_text(encoding="utf-8").splitlines(): line = raw_line.strip() if not line or line.startswith("#") or "=" not in line: continue key, value = line.split("=", 1) key = key.strip() value = value.strip().strip('"').strip("'") os.environ.setdefault(key, value) def utc_timestamp() -> str: return datetime.utcnow().strftime("%Y%m%d_%H%M%S") def save_json(path: Path, payload: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(payload, ensure_ascii=False, indent=2, default=str), encoding="utf-8") def load_metadata(path: Path) -> list[dict[str, Any]]: return json.loads(path.read_text(encoding="utf-8")) def list_visible_files(directory: Path, limit: int = 80) -> list[str]: if not directory.exists(): return [] files: list[str] = [] for path in sorted(directory.rglob("*")): if not path.is_file(): continue rel = path.relative_to(directory) if rel.parts and rel.parts[0] == "__pycache__": continue files.append(str(rel)) if len(files) >= limit: files.append(f"... truncated after {limit} files") break return files def is_within(path: Path, root: Path) -> bool: try: path.resolve().relative_to(root.resolve()) return True except ValueError: return False def validate_access(path: Path, *, task_dir: Path, run_dir: Path) -> None: resolved = path.resolve() allowed_roots = [task_dir / "data", task_dir / "reference", run_dir] if any(root.exists() and is_within(resolved, root) for root in allowed_roots): return raise PermissionError( "Access denied. Use only this task's data/reference directories and the current run directory." ) def trim_output(text: str, limit: int = 12000) -> str: if len(text) <= limit: return text return text[:limit] + f"\n...[truncated {len(text) - limit} chars]" def build_tools(task_dir: Path, run_dir: Path, command_timeout: int): @tool def list_files(path: str = ".") -> str: """List files below an allowed data, reference, or run directory.""" try: target = Path(path) if not target.is_absolute(): target = run_dir / target validate_access(target, task_dir=task_dir, run_dir=run_dir) if not target.exists(): return f"Missing path: {target}" if target.is_file(): return str(target) return "\n".join(list_visible_files(target, limit=160)) or "" except PermissionError as exc: return f"ACCESS_ERROR: {exc}" @tool def read_text_file(path: str, max_chars: int = 12000) -> str: """Read a text-like file from an allowed directory.""" try: target = Path(path) if not target.is_absolute(): target = run_dir / target validate_access(target, task_dir=task_dir, run_dir=run_dir) if not target.exists(): return f"Missing file: {target}" if target.stat().st_size > max_chars: return target.read_text(encoding="utf-8", errors="replace")[:max_chars] return target.read_text(encoding="utf-8", errors="replace") except PermissionError as exc: return f"ACCESS_ERROR: {exc}" @tool def run_shell(command: str, timeout_seconds: int | None = None) -> str: """Run a shell command inside the current run directory.""" timeout = min(timeout_seconds or command_timeout, command_timeout) try: completed = subprocess.run( command, cwd=run_dir, shell=True, text=True, capture_output=True, timeout=timeout, env=os.environ.copy(), ) output = { "returncode": completed.returncode, "stdout": trim_output(completed.stdout), "stderr": trim_output(completed.stderr), } except subprocess.TimeoutExpired as exc: output = { "returncode": 124, "stdout": trim_output(exc.stdout or ""), "stderr": trim_output(exc.stderr or ""), "error": f"TIMEOUT after {timeout}s", } return json.dumps(output, ensure_ascii=False, indent=2) @tool def run_python(code: str, timeout_seconds: int | None = None) -> str: """Run Python code inside the current run directory.""" timeout = min(timeout_seconds or command_timeout, command_timeout) with tempfile.NamedTemporaryFile("w", suffix=".py", dir=run_dir, delete=False, encoding="utf-8") as handle: handle.write(code) script_path = Path(handle.name) command = [sys.executable, str(script_path)] try: completed = subprocess.run( command, cwd=run_dir, text=True, capture_output=True, timeout=timeout, env=os.environ.copy(), ) output = { "script": str(script_path), "returncode": completed.returncode, "stdout": trim_output(completed.stdout), "stderr": trim_output(completed.stderr), } except subprocess.TimeoutExpired as exc: output = { "script": str(script_path), "returncode": 124, "stdout": trim_output(exc.stdout or ""), "stderr": trim_output(exc.stderr or ""), "error": f"TIMEOUT after {timeout}s", } return json.dumps(output, ensure_ascii=False, indent=2) return [list_files, read_text_file, run_shell, run_python] def normalize_transcript_quant(path: Path) -> list[str]: if not path.exists(): return ["missing"] lines = [line.strip() for line in path.read_text(encoding="utf-8", errors="replace").splitlines() if line.strip()] actions: list[str] = [] if lines and re.sub(r"[\s,]+", "", lines[0].lower()) in {"transcript_idcount", "transcriptcount"}: lines = lines[1:] actions.append("removed_header") normalized = [] for line in lines: parts = [part.strip() for part in re.split(r"[\t,]", line) if part.strip()] if len(parts) >= 2: normalized.append(f"{parts[0]}\t{parts[1]}") path.write_text("\n".join(normalized) + ("\n" if normalized else ""), encoding="utf-8") actions.append("normalized_two_column_tsv") return actions def validate_outputs(task_id: str, run_dir: Path) -> list[dict[str, Any]]: reports: list[dict[str, Any]] = [] for name in TASK_OUTPUTS[task_id]: path = run_dir / name actions: list[str] = [] if task_id == "transcript-quant" and name == "truth.tsv" and path.exists(): actions.extend(normalize_transcript_quant(path)) reports.append( { "path": str(path), "exists": path.exists(), "size_bytes": path.stat().st_size if path.exists() else 0, "actions": actions, } ) return reports def completed_run_summary(run_dir: Path, task_id: str) -> dict[str, Any] | None: summary_path = run_dir / "run_summary.json" if not summary_path.exists(): return None try: summary = json.loads(summary_path.read_text(encoding="utf-8")) except json.JSONDecodeError: return None if summary.get("error"): return None outputs = summary.get("outputs") or validate_outputs(task_id, run_dir) if not outputs: return None for output in outputs: if not output.get("exists") or int(output.get("size_bytes") or 0) <= 0: return None return summary def latest_completed_run(runs_root: Path, task_id: str) -> dict[str, Any] | None: pattern = re.compile(rf"^{re.escape(task_id)}_\d{{8}}_\d{{6}}$") candidates = sorted(path for path in runs_root.iterdir() if path.is_dir() and pattern.match(path.name)) for run_dir in reversed(candidates): summary = completed_run_summary(run_dir, task_id) if summary is not None: summary = dict(summary) summary["skipped"] = True summary["skip_reason"] = "completed_run_exists" return summary return None def build_prompt(task_meta: dict[str, Any], run_dir: Path) -> str: task_id = task_meta["task_id"] task_dir = DATASET_ROOT / task_id data_dir = task_dir / "data" reference_dir = task_dir / "reference" outputs = [run_dir / name for name in TASK_OUTPUTS[task_id]] extra = TASK_EXTRA_INSTRUCTIONS.get(task_id, "") return f""" Task ID: {task_id} Task name: {task_meta.get("name", task_id)} Benchmark prompt: {task_meta.get("task_prompt", "")} Background: {task_meta.get("description", "")} Use a ReAct workflow: inspect files, reason about the pipeline, execute code or shell commands, check outputs, then finish. Rules: - Use only this task's data directory, reference directory, and the current run directory. - Do not read {task_dir / "results"} or any sibling task directory. - Do not download external databases or install packages. - Write final deliverables exactly at the required paths below. - Keep intermediate scripts/logs inside {run_dir}. - Before finishing, verify that every required output file exists and is non-empty. {("- " + extra) if extra else ""} Data directory: {data_dir} Visible data files: {chr(10).join("- " + item for item in list_visible_files(data_dir)) or "- "} Reference directory: {reference_dir if reference_dir.exists() else ""} Visible reference files: {chr(10).join("- " + item for item in list_visible_files(reference_dir)) if reference_dir.exists() else "- "} Required outputs: {chr(10).join("- " + str(path) for path in outputs)} """.strip() def make_model(args: argparse.Namespace) -> ChatOpenAI: api_key = ( args.api_key or os.getenv("DEEPSEEK_API_KEY") or os.getenv("BIOMNI_CUSTOM_API_KEY") or os.getenv("OPENAI_API_KEY") ) if not api_key: raise SystemExit("Missing API key. Set DEEPSEEK_API_KEY, BIOMNI_CUSTOM_API_KEY, or OPENAI_API_KEY.") model_name = args.model if ( "deepseek" in args.base_url.lower() and not args.allow_deepseek_reasoner and ("reasoner" in model_name.lower() or "thinking" in model_name.lower()) ): print( f"DeepSeek model {model_name!r} uses thinking/reasoning_content mode, " "which is not compatible with this LangGraph ReAct tool loop. " "Falling back to 'deepseek-chat'.", flush=True, ) model_name = "deepseek-chat" return ChatOpenAI( model=model_name, api_key=api_key, base_url=args.base_url, temperature=args.temperature, timeout=args.llm_timeout, max_retries=args.max_retries, ) def run_task(task_meta: dict[str, Any], args: argparse.Namespace, model: ChatOpenAI) -> dict[str, Any]: task_id = task_meta["task_id"] task_dir = DATASET_ROOT / task_id run_dir = args.runs_root / f"{task_id}_{utc_timestamp()}" run_dir.mkdir(parents=True, exist_ok=True) prompt = build_prompt(task_meta, run_dir) (run_dir / "task_prompt.txt").write_text(prompt, encoding="utf-8") save_json( run_dir / "run_metadata.json", { "task_id": task_id, "task_name": task_meta.get("name", task_id), "dataset_dir": str(task_dir), "run_dir": str(run_dir), "model": model.model_name, "requested_model": args.model, "base_url": args.base_url, "required_outputs": [str(run_dir / name) for name in TASK_OUTPUTS[task_id]], "started_at_utc": utc_timestamp(), }, ) system = SystemMessage( content=( "You are a careful bioinformatics ReAct agent with code execution tools. " "Use tools to inspect data and create the requested benchmark outputs. " "Do not expose API keys or environment secrets. Keep answers concise." ) ) tools = build_tools(task_dir=task_dir, run_dir=run_dir, command_timeout=args.command_timeout) agent = create_react_agent(model, tools) started = perf_counter() try: result = agent.invoke( {"messages": [system, HumanMessage(content=prompt)]}, config={"recursion_limit": args.recursion_limit}, ) error = None except Exception as exc: result = {"messages": []} error = repr(exc) elapsed = perf_counter() - started messages = result.get("messages", []) if isinstance(result, dict) else [] transcript = [] for message in messages: kind = message.__class__.__name__ content = getattr(message, "content", "") transcript.append({"type": kind, "content": content}) save_json(run_dir / "execution_log.json", transcript) (run_dir / "execution_log.txt").write_text( "\n\n".join(f"{item['type']}:\n{item['content']}" for item in transcript), encoding="utf-8", ) final_answer = transcript[-1]["content"] if transcript else "" if error: final_answer = f"ERROR: {error}\n\n{final_answer}" (run_dir / "final_answer.txt").write_text(str(final_answer), encoding="utf-8") output_status = validate_outputs(task_id, run_dir) save_json(run_dir / "output_validation.json", {"outputs": output_status}) summary = { "task_id": task_id, "run_dir": str(run_dir), "total_runtime_seconds": elapsed, "error": error, "outputs": output_status, "final_answer_path": str(run_dir / "final_answer.txt"), } save_json(run_dir / "run_summary.json", summary) return summary def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="Run bioagent-bench with a LangChain ReAct+code DeepSeek agent.") parser.add_argument("--task", action="append", help="Task ID to run. Repeat for multiple tasks.") parser.add_argument("--all", action="store_true", help="Run all supported tasks.") parser.add_argument("--metadata", type=Path, default=METADATA_PATH) parser.add_argument("--runs-root", type=Path, default=DEFAULT_RUNS_ROOT) parser.add_argument("--model", default=os.getenv("DEEPSEEK_MODEL_NAME", "deepseek-chat")) parser.add_argument("--base-url", default=os.getenv("DEEPSEEK_BASE_URL", "https://api.deepseek.com/v1")) parser.add_argument( "--allow-deepseek-reasoner", action="store_true", help=( "Allow DeepSeek reasoner/thinking models. Not recommended with ReAct tool loops because " "DeepSeek may require reasoning_content to be replayed between API calls." ), ) parser.add_argument("--api-key", default=None) parser.add_argument("--temperature", type=float, default=0.0) parser.add_argument("--llm-timeout", type=int, default=120) parser.add_argument("--max-retries", type=int, default=2) parser.add_argument("--command-timeout", type=int, default=900) parser.add_argument("--recursion-limit", type=int, default=80) parser.add_argument("--env-file", action="append", type=Path, default=[]) parser.add_argument("--skip-completed", action="store_true", help="Skip tasks with a completed prior run.") return parser.parse_args() def main() -> int: args = parse_args() default_envs = [ Path.cwd() / ".env", Path("/225040511/project/.env"), Path("/225040511/project/my_graph/.env"), ] load_dotenv_files([*default_envs, *args.env_file]) metadata = load_metadata(args.metadata) by_task = {item["task_id"]: item for item in metadata if item["task_id"] in TASK_OUTPUTS} task_ids = list(TASK_OUTPUTS) if args.all else args.task or [] if not task_ids: raise SystemExit("Provide --task or --all.") unsupported = [task_id for task_id in task_ids if task_id not in by_task] if unsupported: raise SystemExit(f"Unsupported task IDs: {unsupported}") args.runs_root.mkdir(parents=True, exist_ok=True) model = make_model(args) summaries = [] for task_id in task_ids: if args.skip_completed: completed = latest_completed_run(args.runs_root, task_id) if completed is not None: print(f"Skipping {task_id}: completed run exists at {completed.get('run_dir')}", flush=True) summaries.append(completed) continue print(f"Running {task_id} with {model.model_name} via {args.base_url}", flush=True) summary = run_task(by_task[task_id], args, model) summaries.append(summary) print(json.dumps(summary, ensure_ascii=False, indent=2), flush=True) batch = {"timestamp_utc": utc_timestamp(), "tasks": summaries} save_json(args.runs_root / "latest_batch_summary.json", batch) print(f"Batch summary: {args.runs_root / 'latest_batch_summary.json'}") return 0 if __name__ == "__main__": raise SystemExit(main())