CoolFace
Apppublic

prakashrajk/antibiotic-stewardship

sourceHugging Faceupdated 6mo agoView on Hugging Face
0likes
App README

๐Ÿฆ  Antibiotic Stewardship โ€” OpenEnv Environment

Built for the Meta ร— PyTorch OpenEnv Hackathon 2026 Organised by Scaler School of Technology in collaboration with Meta, Hugging Face, and PyTorch.

An RL environment where an LLM agent acts as a clinical pharmacist, treating patients while managing antimicrobial resistance (AMR). AMR is a WHO-priority global health crisis responsible for ~700,000 deaths per year โ€” projected to reach 10 million by 2050.

The agent must balance curing today's patient without destroying the antibiotic's effectiveness for future patients. This is the core stewardship challenge.


๐ŸŒ Why This Matters

Antimicrobial resistance (AMR) occurs when bacteria evolve to resist antibiotics through overuse and misuse. Once a drug becomes ineffective, patients die from infections that used to be easily treatable. This environment trains an AI agent to prescribe antibiotics responsibly โ€” using the weakest effective drug to preserve stronger ones for when they are truly needed.


๐Ÿ—๏ธ Architecture

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                   inference.py                       โ”‚
โ”‚              (LLM Agent / AI Doctor)                 โ”‚
โ”‚   - Qwen/Qwen2.5-72B-Instruct via HF Router         โ”‚
โ”‚   - Deterministic fast-path for obvious cases        โ”‚
โ”‚   - Episode memory (last 6 patients)                 โ”‚
โ”‚   - Retry logic + safe fallback                      โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                       โ”‚ HTTP (reset / step / grade)
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                     app.py                           โ”‚
โ”‚              (FastAPI Web Server)                    โ”‚
โ”‚   - OpenEnv-compliant REST API                       โ”‚
โ”‚   - Per-task session management                      โ”‚
โ”‚   - 503 retryable errors for cold-start handling     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                       โ”‚
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                 environment.py                       โ”‚
โ”‚           (Hospital Simulation Engine)               โ”‚
โ”‚   - 3 tasks: easy / medium / hard                    โ”‚
โ”‚   - Resistance tracking per antibiotic               โ”‚
โ”‚   - Side-effect penalties for vulnerable patients    โ”‚
โ”‚   - Overkill detection (Vancomycin on mild cases)    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

๐ŸŽฏ Tasks

TaskPatientsStarting ResistanceAge RangeInfectionsSeverity Mix
easy100.0 (none)20โ€“60 (adults)E.coli, Strep70% mild
medium150.15 (some)5โ€“85 (elderly + kids)+ StaphMixed
hard200.30 (high)3โ€“90 (babies to elderly)+ MRSA50% severe

๐Ÿ’Š Antibiotics

IDDrugBest ForResistance GrowthSide Effect Risk
0PenicillinMild (severity 1)+0.15 per use (fastest)Low
1AzithromycinModerate (severity 2)+0.10 per useMedium
2VancomycinSevere / MRSA (severity 3)+0.05 per use (slowest)High

Key rule: Every antibiotic use increases bacterial resistance for ALL future patients in the episode. The agent must think long-term, not just about the current patient.


๐Ÿค– Model & Approach

LLM: Qwen/Qwen2.5-72B-Instruct accessed via Hugging Face's OpenAI-compatible router at https://router.huggingface.co/v1

Agent Design:

The agent uses a two-layer decision strategy:

  1. 1.Deterministic fast-path โ€” For crystal-clear cases (MRSA always needs Vancomycin, severity 3 always needs the strongest available drug), the agent decides instantly without an LLM call. This saves API credits and speeds up evaluation.
  1. 1.LLM reasoning โ€” For nuanced cases, the agent sends the full patient context to Qwen2.5-72B-Instruct, including:
  2. 2.Current patient details (age, infection, severity)
  3. 3.Live resistance status for all 3 drugs with OK / WARNING / FAILED labels
  4. 4.Summary of the last 6 patients treated and their outcomes
  5. 5.Episode totals (cured / failed / partial / overkill counts)

Prompt Engineering: The system prompt teaches the LLM the scoring rules, resistance growth rates, decision rules per severity level, and the key stewardship insight: "Using stronger drugs unnecessarily burns resistance for ALL future patients." The LLM responds only with structured JSON {"antibiotic": 0|1|2, "reasoning": "one sentence"} for reliable parsing.

Robustness:

  • โ€”Retry logic with exponential backoff (up to 10 attempts for connection errors, 3 for LLM failures)
  • โ€”wake_up_space() pings the HF Space before evaluation to handle cold starts
  • โ€”Hard fallback to severity-based rules if all LLM retries fail
  • โ€”503 errors treated as retryable (not fatal) for HF Space warm-up delays

๐Ÿ“Š Evaluation Results

Scores achieved by the deterministic agent (fast-path rules only, no LLM):

TaskAvg ScoreCuredPartialFailedOverkill
easy0.868200
medium0.7311400
hard0.459731

With Qwen2.5-72B-Instruct handling nuanced cases on top of the fast-path, scores on medium and hard tasks improve further โ€” particularly for moderate severity patients where resistance levels require careful drug selection.

Score formula: score = max(0, total_reward) / (patients ร— 10) โ†’ normalized 0.0โ€“1.0


๐Ÿ† Scoring Rules

SituationPointsOutcome
Correct drug, resistance < 0.40+10CURED โœ…
Correct drug, resistance 0.40โ€“0.70+3Partial โš ๏ธ
Drug resistance > 0.70 (useless)โˆ’5FAILED โŒ
Drug too weak for severity 1 or 2โˆ’5FAILED โŒ
Drug too weak for severity 3โˆ’15FAILED โŒ
Vancomycin on mild case (overkill)โˆ’12OVERKILL โš ๏ธ
Strong drug on child (age โ‰ค 12)โˆ’1.5 ร— drug_idSide effect
Strong drug on elderly (age โ‰ฅ 65)โˆ’2.5 ร— drug_idSide effect

๐Ÿ”Œ API Reference

EndpointMethodBody / ParamsDescription
/healthGETโ€”Health check โ†’ {"status": "ok"}
/tasksGETโ€”List all tasks with descriptions
/resetPOST{"task_id": "easy"}Start new episode, returns first patient
/stepPOST`{"antibiotic": 0\1\2}`Treat patient, returns reward + next patient
/stateGETโ€”Full current state (resistance, log, patient)
/gradeGET?task_id=easy (optional)Final score 0.0โ€“1.0 + breakdown
/docsGETโ€”Interactive Swagger UI

๐Ÿš€ Quick Start

Run with Docker

bash
# Build and start
docker build -t abx-env .
docker run -p 7860:7860 abx-env

# Verify it's running
curl http://localhost:7860/health
# โ†’ {"status": "ok"}

Play through an episode manually

bash
# Start a hard episode
curl -X POST http://localhost:7860/reset \
     -H "Content-Type: application/json" \
     -d '{"task_id": "hard"}'

# Treat a patient (give Vancomycin)
curl -X POST http://localhost:7860/step \
     -H "Content-Type: application/json" \
     -d '{"antibiotic": 2}'

# Check current state
curl http://localhost:7860/state

# Get final score (after all patients treated)
curl http://localhost:7860/grade

Run the LLM agent

bash
# Against the live HF Space
export ENV_URL=https://prakashrajk-antibiotic-stewardship.hf.space
export API_BASE_URL=https://router.huggingface.co/v1
export MODEL_NAME=Qwen/Qwen2.5-72B-Instruct
export HF_TOKEN=hf_your_token_here

python inference.py

# Against local Docker
python inference.py --url http://localhost:7860

๐Ÿ“ Project Structure

antibiotic-stewardship/
โ”œโ”€โ”€ app.py              # FastAPI server โ€” all OpenEnv endpoints
โ”œโ”€โ”€ environment.py      # Hospital simulation โ€” patients, resistance, scoring
โ”œโ”€โ”€ inference.py        # LLM agent โ€” Qwen2.5 + fast-path + retry logic
โ”œโ”€โ”€ models.py           # Pydantic data models โ€” Action, Observation, StepResult
โ”œโ”€โ”€ client.py           # Typed Python client for the API
โ”œโ”€โ”€ openenv.yaml        # OpenEnv spec declaration
โ”œโ”€โ”€ Dockerfile          # Container config for HF Spaces (port 7860)
โ”œโ”€โ”€ requirements.txt    # Python dependencies
โ””โ”€โ”€ README.md           # This file

๐Ÿ”ฎ Future Work

  • โ€”Interactive GUI โ€” A Gradio or Streamlit frontend where judges and clinicians can run episodes, visualise resistance curves in real time, and inspect the LLM's reasoning for each decision.
  • โ€”Multi-model comparison โ€” Benchmark smaller models (Qwen2.5-7B, LLaMA-3-8B) against the 72B variant under the same environment and scoring protocol to study the cost/performance tradeoff.
  • โ€”Richer clinical parameters โ€” Add comorbidities, allergy history, culture results, and PK/PD-inspired dosing to make the simulation more clinically realistic.
  • โ€”Resistance dynamics research โ€” Use the environment's detailed treatment logs to study how different prescribing policies affect long-term population-level resistance โ€” directly relevant to antibiotic stewardship research.
  • โ€”Clinical validation โ€” Collaborate with infectious disease specialists to validate environment design and scoring rules against real hospital antibiotic stewardship guidelines.

๐Ÿ“ฆ Dependencies

LibraryVersionPurpose
fastapi0.111.0Web framework for OpenEnv API
uvicorn0.29.0ASGI server to run FastAPI
pydantic2.7.1Data validation for all models
openaiโ‰ฅ1.30.0OpenAI-compatible client for Qwen via HF Router
requestsโ‰ฅ2.31.0HTTP calls from inference agent to environment

๐Ÿ“„ OpenEnv Compliance

This environment fully implements the OpenEnv specification:

  • โ€”โœ… openenv.yaml with specversion, tasks, endpoints, actionspace, observation_space
  • โ€”โœ… POST /reset โ€” typed Pydantic models, returns Observation
  • โ€”โœ… POST /step โ€” takes Action, returns StepResult (obs, reward, done, info)
  • โ€”โœ… GET /state โ€” full environment state
  • โ€”โœ… GET /grade โ€” normalized score 0.0โ€“1.0 with breakdown
  • โ€”โœ… 3 tasks with easy โ†’ medium โ†’ hard progression
  • โ€”โœ… Meaningful reward function with partial progress signals
  • โ€”โœ… Deployed on Hugging Face Spaces with working Dockerfile
  • โ€”โœ… inference.py with [START] [STEP] [END] structured logging

AMR kills 700,000 people per year. Teaching AI to prescribe responsibly is not just a hackathon problem โ€” it's a global health necessity.