ryan-superman's picture
Publish trajectories and metrics (BMB content gated)
673d45d verified
Raw History Blame Contribute Delete
7.35 kB
"""A rule-compliant view of ToolUniverse for BioMysteryBench agents.
ToolUniverse ships 2,315 scientific tools, and **422 of them would break this benchmark's
one hard rule**. Anthropic's terms permit "gene ID lookup, sequence annotation, reference
genome download, BLAST" and forbid "looking up GEO/SRA/ENA/BioProject accession IDs to
identify the original dataset, source publication, or study metadata". ToolUniverse
contains `GEO_get_dataset_details` ("by its accession"), `GEO_search_chipseq_datasets`,
`ENCODE_search_histone_experiments` and hundreds more of exactly that shape. An agent
handed the unfiltered library could identify the source study instead of analysing the
data, which would invalidate every result and breach the access terms.
So this module never exposes ToolUniverse directly. Two independent layers must both pass:
1. **Category whitelist** -- only categories whose purpose is annotation, sequence or
structure lookup. Anything not named is excluded, so a new upstream category cannot
silently become reachable.
2. **Pattern scan** -- a per-tool check on name and description, applied *again* at call
time. Filtering only at listing time would leave the door open to an agent naming a
tool directly.
Defence in depth is deliberate: the whitelist is the policy and the scan is the backstop,
and either alone has failed for us before.
"""
from __future__ import annotations
import json
import os
import re
from dataclasses import dataclass
from functools import lru_cache
from pathlib import Path
# Categories whose tools annotate sequence, genes, proteins or structures. Chosen against
# the benchmark's own wording. Everything else is excluded by omission.
ALLOWED_CATEGORIES = frozenset({
"ensembl", "uniprot", "rcsb_pdb", "software_bioinformatics",
"alliance_genome", "ucsc_genome", "reactome", "gene_ontology",
})
# Second layer. Matches the provenance-lookup shapes the rule names, plus the literature
# and dataset-search shapes that reach the same answer by another route.
FORBIDDEN_PATTERN = re.compile(
r"\b(GEO|SRA|ENA|BioProject|BioSample|ArrayExpress|dbGaP|EGA|PRIDE|MassIVE"
r"|MetaboLights|ENCODE|GTEx|TCGA|ICGC|Recount)\b"
r"|accession"
r"|dataset[^.]{0,24}(search|detail|metadata)"
r"|search[^.]{0,24}(dataset|experiment|stud(y|ies)|sample|assay)"
r"|publication|literature|pubmed|citation|study[ _-]metadata",
re.I,
)
@dataclass(frozen=True)
class Tool:
"""One tool cleared for use.
Attributes:
name: ToolUniverse tool name, used to invoke it.
category: Config file it came from, minus the ``_tools.json`` suffix.
description: Upstream description, shown to the agent.
"""
name: str
category: str
description: str
def is_compliant(name: str, description: str) -> bool:
"""Whether a tool may be exposed, on name and description alone.
Pure so it can be tested directly and reused at both listing and call time. A tool is
compliant only if neither field matches `FORBIDDEN_PATTERN`; the description matters
as much as the name, because `ADA_get_standards_section` reveals nothing until read.
"""
return not FORBIDDEN_PATTERN.search(f"{name} {description or ''}")
def _data_dir() -> Path | None:
"""Directory holding ToolUniverse's tool definitions, or None if not installed."""
try:
import tooluniverse # noqa: PLC0415
except ImportError:
return None
path = Path(tooluniverse.__file__).parent / "data"
return path if path.is_dir() else None
@lru_cache(maxsize=1)
def allowed_tools() -> tuple[Tool, ...]:
"""Every ToolUniverse tool that passes both layers.
Returns:
Compliant tools, sorted by name. Empty when ToolUniverse is not installed, so a
caller degrades to shell-only rather than failing.
"""
data = _data_dir()
if data is None:
return ()
out: list[Tool] = []
for path in sorted(data.glob("*_tools.json")):
category = path.name[: -len("_tools.json")]
if category not in ALLOWED_CATEGORIES:
continue
try:
entries = json.loads(path.read_text(errors="replace"))
except (OSError, json.JSONDecodeError):
continue
if not isinstance(entries, list):
continue
for entry in entries:
if not isinstance(entry, dict):
continue
name = entry.get("name", "")
desc = entry.get("description") or ""
if name and is_compliant(name, desc):
out.append(Tool(name, category, desc.strip()))
return tuple(sorted(out, key=lambda t: t.name))
@lru_cache(maxsize=1)
def _by_name() -> dict[str, Tool]:
return {t.name: t for t in allowed_tools()}
class ToolNotPermitted(RuntimeError):
"""Raised when a caller names a tool outside the compliant set."""
def check_permitted(name: str) -> Tool:
"""Resolve a tool name, refusing anything not cleared.
Enforced at call time on purpose. Filtering the *listing* only would still let an
agent invoke `GEO_get_dataset_details` by naming it, and the agent writes its own
commands.
Raises:
ToolNotPermitted: If the name is unknown or outside the compliant set.
"""
tool = _by_name().get(name)
if tool is None:
raise ToolNotPermitted(
f"{name!r} is not in the permitted tool set. This benchmark forbids "
f"identifying the source dataset; sequence, gene and structure annotation "
f"tools are available via `biotool list`.")
return tool
def call_tool(name: str, arguments: dict) -> object:
"""Invoke a permitted ToolUniverse tool.
Args:
name: Tool name, which must be in the compliant set.
arguments: Tool arguments, passed through unchanged.
Returns:
Whatever ToolUniverse returns.
Raises:
ToolNotPermitted: If the tool is not cleared.
RuntimeError: If ToolUniverse is unavailable.
"""
check_permitted(name)
try:
from tooluniverse import ToolUniverse # noqa: PLC0415
except ImportError as exc: # pragma: no cover - environment-dependent
raise RuntimeError("tooluniverse is not installed") from exc
engine = _engine()
return engine.run({"name": name, "arguments": arguments})
@lru_cache(maxsize=1)
def _engine():
"""Load ToolUniverse once. Startup is seconds, so it must not be per-call."""
from tooluniverse import ToolUniverse # noqa: PLC0415
tu = ToolUniverse()
tu.load_tools()
return tu
def describe(limit: int = 40) -> str:
"""Render the permitted tools for an agent prompt, grouped by category."""
tools = allowed_tools()
if not tools:
return "(no structured tools available; use the shell)"
lines = [f"{len(tools)} tools are available via `biotool call <name> '<json args>'`.",
"Dataset, accession and literature lookups are NOT available: this benchmark "
"requires you to solve the problem from the data you were given.", ""]
by_cat: dict[str, list[Tool]] = {}
for tool in tools:
by_cat.setdefault(tool.category, []).append(tool)
for cat, group in sorted(by_cat.items()):
lines.append(f"[{cat}] " + ", ".join(t.name for t in group[:limit]))
return "\n".join(lines)