CoolFace
Apppublic

bandanagupta-03/opd-queue-env

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

๐Ÿฅ Healthcare OPD Queue Optimization Environment

OpenEnv Hackathon Submission ยท Real-world hospital simulation ยท 3 tasks ยท RL-ready

![OpenEnv](https://openenv.ai) ![Python](https://python.org) ![FastAPI](https://fastapi.tiangolo.com) ![HuggingFace](https://huggingface.co/spaces)


๐ŸŽฏ Project Overview

The OPD Queue Optimization Environment simulates a hospital Outpatient Department under realistic operating conditions. An AI agent must intelligently assign arriving patients to available doctors, balancing:

  • โ€”Urgency โ€” critical patients must be seen quickly
  • โ€”Fairness โ€” lower-severity patients shouldn't wait indefinitely
  • โ€”Efficiency โ€” doctors must not sit idle when patients are waiting
  • โ€”Resilience โ€” surge events (accidents, mass casualties) must be handled gracefully

This environment was designed to benchmark AI planning agents in healthcare resource allocation โ€” a domain where good decisions have direct human impact.


๐ŸŒ Real-World Motivation

Every day, millions of patients visit hospital OPDs worldwide. Inefficient queue management leads to:

  • โ€”Preventable deterioration of critical patients
  • โ€”Long wait times causing patient distress
  • โ€”Doctor burnout from uneven workload distribution
  • โ€”Wasted medical capacity during off-peak hours

AI agents trained in this environment can be adapted to assist real triage nurses and queue managers, augmenting human decision-making with data-driven recommendations.


๐Ÿ—๏ธ Architecture

opd_queue_env/
โ”‚
โ”œโ”€โ”€ envs/opd_env/
โ”‚   โ”œโ”€โ”€ __init__.py        โ† Public API exports
โ”‚   โ”œโ”€โ”€ env.py             โ† Core OPDQueueEnv (reset, step, state)
โ”‚   โ””โ”€โ”€ models.py          โ† Pydantic models: Observation, Action, Reward
โ”‚
โ”œโ”€โ”€ tasks/
โ”‚   โ””โ”€โ”€ __init__.py        โ† Task definitions + deterministic graders
โ”‚
โ”œโ”€โ”€ scripts/
โ”‚   โ”œโ”€โ”€ run_baseline.py    โ† Rule-based baseline agent
โ”‚   โ””โ”€โ”€ train_rl_agent.py  โ† Q-Learning training + evaluation
โ”‚
โ”œโ”€โ”€ inference.py           โ† OpenAI-driven inference (mandatory format)
โ”œโ”€โ”€ app.py                 โ† FastAPI server (POST /reset, POST /step)
โ”œโ”€โ”€ openenv.yaml           โ† OpenEnv metadata spec
โ”œโ”€โ”€ Dockerfile             โ† Docker build (python:3.9-slim, port 7860)
โ”œโ”€โ”€ requirements.txt       โ† Python dependencies
โ””โ”€โ”€ README.md              โ† This file

Runtime Flow

Patient Arrives โ”€โ”€โ–บ Queue โ”€โ”€โ–บ Agent Decision โ”€โ”€โ–บ Doctor Assignment
       โ†‘                           โ”‚
       โ”‚                           โ–ผ
  Surge Event           Reward Computation
       โ”‚                  (6 sub-components)
       โ”‚                           โ”‚
  Escalation โ—„โ”€โ”€โ”€ Long Wait        โ–ผ
                            Next Observation

๐Ÿ” Observation Space

FieldTypeDescription
timestepintCurrent simulation minute
waiting_patientsList[Patient]All patients currently in queue
active_doctorsList[Doctor]All doctor states (available/busy/fatigue)
available_doctor_countintFree doctors right now
total_patients_treatedintCumulative treated count
average_waiting_timefloatMean queue wait time (minutes)
critical_patients_waitingintSeverity 4-5 patients in queue
surge_activeboolWhether a surge event is in progress
task_idstrCurrent task identifier

Patient fields: patient_id, severity (1-5), waiting_time, arrival_time, is_being_seen, escalation_count

Doctor fields: doctor_id, is_available, current_patient, patients_seen_today, fatigue_factor (1.0+), busy_until


โšก Action Space

json
{
  "patient_id": "P0012",        // Which patient to treat (null = idle)
  "doctor_id": "D01",           // Which doctor to assign (null = auto-pick)
  "priority_override": false    // Emergency override for severity-5 cases
}

Discrete action strategies (used by RL agent):

  • โ€”0 โ€” Idle (no assignment this step)
  • โ€”1 โ€” Assign highest-severity patient
  • โ€”2 โ€” Assign longest-waiting patient
  • โ€”3 โ€” Assign by composite score (severity ร— 10 + wait ร— 0.5)

๐Ÿ† Reward Function

The reward is continuous, decomposed, and informative at every step:

ComponentSignDescription
severity_bonusโœ…Bonus proportional to severity of patient treated quickly
wait_penaltyโŒExponential penalty for queue wait times, weighted by severity
idle_penaltyโŒPenalty per idle doctor when patients are waiting
critical_miss_penaltyโŒHeavy penalty for severity 4-5 patients waiting > 5 minutes
efficiency_bonusโœ…Small bonus for high overall throughput
escalation_penaltyโŒPenalty when a patient's severity auto-escalates

Total reward = sum of all components. Ranges approximately from -5.0 to +5.0 per step.


๐ŸŒŸ Innovative Features

1. Emergency Escalation System

If a patient waits beyond the task-specific threshold (10-20 minutes), their severity automatically increases by 1. This creates urgency and directly penalises agents that ignore mild patients too long.

2. Doctor Fatigue Simulation

Each doctor's fatigue_factor grows logarithmically with patients treated:

fatigue_factor = 1.0 + 0.05 ร— min(patients_seen, 15)

This multiplies treatment duration, simulating real physician cognitive and physical fatigue.

3. Dynamic Surge Events

With task-specific probability, a mass-casualty event spawns 2-8 high-severity patients in a single timestep โ€” simulating road accidents, building collapses, or disease outbreaks. The surge_active flag warns the agent.

4. Smart Reward Shaping

The six-component decomposed reward allows RL agents to learn which behaviours are beneficial vs harmful, rather than from a single sparse signal.


๐Ÿ“‹ Task Descriptions

TaskNameDoctorsStepsArrival ProbSurge ProbDifficulty
easyMorning Triage4600.403%โญ
mediumAfternoon Rush3800.657%โญโญ
hardEmergency Evening21000.8012%โญโญโญ

All tasks use the same API; task selection at env.reset(task_id=...).


๐Ÿš€ Setup Instructions

Local Installation

bash
# Clone or unzip the project
cd opd_queue_env

# Install dependencies
pip install -r requirements.txt

# Run FastAPI server
uvicorn app:app --host 0.0.0.0 --port 7860 --reload

# Open in browser:
# http://localhost:7860/docs

Run Baseline Agent

bash
python scripts/run_baseline.py

Train RL Agent

bash
# Train on one task
python scripts/train_rl_agent.py --task easy --episodes 300

# Train on all tasks
python scripts/train_rl_agent.py --task all --episodes 500

Run Inference

bash
# With LLM (requires OPENAI_API_KEY)
export OPENAI_API_KEY=sk-...
python inference.py --task medium --steps 30 --model gpt-4o-mini

# Without LLM (rule-based fallback)
python inference.py --task hard --steps 30 --no-llm

Docker

bash
docker build -t opd-queue-env .
docker run -p 7860:7860 opd-queue-env

๐Ÿ“Š Baseline Results

Rule-based agent scores (seed=42, reproducible):

TaskScore (0โ†’1)Avg WaitTreatedTotal Reward
Easy~0.72~8 min~24~+45
Medium~0.58~12 min~28~+30
Hard~0.41~18 min~32~+10

Q-Learning agent (300 episodes training, seed=42):

TaskScore (0โ†’1)Improvement vs Baseline
Easy~0.79+10%
Medium~0.66+14%
Hard~0.53+29%

๐Ÿ”Œ API Quick Reference

bash
# Reset environment
curl -X POST http://localhost:7860/reset \
  -H "Content-Type: application/json" \
  -d '{"task_id": "medium", "seed": 42}'

# Take a step
curl -X POST http://localhost:7860/step \
  -H "Content-Type: application/json" \
  -d '{"patient_id": "P0001", "doctor_id": "D01", "priority_override": false}'

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

# Get graded score
curl -X POST http://localhost:7860/score

๐Ÿ“„ OpenEnv Compliance

This environment implements the full OpenEnv interface:

  • โ€”โœ… Typed Pydantic models: Observation, Action, Reward
  • โ€”โœ… Core API: reset(), step(), state()
  • โ€”โœ… step() returns (observation, reward, done, info)
  • โ€”โœ… openenv.yaml metadata file
  • โ€”โœ… 3 tasks with deterministic graders (score 0.0 โ†’ 1.0)
  • โ€”โœ… Continuous, informative reward function
  • โ€”โœ… Baseline agent + RL agent scripts
  • โ€”โœ… Mandatory inference.py with [START]/[STEP]/[END] format
  • โ€”โœ… FastAPI server with POST /reset and POST /step
  • โ€”โœ… Docker support (python:3.9, port 7860)
  • โ€”โœ… HuggingFace Spaces deployment ready

๐Ÿ“ License

MIT License โ€” free to use, modify, and distribute.