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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
#!/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())