diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
new file mode 100644
index 00000000..f5cd4d4f
--- /dev/null
+++ b/.github/workflows/publish.yml
@@ -0,0 +1,47 @@
+name: Publish to PyPI
+on:
+ workflow_dispatch:
+ release:
+ types: [created]
+
+permissions:
+ contents: read
+
+jobs:
+ test:
+ uses: ./.github/workflows/pytest.yml
+
+ deploy:
+ runs-on: ubuntu-latest
+ environment:
+ name: ${{ github.event_name == 'workflow_dispatch' && 'testpypi' || 'release' }}
+ url: ${{ github.event_name == 'workflow_dispatch' && 'https://test.pypi.org/p/medarc-verifiers' || 'https://pypi.org/p/medarc-verifiers' }}
+ permissions:
+ id-token: write
+ needs: test
+
+ steps:
+ - name: Checkout Code
+ uses: actions/checkout@v4
+
+ - name: Install Python and uv with caching
+ uses: astral-sh/setup-uv@v7
+ with:
+ version: ">=0.10.4,<0.11.0"
+ python-version: 3.13
+ enable-cache: true
+ cache-dependency-glob: "pyproject.toml"
+
+ - name: Install optimi
+ run: uv sync --group cpu
+
+ - name: Build
+ run: uv build
+
+ - name: Publish to PyPI
+ if: github.event_name == 'release'
+ run: uv publish
+
+ - name: Publish to Test PyPI
+ if: github.event_name == 'workflow_dispatch'
+ run: uv publish --publish-url https://test.pypi.org/legacy/
\ No newline at end of file
diff --git a/.github/workflows/pytest.yml b/.github/workflows/pytest.yml
new file mode 100644
index 00000000..55598245
--- /dev/null
+++ b/.github/workflows/pytest.yml
@@ -0,0 +1,47 @@
+name: CI
+on:
+ workflow_call:
+ workflow_dispatch:
+ push:
+ branches: [main]
+ paths:
+ - 'medarc_verifiers/**'
+ - '!medarc_verifiers/orchestrate/**'
+ - 'tests/**'
+ - '!tests/test_orchestrate/**'
+ pull_request:
+ paths:
+ - 'medarc_verifiers/**'
+ - '!medarc_verifiers/orchestrate/**'
+ - 'tests/**'
+ - '!tests/test_orchestrate/**'
+
+jobs:
+ test:
+ runs-on: ubuntu-latest
+
+ steps:
+ - name: Checkout Code
+ uses: actions/checkout@v4
+
+ - name: Install Python and uv with caching
+ uses: astral-sh/setup-uv@v7
+ with:
+ version: ">=0.10.4,<0.11.0"
+ python-version: 3.13
+ enable-cache: true
+ cache-dependency-glob: "pyproject.toml"
+
+ - name: Install optimi
+ run: uv sync
+
+ - name: Ruff Check
+ id: ruff
+ run: |
+ uv run ruff check --output-format=github .
+ uv run ruff format --check .
+
+ - name: Run Tests
+ id: pytest
+ run: |
+ uv run pytest -v --ignore=tests/test_orchestrate
diff --git a/environments/aci_bench/pyproject.toml b/environments/aci_bench/pyproject.toml
index c97e0579..37a7afb2 100644
--- a/environments/aci_bench/pyproject.toml
+++ b/environments/aci_bench/pyproject.toml
@@ -7,7 +7,7 @@ version = "0.1.0"
requires-python = ">=3.11"
dependencies = [
"verifiers>=0.1.5.post0",
- "medarc_verifiers>=0.1.0",
+ "medarc-verifiers>=0.1.0",
]
[tool.prime.environment]
@@ -18,6 +18,3 @@ visibility = "PUBLIC"
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
-
-[tool.uv.sources]
-medarc_verifiers = { git = "https://github.com/MedARC-AI/med-lm-envs" }
\ No newline at end of file
diff --git a/environments/careqa/pyproject.toml b/environments/careqa/pyproject.toml
index a875b5ff..96fade82 100644
--- a/environments/careqa/pyproject.toml
+++ b/environments/careqa/pyproject.toml
@@ -7,7 +7,7 @@ requires-python = ">=3.11"
dependencies = [
"verifiers>=0.1.4",
"datasets>=2.13.0",
- "medarc_verifiers>=0.1.0",
+ "medarc-verifiers>=0.1.0",
]
[tool.prime.environment]
@@ -21,6 +21,3 @@ build-backend = "hatchling.build"
[tool.hatch.build]
include = ["careqa.py"]
-
-[tool.uv.sources]
-medarc_verifiers = { git = "https://github.com/MedARC-AI/med-lm-envs" }
\ No newline at end of file
diff --git a/environments/head_qa/pyproject.toml b/environments/head_qa/pyproject.toml
index 473cebea..92de48c8 100644
--- a/environments/head_qa/pyproject.toml
+++ b/environments/head_qa/pyproject.toml
@@ -16,8 +16,6 @@ dependencies = [
requires = ["hatchling"]
build-backend = "hatchling.build"
-[tool.uv.sources]
-medarc_verifiers = { git = "https://github.com/MedARC-AI/med-lm-envs" }
[tool.prime.environment]
loader = "head_qa:load_environment"
diff --git a/environments/head_qa_v2/pyproject.toml b/environments/head_qa_v2/pyproject.toml
index 52ec6c88..fb1691d7 100644
--- a/environments/head_qa_v2/pyproject.toml
+++ b/environments/head_qa_v2/pyproject.toml
@@ -16,8 +16,6 @@ dependencies = [
requires = ["hatchling"]
build-backend = "hatchling.build"
-[tool.uv.sources]
-medarc_verifiers = { git = "https://github.com/MedARC-AI/med-lm-envs" }
[tool.prime.environment]
loader = "head_qa_v2:load_environment"
diff --git a/environments/longhealth/pyproject.toml b/environments/longhealth/pyproject.toml
index d83a5d85..2bdc2274 100644
--- a/environments/longhealth/pyproject.toml
+++ b/environments/longhealth/pyproject.toml
@@ -9,15 +9,13 @@ authors = [
]
dependencies = [
"verifiers>=0.1.5.post0",
- "medarc_verifiers>=0.1.0",
+ "medarc-verifiers>=0.1.0",
]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
-[tool.uv.sources]
-medarc_verifiers = { git = "https://github.com/MedARC-AI/med-lm-envs" }
[tool.prime.environment]
loader = "longhealth:load_environment"
diff --git a/environments/m_arc/pyproject.toml b/environments/m_arc/pyproject.toml
index 5704569b..33cdf09e 100644
--- a/environments/m_arc/pyproject.toml
+++ b/environments/m_arc/pyproject.toml
@@ -6,7 +6,7 @@ version = "0.1.0"
requires-python = ">=3.11"
dependencies = [
"verifiers>=0.1.3.post0",
- "medarc_verifiers>=0.1.0",
+ "medarc-verifiers>=0.1.0",
]
[tool.prime.environment]
@@ -21,5 +21,3 @@ build-backend = "hatchling.build"
[tool.hatch.build]
include = ["m_arc.py"]
-[tool.uv.sources]
-medarc_verifiers = { git = "https://github.com/MedARC-AI/med-lm-envs" }
diff --git a/environments/med_dialog/pyproject.toml b/environments/med_dialog/pyproject.toml
index 0186517f..92389a26 100644
--- a/environments/med_dialog/pyproject.toml
+++ b/environments/med_dialog/pyproject.toml
@@ -8,12 +8,9 @@ dependencies = [
"verifiers>=0.1.4",
"datasets>=4.1.1",
"openai>=2.1.0",
- "medarc_verifiers>=0.1.0",
+ "medarc-verifiers>=0.1.0",
]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
-
-[tool.uv.sources]
-medarc_verifiers = { git = "https://github.com/MedARC-AI/med-lm-envs" }
\ No newline at end of file
diff --git a/environments/med_halt/pyproject.toml b/environments/med_halt/pyproject.toml
index e93d07a5..957c8772 100644
--- a/environments/med_halt/pyproject.toml
+++ b/environments/med_halt/pyproject.toml
@@ -7,7 +7,7 @@ requires-python = ">=3.11"
dependencies = [
"datasets>=4.0.0",
"verifiers>=0.1.2.post0",
- "medarc_verifiers>=0.1.0",
+ "medarc-verifiers>=0.1.0",
]
[tool.prime.environment]
@@ -22,5 +22,3 @@ build-backend = "hatchling.build"
[tool.hatch.build]
include = ["med_halt.py"]
-[tool.uv.sources]
-medarc_verifiers = { git = "https://github.com/MedARC-AI/med-lm-envs" }
diff --git a/environments/med_mcqa/pyproject.toml b/environments/med_mcqa/pyproject.toml
index 8b4299de..8ba8d6a3 100644
--- a/environments/med_mcqa/pyproject.toml
+++ b/environments/med_mcqa/pyproject.toml
@@ -10,15 +10,13 @@ authors = [
]
dependencies = [
"verifiers>=0.1.5.post0",
- "medarc_verifiers>=0.1.0",
+ "medarc-verifiers>=0.1.0",
]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
-[tool.uv.sources]
-medarc_verifiers = { git = "https://github.com/MedARC-AI/med-lm-envs" }
[tool.prime.environment]
loader = "med_mcqa:load_environment"
diff --git a/environments/medagentbenchv2/medagentbenchv2/_vendor/medagentbenchevals/new_refsol.py b/environments/medagentbenchv2/medagentbenchv2/_vendor/medagentbenchevals/new_refsol.py
index 64421e6f..a49f4427 100644
--- a/environments/medagentbenchv2/medagentbenchv2/_vendor/medagentbenchevals/new_refsol.py
+++ b/environments/medagentbenchv2/medagentbenchv2/_vendor/medagentbenchevals/new_refsol.py
@@ -1,9 +1,10 @@
# Lightly modified from https://github.com/ericoericochen/medagentbenchv2 (no license found in upstream repo at time of copy; copyright original authors: Eric Chen & Sam Postelnik).
+import ast
import json
-from .utils import *
-from datetime import datetime, timedelta, timezone
import re
-import ast
+from datetime import datetime, timedelta, timezone
+
+from .utils import send_get_request
def extract_now_from_context(case_data: dict):
@@ -61,15 +62,13 @@ def extract_posts(results):
for idx, i in enumerate(results.history):
# print(i)
if (i.role == "agent") and ("POST" in i.content):
- if (idx < len(results.history)) and (
- "POST request accepted" in results.history[idx + 1].content
- ):
+ if (idx < len(results.history)) and ("POST request accepted" in results.history[idx + 1].content):
try:
r = i.content
url = r.split("\n")[0][4:].strip()
payload = json.loads("\n".join(r.split("\n")[1:]))
posts.append((url, payload))
- except:
+ except Exception:
pass
return posts
@@ -118,11 +117,7 @@ def task1(case_data, results, fhir_api_base):
f"patient={case_data['eval_MRN']}&code={','.join(prior_codes)}"
f"&_count=5000&_format=json"
)
- entries = [
- e
- for e in json.loads(send_get_request(url)["data"]).get("entry", [])
- if before_cutoff(e["resource"])
- ]
+ entries = [e for e in json.loads(send_get_request(url)["data"]).get("entry", []) if before_cutoff(e["resource"])]
last_dt = None
for e in entries:
@@ -217,10 +212,7 @@ def is_heparin_5k(entry):
return ("heparin" in txt) and (("5,000" in txt) or ("5000" in txt))
# ---------- 1 · baseline active anticoagulant orders ----------
- url = (
- f"{fhir_api_base}MedicationRequest?"
- f"patient={case_data['eval_MRN']}&status=active&_count=5000&_format=json"
- )
+ url = f"{fhir_api_base}MedicationRequest?patient={case_data['eval_MRN']}&status=active&_count=5000&_format=json"
raw_entries = json.loads(send_get_request(url)["data"]).get("entry", [])
entries = [e for e in raw_entries if before_cutoff(e["resource"])]
@@ -235,15 +227,13 @@ def is_heparin_5k(entry):
creates = [
p
for p in posts
- if p[1].get("resourceType") == "MedicationRequest"
- and p[1].get("status", "").lower() == "active"
+ if p[1].get("resourceType") == "MedicationRequest" and p[1].get("status", "").lower() == "active"
]
stops = [
p
for p in posts
if p[1].get("resourceType") == "MedicationRequest"
- and p[1].get("status", "").lower()
- in {"stopped", "cancelled", "completed", "entered-in-error"}
+ and p[1].get("status", "").lower() in {"stopped", "cancelled", "completed", "entered-in-error"}
]
# ---------- 3 · branch validation --------------------------
@@ -253,10 +243,7 @@ def is_heparin_5k(entry):
if need_create:
# At least one new active heparin 5 000-unit order must appear
- if not any(
- ("heparin" in str(pl).lower()) and ("5000" in str(pl).lower())
- for _, pl in creates
- ):
+ if not any(("heparin" in str(pl).lower()) and ("5000" in str(pl).lower()) for _, pl in creates):
return False
if need_stops > 0 and not stops:
@@ -284,9 +271,6 @@ def task3(case_data, results, fhir_api_base):
• Special case: if the agent returns -1 for a window and the gold is None,
treat that as a match.
"""
- import json, ast
- from datetime import datetime, timedelta
-
# ---- 0 · constants / helpers ------------------------------------
CUTOFF = datetime.fromisoformat("2025-01-01T00:00:00+00:00")
@@ -303,10 +287,7 @@ def avg(vals):
twelve_hrs_ago = now - timedelta(hours=12)
# ---- 2 · fetch & filter observations ----------------------------
- url = (
- f"{fhir_api_base}Observation?"
- f"patient={case_data['eval_MRN']}&code=HEARTRATE&_count=5000&_format=json"
- )
+ url = f"{fhir_api_base}Observation?patient={case_data['eval_MRN']}&code=HEARTRATE&_count=5000&_format=json"
bundle = json.loads(send_get_request(url)["data"])
entries = bundle.get("entry", [])
@@ -412,14 +393,9 @@ def task4(case_data, results, fhir_api_base):
PROC_CODE = "NUR1373"
# ---------- 1 · latest catheter insertion before cut-off ----------
- proc_url = (
- f"{fhir_api_base}Procedure?"
- f"patient={case_data['eval_MRN']}&code={PROC_CODE}&_count=5000&_format=json"
- )
+ proc_url = f"{fhir_api_base}Procedure?patient={case_data['eval_MRN']}&code={PROC_CODE}&_count=5000&_format=json"
insert_entries = [
- e
- for e in json.loads(send_get_request(proc_url)["data"]).get("entry", [])
- if before_cutoff(e["resource"])
+ e for e in json.loads(send_get_request(proc_url)["data"]).get("entry", []) if before_cutoff(e["resource"])
]
last_insert = None
@@ -441,16 +417,10 @@ def task4(case_data, results, fhir_api_base):
f"&status=active&_count=5000&_format=json"
)
active_removals = [
- e
- for e in json.loads(send_get_request(sr_url)["data"]).get("entry", [])
- if before_cutoff(e["resource"])
+ e for e in json.loads(send_get_request(sr_url)["data"]).get("entry", []) if before_cutoff(e["resource"])
]
- removal_required = (
- last_insert is not None
- and NOW - last_insert > FORTY_EIGHT_H
- and not active_removals
- )
+ removal_required = last_insert is not None and NOW - last_insert > FORTY_EIGHT_H and not active_removals
# ---------- 3 · evaluate agent posts ------------------------------
posts = extract_posts(results)
@@ -502,28 +472,19 @@ def task5(case_data, results, fhir_api_base):
CT_PRIOR = ["IMGCT0491", "IMGIL0001", CT_CODE]
# ------------- 1 · verify diagnosis before cut-off -------------
- dx_url = (
- f"{fhir_api_base}Condition?"
- f"patient={case_data['eval_MRN']}&code={DX_CODE}&_count=5000&_format=json"
- )
+ dx_url = f"{fhir_api_base}Condition?patient={case_data['eval_MRN']}&code={DX_CODE}&_count=5000&_format=json"
dx_entries = [
- e
- for e in json.loads(send_get_request(dx_url)["data"]).get("entry", [])
- if before_cutoff(e["resource"])
+ e for e in json.loads(send_get_request(dx_url)["data"]).get("entry", []) if before_cutoff(e["resource"])
]
if not dx_entries:
return not check_has_post(results) # no dx → expect silence
# ------------- 2 · most-recent CT before cut-off --------------
proc_url = (
- f"{fhir_api_base}Procedure?"
- f"patient={case_data['eval_MRN']}&code={','.join(CT_PRIOR)}"
- f"&_count=5000&_format=json"
+ f"{fhir_api_base}Procedure?patient={case_data['eval_MRN']}&code={','.join(CT_PRIOR)}&_count=5000&_format=json"
)
ct_entries = [
- e
- for e in json.loads(send_get_request(proc_url)["data"]).get("entry", [])
- if before_cutoff(e["resource"])
+ e for e in json.loads(send_get_request(proc_url)["data"]).get("entry", []) if before_cutoff(e["resource"])
]
last_ct = None
@@ -589,15 +550,8 @@ def task6(case_data, results, fhir_api_base):
# ---------- helpers ----------
def fetch_obs(code):
- url = (
- f"{fhir_api_base}Observation?"
- f"patient={case_data['eval_MRN']}&code={code}&_count=5000&_format=json"
- )
- return [
- e
- for e in json.loads(send_get_request(url)["data"]).get("entry", [])
- if before_cutoff(e["resource"])
- ]
+ url = f"{fhir_api_base}Observation?patient={case_data['eval_MRN']}&code={code}&_count=5000&_format=json"
+ return [e for e in json.loads(send_get_request(url)["data"]).get("entry", []) if before_cutoff(e["resource"])]
def val_dt(entry):
v = entry["resource"]["valueQuantity"]["value"]
@@ -608,12 +562,8 @@ def val_dt(entry):
tsh_vals = [val_dt(e) for e in fetch_obs("TSH")]
ft4_vals = [val_dt(e) for e in fetch_obs("FT4")]
- last_tsh_val, last_tsh_dt = (
- max(tsh_vals, key=lambda x: x[1]) if tsh_vals else (None, None)
- )
- last_ft4_val, last_ft4_dt = (
- max(ft4_vals, key=lambda x: x[1]) if ft4_vals else (None, None)
- )
+ last_tsh_val, last_tsh_dt = max(tsh_vals, key=lambda x: x[1]) if tsh_vals else (None, None)
+ last_ft4_val, last_ft4_dt = max(ft4_vals, key=lambda x: x[1]) if ft4_vals else (None, None)
# Branch A: two high TSH values ≥30 d apart
high_dates = [d for v, d in tsh_vals if v > 10]
@@ -648,10 +598,7 @@ def ok_med(p):
)
def ok_lab(p):
- txt = (
- str(p[1].get("code", {})).lower()
- + p[1].get("code", {}).get("text", "").lower()
- )
+ txt = str(p[1].get("code", {})).lower() + p[1].get("code", {}).get("text", "").lower()
return (
p[1].get("status", "").lower() == "active"
and p[1].get("intent", "").lower() == "order"
@@ -703,24 +650,16 @@ def task7(case_data, results, fhir_api_base):
PATIENT_REF = {"reference": f"Patient/{case_data['eval_MRN']}"}
# ---------------- 1 · QTc before cut-off -------------------
- url_qt = (
- f"{fhir_api_base}Observation?"
- f"patient={case_data['eval_MRN']}&code=QTCINTERVAL"
- f"&_count=5000&_format=json"
- )
+ url_qt = f"{fhir_api_base}Observation?patient={case_data['eval_MRN']}&code=QTCINTERVAL&_count=5000&_format=json"
qt_entries = [
- e
- for e in json.loads(send_get_request(url_qt)["data"]).get("entry", [])
- if before_cutoff(e["resource"])
+ e for e in json.loads(send_get_request(url_qt)["data"]).get("entry", []) if before_cutoff(e["resource"])
]
if not qt_entries: # no baseline data → agent silent
return not check_has_post(results)
# pick the newest pre-cut-off QTc
- qt_latest = max(
- qt_entries, key=lambda e: e["resource"]["meta"].get("lastUpdated", "")
- )["resource"]
+ qt_latest = max(qt_entries, key=lambda e: e["resource"]["meta"].get("lastUpdated", ""))["resource"]
qt_val = qt_latest["valueQuantity"]["value"]
prolonged = qt_val > QT_THRESHOLD
@@ -777,10 +716,7 @@ def med_text(entry):
return entry["resource"]["medicationCodeableConcept"].get("text", "").lower()
# ---------------- 1 · active MedicationRequests ----------------
- url = (
- f"{fhir_api_base}MedicationRequest?"
- f"patient={case_data['eval_MRN']}&status=active&_count=5000&_format=json"
- )
+ url = f"{fhir_api_base}MedicationRequest?patient={case_data['eval_MRN']}&status=active&_count=5000&_format=json"
entries = json.loads(send_get_request(url)["data"]).get("entry", [])
def before_cutoff_8(entry):
@@ -790,12 +726,8 @@ def before_cutoff_8(entry):
# keep only pre-cut-off records
baseline = [e for e in entries if before_cutoff_8(e)]
- active_opioids = [
- e for e in baseline if any(w in med_text(e) for w in OPIOID_WORDS)
- ]
- active_nalox = [
- e for e in baseline if "naloxone" in med_text(e) or "narcan" in med_text(e)
- ]
+ active_opioids = [e for e in baseline if any(w in med_text(e) for w in OPIOID_WORDS)]
+ active_nalox = [e for e in baseline if "naloxone" in med_text(e) or "narcan" in med_text(e)]
needs_naloxone = bool(active_opioids) and not active_nalox
@@ -843,14 +775,9 @@ def task9(case_data, results, fhir_api_base):
PATIENT_REF = f"Patient/{case_data['eval_MRN']}"
# ---------- 1 · prior flu shots before cut-off ----------
- url = (
- f"{fhir_api_base}Procedure?"
- f"patient={case_data['eval_MRN']}&code={CPT_FLU}&_count=5000&_format=json"
- )
+ url = f"{fhir_api_base}Procedure?patient={case_data['eval_MRN']}&code={CPT_FLU}&_count=5000&_format=json"
proc_entries = [
- e
- for e in json.loads(send_get_request(url)["data"]).get("entry", [])
- if before_cutoff(e["resource"])
+ e for e in json.loads(send_get_request(url)["data"]).get("entry", []) if before_cutoff(e["resource"])
]
last_vax_dt = None
@@ -922,27 +849,20 @@ def task10(case_data, results, fhir_api_base):
PROC_CODE = "COVIDVACCINE"
# ---------------- 1 · prior COVID vaccinations (pre-cut-off) ----------------
- proc_url = (
- f"{fhir_api_base}Procedure?"
- f"patient={case_data['eval_MRN']}&code={PROC_CODE}&_count=5000&_format=json"
- )
+ proc_url = f"{fhir_api_base}Procedure?patient={case_data['eval_MRN']}&code={PROC_CODE}&_count=5000&_format=json"
proc_entries = [
- e
- for e in json.loads(send_get_request(proc_url)["data"]).get("entry", [])
- if before_cutoff(e["resource"])
+ e for e in json.loads(send_get_request(proc_url)["data"]).get("entry", []) if before_cutoff(e["resource"])
]
# MedicationRequest records containing “COVID-19 VAC”
med_url = (
- f"{fhir_api_base}MedicationRequest?"
- f"patient={case_data['eval_MRN']}&status=completed&_count=5000&_format=json"
+ f"{fhir_api_base}MedicationRequest?patient={case_data['eval_MRN']}&status=completed&_count=5000&_format=json"
)
med_entries = [
e
for e in json.loads(send_get_request(med_url)["data"]).get("entry", [])
if before_cutoff(e["resource"])
- and "covid-19 vac"
- in e["resource"]["medicationCodeableConcept"].get("text", "").lower()
+ and "covid-19 vac" in e["resource"]["medicationCodeableConcept"].get("text", "").lower()
]
# ---------------- 1b · extract dates ----------------
@@ -955,9 +875,7 @@ def extract_dt(res):
)
dates = [
- datetime.fromisoformat(dt_str)
- for e in proc_entries + med_entries
- if (dt_str := extract_dt(e["resource"]))
+ datetime.fromisoformat(dt_str) for e in proc_entries + med_entries if (dt_str := extract_dt(e["resource"]))
]
last_vax = max(dates) if dates else None
@@ -986,7 +904,5 @@ def extract_dt(res):
return False
# text/code must clearly reference a COVID vaccine / booster
- searchable = (
- str(payload.get("code", {})) + str(payload.get("medicationCodeableConcept", {}))
- ).lower()
+ searchable = (str(payload.get("code", {})) + str(payload.get("medicationCodeableConcept", {}))).lower()
return "covid" in searchable
diff --git a/environments/medagentbenchv2/medagentbenchv2/_vendor/medagentbenchevals/utils.py b/environments/medagentbenchv2/medagentbenchv2/_vendor/medagentbenchevals/utils.py
index 8e0b4d7f..cc400509 100644
--- a/environments/medagentbenchv2/medagentbenchv2/_vendor/medagentbenchevals/utils.py
+++ b/environments/medagentbenchv2/medagentbenchv2/_vendor/medagentbenchevals/utils.py
@@ -32,11 +32,7 @@ def send_get_request(url, params=None, headers=None):
response.raise_for_status() # Raises an HTTPError if the response code is 4xx or 5xx
return {
"status_code": response.status_code,
- "data": (
- response.json()
- if response.headers.get("Content-Type") == "application/json"
- else response.text
- ),
+ "data": (response.json() if response.headers.get("Content-Type") == "application/json" else response.text),
}
except Exception as e:
return {"error": str(e)}
diff --git a/environments/medagentbenchv2/medagentbenchv2/tools.py b/environments/medagentbenchv2/medagentbenchv2/tools.py
index d52b7169..9cd05ec8 100644
--- a/environments/medagentbenchv2/medagentbenchv2/tools.py
+++ b/environments/medagentbenchv2/medagentbenchv2/tools.py
@@ -13,16 +13,10 @@
class PatientSearchParams(BaseModel):
- birthdate: str | None = Field(
- default=None, description="The patient's date of birth in the format YYYY-MM-DD."
- )
+ birthdate: str | None = Field(default=None, description="The patient's date of birth in the format YYYY-MM-DD.")
family: str | None = Field(default=None, description="The patient's family (last) name.")
- given: str | None = Field(
- default=None, description="The patient's given name. May include first and middle names."
- )
- identifier: str | None = Field(
- default=None, description="The patient's identifier or Medical Record Number (MRN)."
- )
+ given: str | None = Field(default=None, description="The patient's given name. May include first and middle names.")
+ identifier: str | None = Field(default=None, description="The patient's identifier or Medical Record Number (MRN).")
class ObservationSearchParams(BaseModel):
@@ -184,9 +178,7 @@ def fhir_patient_search(
) -> dict:
"""Search for a patient via the FHIR Patient search API."""
route = f"{fhir_api_base}Patient"
- args = PatientSearchParams(
- birthdate=birthdate, family=family, given=given, identifier=identifier
- )
+ args = PatientSearchParams(birthdate=birthdate, family=family, given=given, identifier=identifier)
params = args.model_dump(exclude_none=True)
res = requests.get(route, params=params)
return res.json()
diff --git a/environments/medbullets/pyproject.toml b/environments/medbullets/pyproject.toml
index ad7d425d..af2e33b0 100644
--- a/environments/medbullets/pyproject.toml
+++ b/environments/medbullets/pyproject.toml
@@ -6,7 +6,7 @@ version = "0.1.0"
requires-python = ">=3.11"
dependencies = [
"verifiers>=0.1.3.post0",
- "medarc_verifiers>=0.1.0",
+ "medarc-verifiers>=0.1.0",
]
[tool.prime.environment]
@@ -20,6 +20,3 @@ build-backend = "hatchling.build"
[tool.hatch.build]
include = ["medbullets.py"]
-
-[tool.uv.sources]
-medarc_verifiers = { git = "https://github.com/MedARC-AI/med-lm-envs" }
\ No newline at end of file
diff --git a/environments/medcalc_bench/pyproject.toml b/environments/medcalc_bench/pyproject.toml
index 4d2e9452..3c998fad 100644
--- a/environments/medcalc_bench/pyproject.toml
+++ b/environments/medcalc_bench/pyproject.toml
@@ -9,7 +9,7 @@ dependencies = [
"datasets>=4.0.0",
"numpy>=1.26.0",
"simpleeval>=0.9.10",
- "medarc_verifiers>=0.1.0",
+ "medarc-verifiers>=0.1.0",
"RestrictedPython>=8.0",
"scipy>=1.16",
]
@@ -21,8 +21,6 @@ build-backend = "hatchling.build"
[tool.hatch.build]
include = ["medcalc_bench.py"]
-[tool.uv.sources]
-medarc_verifiers = { git = "https://github.com/MedARC-AI/med-lm-envs" }
[tool.prime.environment]
# lets Prime/vf-eval know where the loader lives in a flat repo
diff --git a/environments/medconceptsqa/pyproject.toml b/environments/medconceptsqa/pyproject.toml
index 4f0a6f38..a4768322 100644
--- a/environments/medconceptsqa/pyproject.toml
+++ b/environments/medconceptsqa/pyproject.toml
@@ -10,7 +10,7 @@ authors = [
dependencies = [
"verifiers>=0.1.5.post0",
"datasets>=4.1.1",
- "medarc_verifiers>=0.1.0",
+ "medarc-verifiers>=0.1.0",
]
[tool.prime.environment]
@@ -21,6 +21,3 @@ visibility = "PUBLIC"
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
-
-[tool.uv.sources]
-medarc_verifiers = { git = "https://github.com/MedARC-AI/med-lm-envs" }
\ No newline at end of file
diff --git a/environments/medexqa/pyproject.toml b/environments/medexqa/pyproject.toml
index 8bc24a10..bbcdd4d6 100644
--- a/environments/medexqa/pyproject.toml
+++ b/environments/medexqa/pyproject.toml
@@ -11,7 +11,7 @@ dependencies = [
"datasets>=4.0.0",
"verifiers>=0.1.2.post0",
"pandas>=2.0.0",
- "medarc_verifiers>=0.1.0",
+ "medarc-verifiers>=0.1.0",
]
[dependency-groups]
@@ -29,8 +29,6 @@ build-backend = "hatchling.build"
[tool.hatch.build]
include = ["medexqa.py"]
-[tool.uv.sources]
-medarc_verifiers = { git = "https://github.com/MedARC-AI/med-lm-envs" }
[tool.prime.environment]
# lets Prime/vf-eval know where the loader lives in a flat repo
diff --git a/environments/medicationqa/pyproject.toml b/environments/medicationqa/pyproject.toml
index 4aea7af2..06f523ee 100644
--- a/environments/medicationqa/pyproject.toml
+++ b/environments/medicationqa/pyproject.toml
@@ -7,7 +7,7 @@ requires-python = ">=3.11"
dependencies = [
"verifiers>=0.1.4",
"requests",
- "medarc_verifiers>=0.1.0",
+ "medarc-verifiers>=0.1.0",
"openpyxl"
]
@@ -15,8 +15,6 @@ dependencies = [
requires = ["hatchling"]
build-backend = "hatchling.build"
-[tool.uv.sources]
-medarc_verifiers = { git = "https://github.com/MedARC-AI/med-lm-envs" }
[tool.prime.environment]
loader = "medicationqa:load_environment"
diff --git a/environments/medqa/pyproject.toml b/environments/medqa/pyproject.toml
index fb3e913a..8940627d 100644
--- a/environments/medqa/pyproject.toml
+++ b/environments/medqa/pyproject.toml
@@ -7,7 +7,7 @@ requires-python = ">=3.11"
dependencies = [
"datasets>=4.0.0",
"verifiers>=0.1.2.post0",
- "medarc_verifiers>=0.1.0",
+ "medarc-verifiers>=0.1.0",
]
[build-system]
@@ -17,8 +17,6 @@ build-backend = "hatchling.build"
[tool.hatch.build]
include = ["medqa.py"]
-[tool.uv.sources]
-medarc_verifiers = { git = "https://github.com/MedARC-AI/med-lm-envs" }
[tool.prime.environment]
# lets Prime/vf-eval know where the loader lives in a flat repo
diff --git a/environments/medrbench/medrbench/medrbench.py b/environments/medrbench/medrbench/medrbench.py
index 5f3d388d..06e02cc3 100644
--- a/environments/medrbench/medrbench/medrbench.py
+++ b/environments/medrbench/medrbench/medrbench.py
@@ -548,7 +548,9 @@ async def judge_rubric_reward(completion: Messages, info: Info, state: State, **
rubric.add_reward_func(judge_rubric_reward, weight=1.0)
- patient_agent_api_key = default_judge_api_key(patient_agent_base_url) if patient_agent_api_key is None else patient_agent_api_key
+ patient_agent_api_key = (
+ default_judge_api_key(patient_agent_base_url) if patient_agent_api_key is None else patient_agent_api_key
+ )
_, patient_default_headers = judge_sampling_args_and_headers(patient_agent_model, patient_agent_base_url)
patient_agent_client = AsyncOpenAI(
base_url=patient_agent_base_url,
diff --git a/environments/medrbench/pyproject.toml b/environments/medrbench/pyproject.toml
index 4f7f9e4b..ac12160d 100644
--- a/environments/medrbench/pyproject.toml
+++ b/environments/medrbench/pyproject.toml
@@ -9,7 +9,7 @@ authors = [
]
dependencies = [
"verifiers>=0.1.5.post0",
- "medarc_verifiers>=0.1.0",
+ "medarc-verifiers>=0.1.0",
"requests>=2.28.0",
]
@@ -26,5 +26,3 @@ tags = ["medical", "diagnosis", "treatment", "rare-disease", "llm-judge", "singl
requires = ["hatchling"]
build-backend = "hatchling.build"
-[tool.uv.sources]
-medarc_verifiers = { git = "https://github.com/MedARC-AI/med-lm-envs" }
diff --git a/environments/medxpertqa/pyproject.toml b/environments/medxpertqa/pyproject.toml
index 0c142a43..e1f5bafa 100644
--- a/environments/medxpertqa/pyproject.toml
+++ b/environments/medxpertqa/pyproject.toml
@@ -7,7 +7,7 @@ requires-python = ">=3.11"
dependencies = [
"verifiers>=0.1.4",
"datasets>=4.0.0",
- "medarc_verifiers>=0.1.0",
+ "medarc-verifiers>=0.1.0",
]
[build-system]
@@ -17,8 +17,6 @@ build-backend = "hatchling.build"
[tool.hatch.build]
include = ["medxpertqa.py"]
-[tool.uv.sources]
-medarc_verifiers = { git = "https://github.com/MedARC-AI/med-lm-envs" }
[tool.prime.environment]
# lets Prime/vf-eval know where the loader lives in a flat repo
diff --git a/environments/meqsum/meqsum.py b/environments/meqsum/meqsum.py
index 13cfe94a..aa355106 100644
--- a/environments/meqsum/meqsum.py
+++ b/environments/meqsum/meqsum.py
@@ -222,13 +222,11 @@ def _map(ex: dict) -> dict:
final_system_prompt = system_prompt or ("Summarize the patient health query into one question of 15 words or less.")
# Initialize automatic metrics if enabled
- bleu_metric = None
rouge_metric = None
bertscore_metric = None
if compute_auto_metrics:
try:
- bleu_metric = evaluate.load("bleu")
rouge_metric = evaluate.load("rouge")
bertscore_metric = evaluate.load("bertscore")
except Exception as e:
diff --git a/environments/meqsum/pyproject.toml b/environments/meqsum/pyproject.toml
index 2e9f694c..cfef2e00 100644
--- a/environments/meqsum/pyproject.toml
+++ b/environments/meqsum/pyproject.toml
@@ -7,7 +7,7 @@ requires-python = ">=3.11"
dependencies = [
"verifiers>=0.1.4",
"datasets",
- "medarc_verifiers>=0.1.0"
+ "medarc-verifiers>=0.1.0"
]
[project.optional-dependencies]
@@ -22,8 +22,6 @@ metrics = [
requires = ["hatchling"]
build-backend = "hatchling.build"
-[tool.uv.sources]
-medarc_verifiers = { git = "https://github.com/MedARC-AI/med-lm-envs" }
[tool.prime.environment]
loader = "meqsum:load_environment"
diff --git a/environments/metamedqa/pyproject.toml b/environments/metamedqa/pyproject.toml
index a542ee79..a8ec8cdb 100644
--- a/environments/metamedqa/pyproject.toml
+++ b/environments/metamedqa/pyproject.toml
@@ -10,7 +10,7 @@ authors = [
dependencies = [
"verifiers>=0.1.2.post0", # same major/minor line as your working env
"datasets>=4.0.0",
- "medarc_verifiers>=0.1.0",
+ "medarc-verifiers>=0.1.0",
]
[build-system]
@@ -20,8 +20,6 @@ build-backend = "hatchling.build"
[tool.hatch.build]
include = ["metamedqa.py"]
-[tool.uv.sources]
-medarc_verifiers = { git = "https://github.com/MedARC-AI/med-lm-envs" }
[tool.prime.environment]
# lets Prime/vf-eval know where the loader lives in a flat repo
diff --git a/environments/mmlu_pro_health/pyproject.toml b/environments/mmlu_pro_health/pyproject.toml
index f6704c9d..2a6f1b2c 100644
--- a/environments/mmlu_pro_health/pyproject.toml
+++ b/environments/mmlu_pro_health/pyproject.toml
@@ -6,7 +6,7 @@ version = "0.1.0"
requires-python = ">=3.11"
dependencies = [
"verifiers>=0.1.3.post0",
- "medarc_verifiers>=0.1.0",
+ "medarc-verifiers>=0.1.0",
]
[tool.prime.environment]
@@ -21,5 +21,3 @@ build-backend = "hatchling.build"
[tool.hatch.build]
include = ["mmlu_pro_health.py"]
-[tool.uv.sources]
-medarc_verifiers = { git = "https://github.com/MedARC-AI/med-lm-envs" }
diff --git a/environments/mtsamples_procedures/pyproject.toml b/environments/mtsamples_procedures/pyproject.toml
index 559ee414..e9a119fd 100644
--- a/environments/mtsamples_procedures/pyproject.toml
+++ b/environments/mtsamples_procedures/pyproject.toml
@@ -8,13 +8,10 @@ dependencies = [
"verifiers>=0.1.4",
"datasets>=4.1.1",
"openai>=2.1.0",
- "medarc_verifiers>=0.1.0",
+ "medarc-verifiers>=0.1.0",
"requests>=2.31.0",
]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
-
-[tool.uv.sources]
-medarc_verifiers = { git = "https://github.com/MedARC-AI/med-lm-envs" }
\ No newline at end of file
diff --git a/environments/mtsamples_replicate/pyproject.toml b/environments/mtsamples_replicate/pyproject.toml
index 82cb9d28..5c854dd7 100644
--- a/environments/mtsamples_replicate/pyproject.toml
+++ b/environments/mtsamples_replicate/pyproject.toml
@@ -15,7 +15,7 @@ dependencies = [
"verifiers>=0.1.4",
"datasets>=4.1.1",
"openai>=2.1.0",
- "medarc_verifiers>=0.1.0",
+ "medarc-verifiers>=0.1.0",
"requests>=2.31.0",
]
@@ -23,5 +23,3 @@ dependencies = [
requires = ["hatchling"]
build-backend = "hatchling.build"
-[tool.uv.sources]
-medarc_verifiers = { git = "https://github.com/MedARC-AI/med-lm-envs" }
diff --git a/environments/pubhealthbench/pyproject.toml b/environments/pubhealthbench/pyproject.toml
index d8a46ab5..c283fd19 100644
--- a/environments/pubhealthbench/pyproject.toml
+++ b/environments/pubhealthbench/pyproject.toml
@@ -7,7 +7,7 @@ requires-python = ">=3.11"
dependencies = [
"datasets>=4.0.0",
"verifiers>=0.1.2.post0",
- "medarc_verifiers>=0.1.0",
+ "medarc-verifiers>=0.1.0",
]
[build-system]
@@ -17,8 +17,6 @@ build-backend = "hatchling.build"
[tool.hatch.build]
include = ["pubhealthbench.py"]
-[tool.uv.sources]
-medarc_verifiers = { git = "https://github.com/MedARC-AI/med-lm-envs" }
[tool.prime.environment]
loader = "pubhealthbench:load_environment"
diff --git a/environments/pubmedqa/pyproject.toml b/environments/pubmedqa/pyproject.toml
index f6acc279..97ad4026 100644
--- a/environments/pubmedqa/pyproject.toml
+++ b/environments/pubmedqa/pyproject.toml
@@ -10,7 +10,7 @@ authors = [
dependencies = [
"verifiers>=0.1.3.post0",
"datasets>= 4.0.0",
- "medarc_verifiers>=0.1.0",
+ "medarc-verifiers>=0.1.0",
]
[project.optional-dependencies]
@@ -25,6 +25,3 @@ build-backend = "hatchling.build"
[tool.hatch.build]
include = ["pubmedqa.py"]
-
-[tool.uv.sources]
-medarc_verifiers = { git = "https://github.com/MedARC-AI/med-lm-envs" }
\ No newline at end of file
diff --git a/environments/pubmedqa/test_pubmedqa.py b/environments/pubmedqa/test_pubmedqa.py
index cbd36f12..ba33f164 100644
--- a/environments/pubmedqa/test_pubmedqa.py
+++ b/environments/pubmedqa/test_pubmedqa.py
@@ -1,15 +1,18 @@
import argparse
-import os
+import importlib
import json
+import os
+
from pubmedqa import load_environment
from openai.types.chat import ChatCompletion, ChatCompletionMessage
from openai.types.chat.chat_completion import Choice
-import random
+
class MockClient:
def __init__(self):
self.chat = MockChat()
+
class MockChat:
def __init__(self):
self.completions = MockCompletions()
@@ -18,39 +21,28 @@ def __init__(self):
class MockCompletions:
def __init__(self):
self.contents = [
- r'C',
- r'\\boxed{A }',
- r'\\boxed{BF}',
- r'\\boxed{no}',
- r' dadada my answer is \\boxed{A}',
- r' dadada my answer is \\boxed{yes}'
+ r"C",
+ r"\\boxed{A }",
+ r"\\boxed{BF}",
+ r"\\boxed{no}",
+ r" dadada my answer is \\boxed{A}",
+ r" dadada my answer is \\boxed{yes}",
]
- self.index = 0;
-
+ self.index = 0
async def create(self, **kwargs):
- model = kwargs.get('model', 'unknown')
+ model = kwargs.get("model", "unknown")
content = self.contents[self.index % len(self.contents)]
self.index += 1
- message = ChatCompletionMessage(
- role='assistant',
- content=content
- )
- choice = Choice(
- index=0,
- message=message,
- finish_reason='stop'
- )
+ message = ChatCompletionMessage(role="assistant", content=content)
+ choice = Choice(index=0, message=message, finish_reason="stop")
return ChatCompletion(
- id='mock-completion',
- object='chat.completion',
- created=1234567890,
- model=model,
- choices=[choice]
+ id="mock-completion", object="chat.completion", created=1234567890, model=model, choices=[choice]
)
+
'''
def submit_results(env_name, model_name, results):
"""callable via: #submit_results("pubmedqa", model_name, results)"""
@@ -76,67 +68,67 @@ def submit_results(env_name, model_name, results):
def main():
- parser = argparse.ArgumentParser(description='Run PubMedQA evaluation')
- parser.add_argument('--no-mock', action='store_true', help='Use real Mistral API instead of mock client')
- parser.add_argument('--think', action='store_true', help='Use thinking')
- parser.add_argument('--model', default='mock-model', help='Model name to use')
- parser.add_argument('--num_examples', type=int, default=5, help='Number of examples to evaluate (-1 for full benchmark)')
-
+ parser = argparse.ArgumentParser(description="Run PubMedQA evaluation")
+ parser.add_argument("--no-mock", action="store_true", help="Use real Mistral API instead of mock client")
+ parser.add_argument("--think", action="store_true", help="Use thinking")
+ parser.add_argument("--model", default="mock-model", help="Model name to use")
+ parser.add_argument(
+ "--num_examples", type=int, default=5, help="Number of examples to evaluate (-1 for full benchmark)"
+ )
+
args, _ = parser.parse_known_args()
if args.no_mock:
# Use real Mistral client
from openai import AsyncOpenAI
-
+
try:
- import api_tokens # Load API keys
+ importlib.import_module("api_tokens") # Load API keys
except ImportError:
pass # API keys not available, will use environment variables
- client = AsyncOpenAI(
- api_key=os.getenv("MISTRAL_API_KEY"),
- base_url="https://api.mistral.ai/v1"
- )
+ client = AsyncOpenAI(api_key=os.getenv("MISTRAL_API_KEY"), base_url="https://api.mistral.ai/v1")
print(f"Using real Mistral API with model: {args.model}")
else:
# Use mock client
client = MockClient()
print(f"Using mock client with model: {args.model}")
-
+
# conduct evaluation
env = load_environment(use_think=args.think)
- #print(len(env.eval_dataset), env.eval_dataset[0])
-
+ # print(len(env.eval_dataset), env.eval_dataset[0])
+
# Handle full benchmark case
results = env.evaluate(client, model=args.model, num_examples=args.num_examples)
-
+
# Create outputs directory and file
- os.makedirs('outputs', exist_ok=True)
+ os.makedirs("outputs", exist_ok=True)
if args.num_examples == -1:
- output_file = f'outputs/{args.model}_full.jsonl'
+ output_file = f"outputs/{args.model}_full.jsonl"
else:
- output_file = f'outputs/{args.model}_nsamples_{args.num_examples}.jsonl'
-
+ output_file = f"outputs/{args.model}_nsamples_{args.num_examples}.jsonl"
+
# Write results to JSONL file
- with open(output_file, 'w') as f:
- #print(dir(results))
+ with open(output_file, "w") as f:
+ # print(dir(results))
for i in range(len(results.answer)):
result_item = {}
- result_item["question"] = env.eval_dataset[i]['question']
+ result_item["question"] = env.eval_dataset[i]["question"]
result_item["ground_truth"] = results.answer[i]
- result_item["long_answer"] = env.eval_dataset[i]['long_answer']
+ result_item["long_answer"] = env.eval_dataset[i]["long_answer"]
result_item["reward"] = results.reward[i]
- result_item["completion"] = results.completion[i][0]['content']
- result_item["full_prompt"] = env.eval_dataset[i]['prompt']
- f.write(json.dumps(result_item) + '\n')
-
+ result_item["completion"] = results.completion[i][0]["content"]
+ result_item["full_prompt"] = env.eval_dataset[i]["prompt"]
+ f.write(json.dumps(result_item) + "\n")
+
# Calculate and display summary stats
rewards = results.reward
avg_reward = sum(rewards) / len(rewards)
success_rate = sum(1 for r in rewards if r == 1.0) / len(rewards)
-
+
print(f"Results saved to: {output_file}")
print(f"Summary: {len(rewards)} examples, avg reward: {avg_reward:.3f}, success rate: {success_rate:.3f}")
+
if __name__ == "__main__":
main()
diff --git a/environments/sctpublic/pyproject.toml b/environments/sctpublic/pyproject.toml
index c01dc52b..4859b494 100644
--- a/environments/sctpublic/pyproject.toml
+++ b/environments/sctpublic/pyproject.toml
@@ -15,8 +15,6 @@ dependencies = [
requires = ["hatchling"]
build-backend = "hatchling.build"
-[tool.uv.sources]
-medarc_verifiers = { git = "https://github.com/MedARC-AI/med-lm-envs" }
[tool.prime.environment]
loader = "sctpublic:load_environment"
diff --git a/environments/supergpqa_medicine/pyproject.toml b/environments/supergpqa_medicine/pyproject.toml
index cd4b333e..db8b268a 100644
--- a/environments/supergpqa_medicine/pyproject.toml
+++ b/environments/supergpqa_medicine/pyproject.toml
@@ -6,7 +6,7 @@ version = "0.1.0"
requires-python = ">=3.11"
dependencies = [
"verifiers>=0.1.3.post0",
- "medarc_verifiers>=0.1.0",
+ "medarc-verifiers>=0.1.0",
]
[tool.prime.environment]
@@ -21,5 +21,3 @@ build-backend = "hatchling.build"
[tool.hatch.build]
include = ["supergpqa_medicine.py"]
-[tool.uv.sources]
-medarc_verifiers = { git = "https://github.com/MedARC-AI/med-lm-envs" }
diff --git a/pyproject.toml b/pyproject.toml
index 1445b116..e77652b1 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,7 +1,7 @@
[project]
name = "medarc-verifiers"
version = "0.1.0"
-description = "A collection of MedARC utilites for the verifiers package"
+description = "A collection of MedARC utilites for Prime Intellect's verifiers package"
readme = "README.md"
requires-python = ">=3.11"
license = { file = "LICENSE" }
@@ -46,7 +46,7 @@ extend-exclude = ["docs"]
src = ["medarc_verifiers"]
[build-system]
-requires = ["uv_build>=0.9.0,<0.10.0"]
+requires = ["uv_build>=0.10.4,<0.11.0"]
build-backend = "uv_build"
[tool.uv.build-backend]
diff --git a/scripts/mmlu_pro_health_transform.py b/scripts/mmlu_pro_health_transform.py
deleted file mode 100644
index 3dff8043..00000000
--- a/scripts/mmlu_pro_health_transform.py
+++ /dev/null
@@ -1,222 +0,0 @@
-#!/usr/bin/env python
-"""
-One-off helper to:
- - load the MMLU-Pro dev split and grab the five health examples
- - show their original (list-based) option format
- - load mkieffer/MMLU-Pro-Health validation examples for comparison
- - convert the MMLU-Pro examples into the dict-based option format used by mkieffer/MMLU-Pro-Health
-
-The script prints the before/after records so you can verify the mapping.
-"""
-
-from __future__ import annotations
-
-import argparse
-import json
-import os
-import string
-from typing import Any, Dict, Iterable, List, Tuple
-
-from datasets import Dataset, load_dataset
-from datasets.utils.logging import disable_progress_bar
-from huggingface_hub import HfApi
-
-disable_progress_bar()
-
-
-DATASET_MMLU_PRO = "TIGER-Lab/MMLU-Pro"
-DATASET_HEALTH = "mkieffer/MMLU-Pro-Health"
-
-
-def _first_available_split(dataset: str, candidates: Iterable[str]):
- """Try each split name in order until one loads."""
- last_err = None
- for split in candidates:
- try:
- ds = load_dataset(dataset, split=split, download_mode="reuse_cache_if_exists")
- return split, ds
- except Exception as exc: # pragma: no cover - this is a best-effort utility
- last_err = exc
- raise RuntimeError(f"Could not load dataset '{dataset}' with splits {list(candidates)}") from last_err
-
-
-def _normalize_options(row: Dict[str, Any]) -> Tuple[Dict[str, str], List[str]]:
- """
- Take the raw options (either list or dict) from MMLU-Pro and return:
- - dict keyed by letters
- - ordered list of option texts (mirrors the incoming order for diagnostics)
- """
- raw = row.get("options") or row.get("choices") or row.get("options_list") or []
- def _keep(text: str | None) -> bool:
- return bool(text) and str(text).strip().lower() not in {"n/a", "na", "none"}
-
- if isinstance(raw, dict):
- # Already keyed by letters
- ordered = [raw[k] for k in sorted(raw.keys()) if _keep(raw[k])]
- return {k: v for k, v in raw.items() if _keep(v)}, ordered
- if not isinstance(raw, list):
- return {}, []
- letters = string.ascii_uppercase
- mapped = {letters[i]: opt for i, opt in enumerate(raw) if _keep(opt)}
- return mapped, [opt for opt in raw if _keep(opt)]
-
-
-def _normalize_answer(row: Dict[str, Any], options: Dict[str, str]) -> str | None:
- """
- Normalize the answer into a letter.
- Handles letters, integer indices, or digit strings.
- """
- ans = row.get("answer") or row.get("label") or row.get("correct_choice")
- letters = string.ascii_uppercase
- if ans is None:
- return None
- if isinstance(ans, str):
- ans_str = ans.strip()
- if len(ans_str) == 1 and ans_str.upper() in letters:
- return ans_str.upper()
- if ans_str.isdigit():
- idx = int(ans_str)
- return letters[idx] if idx < len(letters) else None
- if isinstance(ans, int):
- return letters[ans] if ans < len(letters) else None
- # If options already dict and answer matches a key, keep it
- if isinstance(ans, str) and ans in options:
- return ans
- return None
-
-
-def _filter_health(ds):
- """Filter only on the category field containing 'health'."""
- health_rows = []
- for row in ds:
- category = row.get("category")
- if isinstance(category, str) and "health" in category.lower():
- health_rows.append(row)
- return health_rows
-
-
-def _print_section(title: str, rows: List[Dict[str, Any]]):
- print(f"\n=== {title} ===")
- print(json.dumps(rows, indent=2, ensure_ascii=False))
-
-
-def _parse_args() -> argparse.Namespace:
- parser = argparse.ArgumentParser(description="Transform MMLU-Pro health examples and optionally push to HF Hub.")
- parser.add_argument(
- "--push-to-hub",
- type=str,
- default=None,
- help="Optional hub dataset repo id to push the transformed health validation examples (e.g., your-username/MMLU-Pro-Health-Transformed).",
- )
- parser.add_argument(
- "--token",
- type=str,
- default=os.getenv("HF_TOKEN") or os.getenv("HUGGINGFACE_TOKEN"),
- help="HF token for pushing. Defaults to HF_TOKEN or HUGGINGFACE_TOKEN env var.",
- )
- parser.add_argument(
- "--cache-dir",
- type=str,
- default=os.getenv("HF_DATASETS_CACHE"),
- help="Optional cache dir override for datasets loading (passed to HF_DATASETS_CACHE).",
- )
- return parser.parse_args()
-
-
-def main():
- args = _parse_args()
-
- if args.cache_dir:
- os.environ["HF_DATASETS_CACHE"] = args.cache_dir
-
- # Load MMLU-Pro dev (or validation if dev is unavailable) and grab health rows
- split_name, mmlu_dev = _first_available_split(DATASET_MMLU_PRO, ["dev", "validation"])
- health_rows = _filter_health(mmlu_dev)
- health_rows = health_rows[:5] # only keep the first five
-
- # Load mkieffer/MMLU-Pro-Health validation few-shot examples
- _, mkieffer_val = _first_available_split(DATASET_HEALTH, ["validation"])
- mkieffer_preview = [mkieffer_val[i] for i in range(min(5, len(mkieffer_val)))]
-
- # Show the raw originals
- _print_section(
- f"Original {DATASET_MMLU_PRO} {split_name} health rows (first 5, raw list-based options)",
- [
- {
- "question": r.get("question"),
- "options": r.get("options") or r.get("choices"),
- "answer": r.get("answer"),
- "subject": r.get("subject") or r.get("category"),
- "extra_keys": {k: r[k] for k in r.keys() if k not in {"question", "options", "choices", "answer", "subject", "category"}},
- }
- for r in health_rows
- ],
- )
-
- # Show the mkieffer format for reference
- _print_section(
- f"{DATASET_HEALTH} validation preview (dict-based options)",
- [
- {
- "question": r.get("question"),
- "options": r.get("options"),
- "answer": r.get("answer"),
- "cot_content": r.get("cot_content", None),
- }
- for r in mkieffer_preview
- ],
- )
-
- # Transform originals into dict-based options
- transformed: List[Dict[str, Any]] = []
- for row in health_rows:
- options_dict, original_order = _normalize_options(row)
- answer_letter = _normalize_answer(row, options_dict)
- transformed.append(
- {
- "question": row.get("question"),
- "options": options_dict,
- "answer": answer_letter,
- "answer_text": options_dict.get(answer_letter),
- "cot_content": row.get("cot_content"),
- "original_order": original_order,
- }
- )
-
- _print_section(f"Transformed {DATASET_MMLU_PRO} health rows (dict-based options)", transformed)
-
- if args.push_to_hub:
- if not args.token:
- raise SystemExit("HF token required to push. Provide --token or set HF_TOKEN/HUGGINGFACE_TOKEN.")
- ds = Dataset.from_list(
- [
- {
- "question": row["question"],
- "options": row["options"],
- "answer": row["answer"],
- "cot_content": row.get("cot_content", ""),
- }
- for row in transformed
- ]
- )
- api = HfApi(token=args.token)
- repo_id = args.push_to_hub
- print(f"\nEnsuring dataset repo exists: {repo_id}")
- api.create_repo(repo_id, repo_type="dataset", exist_ok=True, token=args.token)
- print(f"Pushing transformed dataset to HF Hub at {repo_id} ...")
- ds.push_to_hub(repo_id, token=args.token, split="validation")
- print("Push complete.")
-
- print("\nDone.")
-
-
-if __name__ == "__main__":
- # Default to online to allow downloading/pushing; users can set HF_DATASETS_OFFLINE=1 if needed.
- os.environ.setdefault("HF_DATASETS_OFFLINE", "0")
-
- # Point HF datasets cache to a local, writable path to avoid lock conflicts with shared caches
- local_cache = os.path.join(os.getcwd(), ".cache", "hf_datasets")
- os.makedirs(local_cache, exist_ok=True)
- os.environ.setdefault("HF_DATASETS_CACHE", local_cache)
-
- main()
diff --git a/tests/test_cli/test_manifest_tools.py b/tests/test_cli/test_manifest_tools.py
index dc7ad8fd..3a813b1d 100644
--- a/tests/test_cli/test_manifest_tools.py
+++ b/tests/test_cli/test_manifest_tools.py
@@ -1,8 +1,6 @@
from __future__ import annotations
import json
-import subprocess
-import sys
from pathlib import Path
from medarc_verifiers.cli._manifest_tools import validate_manifests_in_runs
@@ -51,61 +49,3 @@ def test_validate_manifests_reports_broken_paths(tmp_path: Path) -> None:
assert result.manifests_checked == 1
assert result.jobs_checked == 1
assert any(issue.kind == "warning" and "fallback" in issue.message.lower() for issue in result.issues)
-
-
-def test_convert_manifest_v2_to_v3_script_rewrites_paths_and_drops_redundant_fields(tmp_path: Path) -> None:
- run_dir = tmp_path / "runs" / "raw" / "demo-run"
- job_dir = run_dir / "job-1"
- _write_json(job_dir / "metadata.json", {"env_id": "demo"})
- (job_dir / "results.jsonl").write_text('{"example_id": 1}\n{"example_id": 2}\n', encoding="utf-8")
-
- src = run_dir / "run_manifest.json"
- payload = {
- "version": 2,
- "run_id": "demo-run",
- "name": "demo",
- "config_source": "cfg.yaml",
- "config_checksum": "x",
- "created_at": "2024-01-01T00:00:00Z",
- "updated_at": "2024-01-01T00:00:00Z",
- "models": {},
- "env_templates": {},
- "jobs": [
- {
- "job_id": "job-1",
- "job_name": "job-1",
- "model_id": "m",
- "env_id": "e",
- "env_template_id": "e:t",
- "env_variant_id": "e",
- "env_args": {},
- "results_dir": "job-1",
- "status": "completed",
- }
- ],
- "summary": {"total": 1, "completed": 1, "pending": 0, "failed": 0, "running": 0, "skipped": 0},
- }
- _write_json(src, payload)
-
- out = run_dir / "run_manifest.v3.json"
- subprocess.check_call(
- [
- sys.executable,
- "scripts/convert_manifest_v2_to_v3.py",
- str(src),
- "--output",
- str(out),
- ],
- cwd=Path(__file__).resolve().parents[2],
- )
- migrated = json.loads(out.read_text(encoding="utf-8"))
- assert migrated["version"] == 3
- assert migrated["artifacts_root"] == "."
- job = migrated["jobs"][0]
- assert job["results_relpath"] == "job-1/results.jsonl"
- assert job["metadata_relpath"] == "job-1/metadata.json"
- assert "summary_relpath" not in job
- assert "results_dir" not in job
- assert "artifacts_checksum" not in job
- assert "artifacts" not in job
- assert job["row_count"] == 2
diff --git a/tests/test_orchestrate_cli_validation.py b/tests/test_orchestrate/test_orchestrate_cli_validation.py
similarity index 100%
rename from tests/test_orchestrate_cli_validation.py
rename to tests/test_orchestrate/test_orchestrate_cli_validation.py
diff --git a/tests/test_orchestrate_config.py b/tests/test_orchestrate/test_orchestrate_config.py
similarity index 100%
rename from tests/test_orchestrate_config.py
rename to tests/test_orchestrate/test_orchestrate_config.py
diff --git a/tests/test_orchestrate_dashboard.py b/tests/test_orchestrate/test_orchestrate_dashboard.py
similarity index 100%
rename from tests/test_orchestrate_dashboard.py
rename to tests/test_orchestrate/test_orchestrate_dashboard.py
diff --git a/tests/test_orchestrate_docker_vllm.py b/tests/test_orchestrate/test_orchestrate_docker_vllm.py
similarity index 100%
rename from tests/test_orchestrate_docker_vllm.py
rename to tests/test_orchestrate/test_orchestrate_docker_vllm.py
diff --git a/tests/test_orchestrate_parallel_launch.py b/tests/test_orchestrate/test_orchestrate_parallel_launch.py
similarity index 100%
rename from tests/test_orchestrate_parallel_launch.py
rename to tests/test_orchestrate/test_orchestrate_parallel_launch.py
diff --git a/tests/test_orchestrate_scheduler_backfill.py b/tests/test_orchestrate/test_orchestrate_scheduler_backfill.py
similarity index 100%
rename from tests/test_orchestrate_scheduler_backfill.py
rename to tests/test_orchestrate/test_orchestrate_scheduler_backfill.py
diff --git a/tests/test_orchestrate_scheduler_cancellation.py b/tests/test_orchestrate/test_orchestrate_scheduler_cancellation.py
similarity index 100%
rename from tests/test_orchestrate_scheduler_cancellation.py
rename to tests/test_orchestrate/test_orchestrate_scheduler_cancellation.py
diff --git a/tests/test_orchestrate_scheduler_retry_on_release.py b/tests/test_orchestrate/test_orchestrate_scheduler_retry_on_release.py
similarity index 100%
rename from tests/test_orchestrate_scheduler_retry_on_release.py
rename to tests/test_orchestrate/test_orchestrate_scheduler_retry_on_release.py
diff --git a/tests/test_orchestrate_shutdown.py b/tests/test_orchestrate/test_orchestrate_shutdown.py
similarity index 100%
rename from tests/test_orchestrate_shutdown.py
rename to tests/test_orchestrate/test_orchestrate_shutdown.py
diff --git a/tests/test_orchestrate_task_paths.py b/tests/test_orchestrate/test_orchestrate_task_paths.py
similarity index 100%
rename from tests/test_orchestrate_task_paths.py
rename to tests/test_orchestrate/test_orchestrate_task_paths.py