Skip to content
72 changes: 72 additions & 0 deletions app/nullius/catalogue/benchmarks/medagentbench/benchmark.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
{
"key": "medagentbench",
"title": "MedAgentBench",
"category": "Healthcare",
"domain": "Clinical tasks in an electronic health record: look up patients, record vitals, order tests and drugs.",
"scoring": "Answers and orders",
"harness": [
"standard",
"harbor"
],
"origin": "official",
"good_to_know": [
"10 task categories, 30 tasks each in v2 and 10 each in v1.",
"A message is one GET, POST or FINISH and nothing else: any other text ends the task as failed.",
"An order is graded from its POST message; the server never receives it."
],
"upstream_limitations": [
"The published schema gives a drug order's route as an object; the grader accepts only text (IV, oral).",
"A task whose FINISH message contains the word POST fails.",
"The grader is a file on Box, outside the repository."
],
"datasets": [
{
"key": "v2",
"title": "v2",
"tasks": 300,
"official": "https://github.com/stanfordmlgroup/MedAgentBench",
"source": "Harbor registry",
"registry": "medagentbench@1.0",
"hub": "",
"verifier": "The authors' grader: the answer against the record, and each order's payload.",
"notes": "The authors' default."
},
{
"key": "v1",
"title": "v1",
"tasks": 100,
"official": "https://github.com/stanfordmlgroup/MedAgentBench",
"source": "GitHub",
"registry": "",
"hub": "",
"verifier": "The authors' grader: the answer against the record, and each order's payload.",
"notes": "The first release."
}
],
"report": {
"sources": [
"medagentbench"
]
},
"citation": "@article{jiang2025medagentbench,\n title={MedAgentBench: A Virtual EHR Environment to Benchmark Medical LLM Agents},\n author={Jiang, Yixing and Black, Kameron C and Geng, Gloria and Park, Danny and Zou, James and Ng, Andrew Y and Chen, Jonathan H},\n journal={NEJM AI},\n pages={AIdbp2500144},\n year={2025},\n publisher={Massachusetts Medical Society},\n url={https://ai.nejm.org/doi/full/10.1056/AIdbp2500144}\n}",
"citation_source": "https://github.com/stanfordmlgroup/MedAgentBench",
"task_count": 300,
"evidence": [
{
"label": "Ended by",
"path": "status"
},
{
"label": "Result",
"path": "result"
},
{
"label": "Reads",
"path": "gets"
},
{
"label": "Orders",
"path": "posts"
}
]
}
198 changes: 198 additions & 0 deletions app/nullius/catalogue/benchmarks/medagentbench/driver.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
"""MedAgentBench's driver for the Nullius standard: the authors' code at the pinned commit, imported.

units - the data file's ids
setup - the authors' task loop (``MedAgentBench.start_sample``) started on the
unit, with its own ``Session``; the prompt is its first message
turn - the agent's message handed to that loop, through the session's
controller as the upstream's task worker does; its answer is the next
message
answer - the original: the authors' ``HTTPAgent``, from their configuration, in
the same loop
score - the authors' ``eval`` and their ``refsol.py`` (Box, by its digest), on
what ``calculate_overall`` grades: an output with a result
oracle - the reference answers of Harbor's adapter, said through the same loop

Ours: the thread the loop runs in, the FHIR server's container (``fhir.py``).
"""
import asyncio
import copy
import importlib
import importlib.machinery
import importlib.util
import json
import os
import sys
import threading
import types
from pathlib import Path

PROTOCOL, sys.stdout = sys.stdout, sys.stderr # the upstream prints: stdout is the protocol's
UP = os.environ["NULLIUS_UPSTREAM"]
sys.path.insert(0, UP)
for name in ("src.client", "src.client.agents"): # without their __init__, which import FastChat and torch
sys.modules[name] = types.ModuleType(name)
sys.modules[name].__path__ = [os.path.join(UP, *name.split("."))]

import fhir
from nullius.standard.protocols.jsonl import serve
from src.configs import ConfigLoader
from src.server.task import Session
from src.typings import AgentContextLimitException, AgentOutput, AgentOutputStatus, InstanceFactory, SampleStatus, TaskOutput

TASK = "medagentbench-std"
WAIT = 600 # one answer of the loop: a GET at most
STATE, SERVER = {}, {}


def _module(name, path):
spec = importlib.util.spec_from_loader(name, importlib.machinery.SourceFileLoader(name, path)) # a download has no .py
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
spec.loader.exec_module(module)
return module


def config():
c = ConfigLoader().load_from(os.path.join(UP, "configs/tasks/task_assembly.yaml"))[TASK]
p = dict(c["parameters"], data_file=os.environ["NULLIUS_DATASET"])
p["func_file"] = os.path.join(UP, p["func_file"])
if os.environ.get("NULLIUS_OPTION_MAX_ROUND"):
p["max_round"] = int(os.environ["NULLIUS_OPTION_MAX_ROUND"])
return dict(c, parameters=p)


def task():
"""The authors' task, once its FHIR server answers."""
if "task" not in SERVER:
c = config()
base = c["parameters"]["fhir_api_base"]
_module("src.server.tasks.medagentbench.refsol", os.environ["NULLIUS_FILE_REFSOL"])
utils = importlib.import_module("src.server.tasks.medagentbench.utils")
SERVER.update(base=base, up=lambda: utils.verify_fhir_server(base))
SERVER["holder"] = fhir.start(SERVER["up"])
SERVER["task"] = InstanceFactory(**c).create()
return SERVER["task"]


def index(unit):
rows = json.loads(Path(os.environ["NULLIUS_DATASET"]).read_text())
return next(i for i, r in enumerate(rows) if r["id"] == unit)


class Sample:
"""One task in the authors' loop, in a thread of its own."""

def __init__(self, unit):
self.task, self.index = task(), index(unit)
self.loop = asyncio.new_event_loop()
threading.Thread(target=self._run, daemon=True).start()
asyncio.run_coroutine_threadsafe(self._start(), self.loop).result(WAIT)
self.output = self._pull(None)

def _run(self):
asyncio.set_event_loop(self.loop)
self.loop.run_forever()

async def _start(self):
self.session = Session() # its locks belong to this loop
self.running = self.loop.create_task(self._sample())

async def _sample(self):
out = await self.task.start_sample(self.index, self.session)
await self.session.controller.env_finish(
TaskOutput(index=self.index, status=out.status, result=out.result, history=self.session.history))

def _pull(self, said):
async def pull():
return await self.session.controller.agent_pull(said)
return asyncio.run_coroutine_threadsafe(pull(), self.loop).result(WAIT)

@property
def over(self):
return self.output.status != SampleStatus.RUNNING

def say(self, content=None, **kw):
self.output = self._pull(AgentOutput(content=content, **kw))

def close(self):
self.loop.call_soon_threadsafe(self.loop.stop)


def units(dataset, setup=None):
return {"units": [r["id"] for r in json.loads(Path(os.environ["NULLIUS_DATASET"]).read_text())]}


def setup(unit, dir):
for s in STATE.values():
s.close()
STATE.clear()
s = STATE[unit] = Sample(unit)
return {"prompt": s.output.history[-1].content}


def turn(unit, dir, transcript, **_):
s = STATE[unit]
if not s.over:
s.say(transcript[-1].get("text") or "")
return {"done": True} if s.over else {"message": s.output.history[-1].content}


def answer(unit, dir, setup, model, base_url, key, **_):
if setup != "original":
raise ValueError(f"MedAgentBench has no {setup} setup")
globals()["setup"](unit, dir) # a setup's unit is sent no setup
s = STATE[unit]
c = ConfigLoader().load_from(os.path.join(UP, "configs/agents/api_agents.yaml"))["gpt-4o-mini"]
p = copy.deepcopy(c["parameters"])
p["url"] = base_url.rstrip("/") + "/chat/completions"
p["headers"]["Authorization"] = "Bearer " + key
p["body"]["model"] = model
for name, kind in (("temperature", float), ("max_tokens", int)):
value = os.environ.get("NULLIUS_OPTION_" + name.upper())
if value == "default":
p["body"].pop(name)
elif value:
p["body"][name] = kind(value)
agent = InstanceFactory(module="src.client.agents.http_agent.HTTPAgent", parameters=p).create()
while not s.over:
try:
s.say(agent.inference([h.dict() for h in s.output.history]))
except AgentContextLimitException:
s.say(status=AgentOutputStatus.AGENT_CONTEXT_LIMIT)
said = [h.content for h in s.output.history if h.role == "agent"]
return {"answer": said[-1] if said else ""}


def score(unit, dir, transcript, answer, **_):
s = STATE[unit]
out = s.output
grade = importlib.import_module("src.server.tasks.medagentbench.eval").eval
passed = False
if s.over and out.result is not None:
if not SERVER["up"]():
raise RuntimeError("VerifierError: the FHIR server does not answer")
passed = grade(s.task.data[s.index], out, SERVER["base"]) is True
if not passed and not SERVER["up"]():
raise RuntimeError("VerifierError: the FHIR server does not answer")
said = [h.content.strip() for h in out.history if h.role == "agent"]
return {"reward": float(passed), "passed": passed,
"detail": {"category": unit.split("_")[0], "status": out.status.value if s.over else "no answer",
"result": out.result, "steps": len(said), "steps_limit": s.task.max_round,
"gets": sum(m.startswith("GET") for m in said), "posts": sum(m.startswith("POST") for m in said)}}


def oracle(unit, dir):
s = STATE[unit]
sys.modules.setdefault("refsol_pkg", types.ModuleType("refsol_pkg")).refsol = \
sys.modules["src.server.tasks.medagentbench.refsol"]
adapter = _module("medagentbench_logic", os.environ["NULLIUS_FILE_REFERENCE"])
case = s.task.data[s.index]
said = adapter.run_oracle({"task_id": unit, "eval_MRN": case.get("eval_MRN"), "sol": case.get("sol"),
"fhir_api_base": SERVER["base"]}, Path(dir) / ".reference.json")
for m in [h["content"] for h in said["history"] if h["role"] == "agent"] + [f"FINISH({json.dumps(said['result'])})"]:
s.say(m)
return {"answer": m}


if __name__ == "__main__":
serve({"units": units, "setup": setup, "turn": turn, "answer": answer, "score": score, "oracle": oracle}, PROTOCOL)
116 changes: 116 additions & 0 deletions app/nullius/catalogue/benchmarks/medagentbench/fhir.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
"""The benchmark's FHIR server, the authors' image as published, one per machine.

Upstream runs one server for every task, read only: a POST is never sent to it.
Drivers share it: each has a holder process with a shared lock, which ends with
its driver however that ends, and the last one removes the container.

The server listens on a free port of 127.0.0.1. A connection the driver opens
to localhost:8080, the authors' address, goes there; any other address goes
where upstream sends it.

python3 fhir.py hold FD: until stdin closes, then let go."""
import fcntl
import os
import subprocess
import sys
import time

IMAGE = "jyxsu6/medagentbench@sha256:3fb83d7ed71c5476f9eb6212bd440a909ef7505922bbc757dc488a8fc0701966"
NAME = f"nullius-medagentbench-fhir-{os.getuid()}"
LOCK = f"/tmp/{NAME}"
READY_SECONDS = 420
GONE_SECONDS = 1800 # a busy daemon can take minutes to remove the server's written layer


def _open(path):
return os.open(path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600)


def _docker(*args, seconds=120):
said = subprocess.run(["docker", *args], capture_output=True, text=True, timeout=seconds, stdin=subprocess.DEVNULL)
if said.returncode:
raise RuntimeError(f"docker {args[0]}: {(said.stderr or said.stdout).strip()[-300:]}")
return said.stdout.strip()


def _address():
"""The running server's host:port, else None."""
try:
if _docker("inspect", "-f", "{{.State.Running}} {{.Config.Image}}", NAME) == f"true {IMAGE}":
return _docker("port", NAME, "8080/tcp").splitlines()[0]
except RuntimeError:
pass
return None


def _remove():
"""The container gone, waited for: a run under its name before then is refused."""
ends = time.monotonic() + GONE_SECONDS
while subprocess.run(["docker", "inspect", NAME], capture_output=True, timeout=120).returncode == 0:
subprocess.run(["docker", "rm", "-f", NAME], capture_output=True, timeout=GONE_SECONDS)
if time.monotonic() > ends:
raise RuntimeError(f"the last FHIR server was not removed in {GONE_SECONDS} s: docker rm -f {NAME}")
time.sleep(2)


def _route(address):
"""Connections to localhost:8080 reach ``address``: requests', which the upstream's GETs use."""
from urllib3.util import connection
host, port = address.rsplit(":", 1)
opened = getattr(connection.create_connection, "opened", connection.create_connection)

def create_connection(where, *args, **kwargs):
if where[0] in ("localhost", "127.0.0.1") and int(where[1]) == 8080:
where = (host, int(port))
return opened(where, *args, **kwargs)
create_connection.opened = opened
connection.create_connection = create_connection


def start(ready):
"""Start the server unless it runs, wait until ``ready()``, and hold it."""
gate = _open(LOCK + ".gate")
try:
fcntl.flock(gate, fcntl.LOCK_EX)
users = _open(LOCK + ".users")
fcntl.flock(users, fcntl.LOCK_SH)
try:
holder = subprocess.Popen([sys.executable, "-I", os.path.abspath(__file__), "hold", str(users)],
stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
start_new_session=True, pass_fds=[users])
finally:
os.close(users)
address = _address()
if address is None:
_remove()
_docker("run", "-d", "--name", NAME, "-p", "127.0.0.1::8080", IMAGE, seconds=3600)
address = _address()
if address is None:
raise RuntimeError("the FHIR server's container ended as it started")
for name in ("no_proxy", "NO_PROXY"): # never this machine's proxy
hosts = [h for h in os.environ.get(name, "").split(",") if h]
os.environ[name] = ",".join(hosts + [h for h in ("localhost", "127.0.0.1") if h not in hosts])
_route(address)
ends = time.monotonic() + READY_SECONDS
while not ready():
if time.monotonic() > ends:
raise RuntimeError(f"the FHIR server was not ready in {READY_SECONDS} s: docker logs {NAME}")
time.sleep(2)
return holder
finally:
os.close(gate)


def hold(users):
sys.stdin.buffer.read()
gate = _open(LOCK + ".gate")
fcntl.flock(gate, fcntl.LOCK_EX)
try:
fcntl.flock(users, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
return
_remove()


if __name__ == "__main__":
hold(int(sys.argv[2]))
Loading