BioOcto / Biomanus /experiments /lab_bench /scripts /run_single_dbqa_debug.py
czty's picture
BioOcto code and data release (snapshot 2026-11-27) (part 32)
daf20b7 verified
Raw History Blame Contribute Delete
16.9 kB
#!/usr/bin/env python3
"""Run one DbQA question with detailed graph-planning and reasoning logs."""
from __future__ import annotations
import argparse
import json
import os
import re
import sys
from datetime import datetime, timezone
from pathlib import Path
from types import SimpleNamespace
from typing import Any
HYPO_ROOT = Path("/225040511/project/Hypo_Bio_OS")
LAB_BENCH_SCRIPTS_ROOT = HYPO_ROOT / "experiments" / "lab_bench" / "scripts"
sys.path.insert(0, str(HYPO_ROOT))
sys.path.insert(0, str(LAB_BENCH_SCRIPTS_ROOT))
from biomni.graph import GraphRouter, ToolGraph, ToolSchemaExtractor # noqa: E402
from biomni.model.query_rewriter import QueryRewriter # noqa: E402
from run_labbench_with_hypobioos import ( # noqa: E402
DEFAULT_AGENT_ROOT,
DEFAULT_GRAPH_DIR,
HypoBioOSLabBenchAgent,
configure_deepseek_env,
load_eval,
load_project_env,
parse_answer,
require_llm_config,
)
DEFAULT_OUTPUT_ROOT = HYPO_ROOT / "experiments" / "lab_bench" / "results" / "dbqa_debug"
DEFAULT_REUSE_RESULTS = HYPO_ROOT / "experiments" / "lab_bench" / "results" / "dbqa_seqqa" / "DbQA_dev_run1.json"
def sanitize_slug(text: str, limit: int = 48) -> str:
slug = re.sub(r"[^a-zA-Z0-9]+", "-", text.strip().lower()).strip("-")
return slug[:limit] or "dbqa-question"
def utc_stamp() -> str:
return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
def has_llm_config() -> bool:
return any(
os.getenv(key)
for key in ("ANTHROPIC_API_KEY", "OPENAI_API_KEY", "BIOMNI_CUSTOM_API_KEY", "DEEPSEEK_API_KEY")
)
def build_agent_args(args: argparse.Namespace) -> SimpleNamespace:
return SimpleNamespace(
repeat=args.repeat,
run_label=args.run_label,
agent_root=args.agent_root,
graph_dir=args.graph_dir,
executable_only_mcp=args.executable_only_mcp,
llm=args.llm,
source=args.source,
base_url=args.base_url,
api_key=args.api_key,
use_tool_retriever=args.use_tool_retriever,
mcp_server_top_k=args.mcp_server_top_k,
mcp_tool_top_k=args.mcp_tool_top_k,
mcp_server_candidate_pool=args.mcp_server_candidate_pool,
timeout_seconds=args.timeout_seconds,
)
def select_dbqa_instance(question_contains: str | None) -> tuple[Any, Any, str, str, str]:
evaluator = load_eval("DbQA")
chosen = None
chosen_subset = ""
chosen_target = ""
chosen_unsure = ""
needle = (question_contains or "").strip().lower()
for subset, instance in evaluator.eval_set.instances:
agent_input, target, unsure = instance.get_input_output()
question = str(agent_input.question)
if needle and needle in question.lower():
return instance, agent_input, subset, target, unsure
if chosen is None:
chosen = (instance, agent_input, subset, target, unsure)
if chosen is None:
raise RuntimeError("DbQA evaluator returned no instances.")
return chosen
def find_saved_task(question_contains: str | None, results_path: Path) -> dict[str, Any]:
if not results_path.exists():
raise FileNotFoundError(f"Saved DbQA result not found: {results_path}")
payload = json.loads(results_path.read_text(encoding="utf-8"))
needle = (question_contains or "").strip().lower()
fallback = None
for task_id, task in payload.get("tasks", {}).items():
question = str(task.get("input", {}).get("question", ""))
if fallback is None:
fallback = {"task_id": task_id, **task}
if needle and needle in question.lower():
return {"task_id": task_id, **task}
if fallback is None:
raise RuntimeError(f"No tasks found in saved DbQA result: {results_path}")
return fallback
def build_route_from_current_graph(
question: str,
graph_dir: Path,
*,
top_k_servers: int,
candidate_pool: int,
top_k_tools: int,
) -> tuple[dict[str, Any], dict[str, Any]]:
server_catalog = json.loads((graph_dir / "server_catalog.json").read_text(encoding="utf-8"))
extractor = ToolSchemaExtractor()
graph = ToolGraph(schema_extractor=extractor)
graph.build_from_server_entries(server_catalog)
query_context = QueryRewriter().rewrite(question, llm=None)
query_semantics = extractor.infer_query_semantics(query_context)
route_result = GraphRouter(schema_extractor=extractor).route(
query_context,
graph,
top_k_servers=top_k_servers,
candidate_pool=candidate_pool,
top_k_tools=top_k_tools,
)
return query_context | {"retrieval_mode": "offline_fallback"}, {
"query_semantics": query_semantics,
"route_result": route_result,
}
def format_choice_block(choices: list[str]) -> str:
return "\n".join(str(choice) for choice in choices)
def summarize_selected_servers(route_result: dict[str, Any]) -> list[dict[str, Any]]:
rows = []
for server in route_result.get("selected_servers", []) or []:
rows.append(
{
"name": server.get("name"),
"category": server.get("category", "general"),
"score": server.get("score", 0.0),
"reasons": server.get("graph_reason", []),
"tools": [tool.get("name") for tool in server.get("tools", [])],
}
)
return rows
def build_markdown_report(
*,
instance_id: str,
subset: str,
question: str,
choices: list[str],
target: str,
unsure: str,
answer: str,
raw_output: str,
query_context: dict[str, Any],
query_semantics: dict[str, Any],
graph_route: dict[str, Any],
internal_route: dict[str, Any],
reasoning_markdown: str,
) -> str:
lines = [
f"# DbQA Debug Run: {instance_id}",
"",
"## Question",
"",
f"- subset: {subset}",
f"- target_choice: {target}",
f"- unsure_choice: {unsure}",
f"- predicted_answer: {answer}",
"",
question,
"",
"Choices:",
"",
"```text",
format_choice_block(choices),
"```",
"",
"## Query Rewrite",
"",
"```json",
json.dumps(query_context, ensure_ascii=False, indent=2),
"```",
"",
"## Query Semantics Inferred For Graph Routing",
"",
"```json",
json.dumps(query_semantics, ensure_ascii=False, indent=2),
"```",
"",
"## How Planning Was Extracted From The Graph",
"",
"The current router uses the QueryRewriter output to infer a typed task specification: source semantic datatypes, target semantic datatype, operation anchors, and soft constraints.",
"It then searches the prebuilt graph at operation level, walking DataType -> Operation -> DataType edges until it finds paths that include the required operation anchors and reach the target type.",
"The planning object is synthesized from the highest-ranked operation path, then each operation is bound back to candidate MCP tools through implements_operation edges.",
"",
"### Task Spec",
"",
"```json",
json.dumps(graph_route.get("task_spec", {}), ensure_ascii=False, indent=2),
"```",
"",
"### Candidate Operation Paths",
"",
"```json",
json.dumps(graph_route.get("candidate_paths", []), ensure_ascii=False, indent=2),
"```",
"",
"### Bound Tool Call Chain",
"",
"```json",
json.dumps(graph_route.get("tool_plan", []), ensure_ascii=False, indent=2),
"```",
"",
"### Selected MCP Servers",
"",
"```json",
json.dumps(summarize_selected_servers(graph_route), ensure_ascii=False, indent=2),
"```",
"",
"### MCP Graph Route Result",
"",
"```json",
json.dumps(graph_route, ensure_ascii=False, indent=2),
"```",
"",
"### Internal Biomni Tool Route",
"",
"```json",
json.dumps(internal_route, ensure_ascii=False, indent=2),
"```",
"",
"## Reasoning Based On The Planning",
"",
"The transcript below is the actual agent reasoning/output log after the graph call chain was injected into the agent prompt.",
"",
reasoning_markdown.strip(),
"",
"## Final Raw Output",
"",
"```text",
raw_output.strip(),
"```",
]
return "\n".join(lines) + "\n"
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Run one DbQA question with detailed graph and reasoning logs.")
parser.add_argument("--question-contains", default="Currarino", help="Substring used to pick a DbQA question.")
parser.add_argument("--out-dir", type=Path, default=DEFAULT_OUTPUT_ROOT)
parser.add_argument("--agent-root", type=Path, default=DEFAULT_AGENT_ROOT)
parser.add_argument("--graph-dir", type=Path, default=DEFAULT_GRAPH_DIR)
parser.add_argument("--repeat", type=int, default=1)
parser.add_argument("--run-label", default="single_dbqa_debug")
parser.add_argument("--executable-only-mcp", action="store_true", default=True)
parser.add_argument("--include-nonexecutable-mcp", dest="executable_only_mcp", action="store_false")
parser.add_argument("--mcp-server-top-k", type=int, default=8)
parser.add_argument("--mcp-tool-top-k", type=int, default=12)
parser.add_argument("--mcp-server-candidate-pool", type=int, default=24)
parser.add_argument("--timeout-seconds", type=int, default=int(os.getenv("BIOMNI_TIMEOUT_SECONDS", "600")))
parser.add_argument("--use-tool-retriever", action="store_true", default=True)
parser.add_argument("--no-use-tool-retriever", dest="use_tool_retriever", action="store_false")
parser.add_argument("--reuse-results", type=Path, default=DEFAULT_REUSE_RESULTS)
parser.add_argument("--offline", action="store_true", help="Skip live agent execution and reuse saved DbQA logs.")
parser.add_argument("--llm", default=os.getenv("BIOMNI_LLM") or os.getenv("BIOMNI_LLM_MODEL"))
parser.add_argument("--source", default=os.getenv("BIOMNI_SOURCE"))
parser.add_argument("--base-url", default=os.getenv("BIOMNI_CUSTOM_BASE_URL"))
parser.add_argument("--api-key", default=os.getenv("BIOMNI_CUSTOM_API_KEY"))
return parser.parse_args()
def main() -> int:
args = parse_args()
if not args.graph_dir.exists():
raise SystemExit(f"MCP graph directory does not exist: {args.graph_dir}")
load_project_env()
configure_deepseek_env()
if args.api_key is None:
args.api_key = os.getenv("BIOMNI_CUSTOM_API_KEY")
if args.source is None:
args.source = os.getenv("BIOMNI_SOURCE")
if args.llm is None:
args.llm = os.getenv("BIOMNI_LLM") or os.getenv("BIOMNI_LLM_MODEL")
if args.base_url is None:
args.base_url = os.getenv("BIOMNI_CUSTOM_BASE_URL")
live_mode = not args.offline and has_llm_config()
if live_mode:
require_llm_config()
instance, agent_input, subset, target, unsure = select_dbqa_instance(args.question_contains)
agent = HypoBioOSLabBenchAgent(build_agent_args(args), "DbQA")
answer = agent._run_task_sync(agent_input)
trace = agent.traces[str(agent_input.id)]
query_context = dict(getattr(agent.agent, "query_context", {}) or {})
query_semantics = agent.agent.schema_extractor.infer_query_semantics(query_context)
graph_route = dict(getattr(agent.agent, "last_graph_route", {}) or {})
internal_route = dict(getattr(agent.agent, "last_internal_tool_route", {}) or {})
reasoning_markdown = agent.agent._generate_markdown_content(include_images=False)
answer_check = parse_answer(trace["raw_output"], len(agent_input.choices))
instance_id = str(agent_input.id)
question = str(agent_input.question)
choices = list(agent_input.choices)
else:
saved_task = find_saved_task(args.question_contains, args.reuse_results)
instance_id = str(saved_task["task_id"])
subset = str(saved_task.get("subset", "saved_result"))
question = str(saved_task.get("input", {}).get("question", ""))
choices = list(saved_task.get("input", {}).get("choices", []))
target = str(saved_task.get("target_choice", ""))
unsure = str(saved_task.get("unsure_choice", ""))
answer = str(saved_task.get("answer", ""))
trace = {
"raw_output": str(saved_task.get("raw_output", "")),
"selected_mcp_servers": list(saved_task.get("selected_mcp_servers", [])),
"registered_mcp_servers": list(saved_task.get("registered_mcp_servers", [])),
"runtime_mcp_config_paths": list(saved_task.get("runtime_mcp_config_paths", [])),
"biomni_log": list(saved_task.get("biomni_log", [])),
}
query_context, route_debug = build_route_from_current_graph(
question,
args.graph_dir,
top_k_servers=args.mcp_server_top_k,
candidate_pool=args.mcp_server_candidate_pool,
top_k_tools=args.mcp_tool_top_k,
)
query_semantics = route_debug["query_semantics"]
graph_route = route_debug["route_result"]
internal_route = {}
transcript = "\n\n".join(str(entry) for entry in trace["biomni_log"])
reasoning_markdown = "\n".join(
[
"# Biomni Agent Conversation History",
"",
"Offline fallback mode reused the saved reasoning log from the previous DbQA run.",
"",
"```text",
transcript.strip(),
"```",
]
)
answer_check = parse_answer(trace["raw_output"], len(choices))
run_name = f"{utc_stamp()}_{sanitize_slug(args.question_contains or question)}"
out_dir = args.out_dir / run_name
out_dir.mkdir(parents=True, exist_ok=True)
payload = {
"live_mode": live_mode,
"instance_id": instance_id,
"subset": subset,
"question": question,
"choices": choices,
"target_choice": target,
"unsure_choice": unsure,
"predicted_answer": answer,
"predicted_answer_reparsed": answer_check,
"raw_output": trace["raw_output"],
"query_context": query_context,
"query_semantics": query_semantics,
"graph_route_result": graph_route,
"internal_tool_route": internal_route,
"selected_mcp_servers": trace.get("selected_mcp_servers", []),
"registered_mcp_servers": trace.get("registered_mcp_servers", []),
"runtime_mcp_config_paths": trace.get("runtime_mcp_config_paths", []),
"biomni_log": trace.get("biomni_log", []),
}
markdown_report = build_markdown_report(
instance_id=instance_id,
subset=subset,
question=question,
choices=choices,
target=str(target),
unsure=str(unsure),
answer=str(answer),
raw_output=str(trace["raw_output"]),
query_context=query_context,
query_semantics=query_semantics,
graph_route=graph_route,
internal_route=internal_route,
reasoning_markdown=reasoning_markdown,
)
json_path = out_dir / "debug_payload.json"
md_path = out_dir / "debug_report.md"
txt_path = out_dir / "stdout_summary.txt"
json_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
md_path.write_text(markdown_report, encoding="utf-8")
summary_lines = [
f"live_mode={live_mode}",
f"instance_id={instance_id}",
f"subset={subset}",
f"question={question}",
f"target_choice={target}",
f"predicted_answer={answer}",
f"selected_mcp_servers={trace.get('selected_mcp_servers', [])}",
"planning_steps="
+ " | ".join(
step.get("operation") or step.get("step", "")
for step in graph_route.get("operation_plan", {}).get("steps", [])
),
f"execution_plan_len={len(graph_route.get('execution_plan', []))}",
f"json={json_path}",
f"markdown={md_path}",
]
summary = "\n".join(summary_lines) + "\n"
txt_path.write_text(summary, encoding="utf-8")
print(summary, end="")
print("Top selected servers and reasons:")
for server in summarize_selected_servers(graph_route)[:5]:
print(f"- {server['name']} score={server['score']:.2f} tools={server['tools'][:4]}")
for reason in server["reasons"][:4]:
print(f" reason: {reason}")
print(f"Detailed markdown report: {md_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main())