Spaces:
Sleeping
Sleeping
Subhash Vadaparthi commited on
Commit ·
6257207
1
Parent(s): a9589c9
refactor: align with OpenEnv spec - create_app, Action/Observation base classes, improved inference with memory
Browse filesFiles changed (30)
- .gitignoreAdded+12
- Dockerfile+31-4
- README.md+135-49
- app/__init__.py+11-1
- app/__pycache__/__init__.cpython-310.pycDeleted
- app/__pycache__/__init__.cpython-311.pycDeleted
- app/__pycache__/__init__.cpython-313.pycDeleted
- app/__pycache__/agent.cpython-310.pycDeleted
- app/__pycache__/agent.cpython-311.pycDeleted
- app/__pycache__/agent.cpython-313.pycDeleted
- app/__pycache__/env.cpython-310.pycDeleted
- app/__pycache__/env.cpython-311.pycDeleted
- app/__pycache__/env.cpython-313.pycDeleted
- app/__pycache__/main.cpython-310.pycDeleted
- app/__pycache__/models.cpython-310.pycDeleted
- app/__pycache__/tasks.cpython-310.pycDeleted
- app/__pycache__/tasks.cpython-311.pycDeleted
- app/__pycache__/tasks.cpython-313.pycDeleted
- app/agent.py+46-21
- app/env.py+253-63
- app/main.py+63-101
- app/models.py+78-7
- client.pyAdded+81
- inference.py+174-51
- openenv.yaml+6-42
- pyproject.toml+27-12
- requirements.txt+9-4
- server/__init__.py+1-1
- server/app.py+185-5
- test_env.py+61-22
123456789101112__pycache__/*.pyc*.pyo.venv/venv/.env*.egg-info/dist/build/uv.lockoutputs/.DS_Store1234567891011FROM python:3.9-slimWORKDIR /appCOPY . /appRUN pip install --no-cache-dir -r requirements.txtEXPOSE 7860CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]1234567891011121314151617181920212223242526272829303132333435363738# Use Python 3.11 slim image as baseFROM python:3.11-slimENV API_PORT=7860# Set working directoryWORKDIR /app# Set environment variablesENV PYTHONDONTWRITEBYTECODE=1 \PYTHONUNBUFFERED=1 \PYTHONPATH=/app# Install system dependenciesRUN apt-get update && apt-get install -y \gcc \curl \&& rm -rf /var/lib/apt/lists/*# Copy requirements first for better cachingCOPY requirements.txt .# Install Python dependenciesRUN pip install --no-cache-dir --upgrade pip && \pip install --no-cache-dir -r requirements.txt# Copy application codeCOPY . .# Expose port 7860 (Hugging Face Spaces default)EXPOSE 7860# Health checkHEALTHCHECK --interval=30s --timeout=30s --start-period=5s --retries=3 \CMD curl -f http://localhost:7860/health || exit 1# Run the applicationCMD ["uvicorn", "server.app:app", "--host", "0.0.0.0", "--port", "7860"]
6 unmodified lines7891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283846 unmodified linespinned: false---# Healthcare Appointment Scheduling RL EnvironmentThis project implements a complete OpenEnv-compatible reinforcement learning environment simulating a real-world hospital appointment booking system.## Environment DesignThe environment simulates a hospital with multiple doctors and patients. The goal is to efficiently schedule appointments while considering patient priorities, doctor availability, and patient preferences.### Observation SpaceThe state is a dictionary containing:- `doctor_slots`: Availability of each doctor for each time slot.- `patients`: Information about patients (priority, preferred doctor, status).- `waiting_queue`: List of patient IDs currently waiting for an appointment.### Action SpaceActions are dictionaries:- `type`: "book", "reschedule", "cancel", or "waitlist".- `patient_id`: ID of the patient.- `doctor_id`: ID of the doctor (required for "book" and "reschedule").- `slot_id`: ID of the time slot (required for "book" and "reschedule").### Reward Function- **+1.0**: Successful booking.- **+0.2 bonus**: Booking with preferred doctor.- **+0.3**: Waitlisting a patient (partial progress).- **-1.0**: Conflicts (trying to book an occupied slot) or invalid actions.- **-0.2**: Cancellations.- **+0.5**: Successful rescheduling.## Tasks & Grading1. **Task 1 (Easy)**: Successfully book an appointment when slots are available.2. **Task 2 (Medium)**: Handle scheduling conflicts and rescheduling efficiently.3. **Task 3 (Hard)**: Optimize scheduling for multiple patients with different priorities (Priority 1 > Priority 2 > Priority 3).The `/grader` endpoint returns a score between 0.0 and 1.0 for each task based on efficiency and priority fulfillment.## Setup & Usage### Local Development1. Clone the repository.2. Install dependencies:```bashpip install -r requirements.txt```3. Run the FastAPI server:```bashpython app/main.py```4. The API will be available at `http://localhost:7860`.### Running with Docker```bashdocker build -t healthcare-rl-env .docker run -p 7860:7860 healthcare-rl-env```### DeploymentThis environment is fully compatible with Hugging Face Spaces. Simply upload the files to a Space and select "Docker" configuration.## API Endpoints- `GET /`: Root endpoint.- `POST /reset`: Resets the environment.- `POST /step`: Performs an action.- `GET /state`: Gets current state.- `GET /tasks`: Lists all available tasks.- `GET /grader`: Returns scores for each task.- `GET /baseline`: Runs a rule-based baseline agent and returns its performance.## License6 unmodified lines7891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691706 unmodified linespinned: false---# Healthcare Appointment Scheduling — OpenEnv EnvironmentAn OpenEnv-compatible reinforcement learning environment simulating a real-world hospital appointment booking system. The environment exposes scheduling tasks through the standard OpenEnv `reset()`/`step()`/`state()` interface.## Quick Start### Docker (Recommended)```bashcd Meta_Hackathondocker build -t healthcare-scheduling:latest .docker run --rm -p 7860:7860 healthcare-scheduling:latest```Verify the server is healthy:```bashcurl http://localhost:7860/health```Expected response:```json{"status": "healthy", "service": "healthcare_scheduling"}```### Without Docker```bashpip install -r requirements.txtuvicorn server.app:app --host 0.0.0.0 --port 7860```### Deploy to Hugging Face Spaces```bashopenenv push```Or specify options:```bashopenenv push --namespace my-org --private```## Environment DesignThe environment simulates a hospital with **3 doctors × 5 time slots** and **10 patients** with varying priorities. The agent's goal is to efficiently schedule appointments while respecting constraints.### Observation Space`HealthcareObservation` contains:| Field | Type | Description ||-------|------|-------------|| `doctor_slots` | `Dict[str, List[bool]]` | Availability per doctor per slot (True = free) || `patients` | `Dict[str, Dict]` | Patient info: priority, preferred doctor, status || `waiting_queue` | `List[str]` | Patient IDs currently awaiting appointment || `current_step` | `int` | Current step number |### Action Space`HealthcareAction` fields:| Field | Type | Description ||-------|------|-------------|| `type` | `str` | `"book"`, `"reschedule"`, `"cancel"`, or `"waitlist"` || `patient_id` | `int` | ID of the target patient || `doctor_id` | `int` | ID of the doctor (for book/reschedule) || `slot_id` | `int` | ID of the time slot (for book/reschedule) |### Reward Function| Action | Reward | Condition ||--------|--------|-----------|| Book | **+1.0** | Successful booking || Book (preferred) | **+1.2** | Booking with preferred doctor || Reschedule | **+0.5** | Successful reschedule || Waitlist | **+0.3** | Partial progress || Cancel | **-0.2** | Cancellation || Invalid/Conflict | **-1.0** | Bad action |## Tasks & Grading| Task | Difficulty | Description | Score Range ||------|-----------|-------------|-------------|| Task 1 | Easy | Successfully book appointments | 0.0 – 1.0 || Task 2 | Medium | Handle conflicts and rescheduling | 0.0 – 1.0 || Task 3 | Hard | Priority-based scheduling (1 > 2 > 3) | 0.0 – 1.0 |## Client Usage### Python (sync)```pythonfrom client import HealthcareEnvClientfrom app.models import HealthcareActionwith HealthcareEnvClient(base_url="http://localhost:7860") as env:result = env.reset()print(result)result = env.step(HealthcareAction(type="book",patient_id=0,doctor_id=1,slot_id=2))print(result)```## API Endpoints| Method | Path | Description ||--------|------|-------------|| `GET` | `/health` | Container health check || `POST` | `/reset` | Reset environment, get initial observation || `POST` | `/step` | Execute action, get next observation || `GET` | `/state` | Get current environment state || `GET` | `/schema` | Action/Observation JSON schemas || `GET` | `/tasks` | List task definitions || `GET` | `/grader` | Get grading scores || `GET` | `/baseline` | Run baseline agent || `GET` | `/docs` | Swagger/OpenAPI docs || `WS` | `/ws` | WebSocket for persistent sessions |## Project Structure```healthcare_scheduling/├── openenv.yaml # OpenEnv manifest (spec_version: 1)├── pyproject.toml # Dependencies and package config├── requirements.txt # Docker build dependencies├── Dockerfile # Container image definition├── client.py # EnvClient for remote access├── inference.py # LLM inference script├── test_env.py # Verification script├── app/│ ├── __init__.py # Package exports│ ├── models.py # HealthcareAction, HealthcareObservation│ ├── env.py # HealthcareEnvironment (OpenEnv interface)│ ├── agent.py # Baseline rule-based agent│ └── tasks.py # Task definitions and grader├── server/│ ├── __init__.py│ └── app.py # FastAPI app via create_app()└── static/└── index.html # Web frontend```## Running Inference```bashexport HF_TOKEN=your_token_herepython inference.py```The script outputs structured `[START]`/`[STEP]`/`[END]` blocks for each task.## License
1# Initializing app module1234567891011"""Healthcare Scheduling OpenEnv environment package."""from app.models import HealthcareAction, HealthcareObservationfrom app.env import HealthcareEnvironment, HealthcareEnv__all__ = ["HealthcareAction","HealthcareObservation","HealthcareEnvironment","HealthcareEnv",]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657from typing import Dict, Any, Listclass BaselineAgent:"""Rule-based agent for appointment scheduling.Strategy:1. Iterate through waiting queue.2. Sort patients by priority.3. Book the patient's preferred doctor if a slot is available.4. If not available, book any available slot with any doctor.5. If no slots, waitlist."""def __init__(self, env):self.env = envdef select_action(self, obs: Dict[str, Any]) -> Dict[str, Any]:waiting_queue = obs.get("waiting_queue", [])if not waiting_queue:return {"type": "waitlist", "patient_id": -1}patients = obs.get("patients", {})doctor_slots = obs.get("doctor_slots", {})# Sort waiting patients by priority (1 is highest)waiting_patients = [patients[pid] for pid in waiting_queue]waiting_patients.sort(key=lambda x: x["priority"])for patient in waiting_patients:pid = patient["id"]preferred_doctor = patient["preferred_doctor"]# 1. Try preferred doctorif preferred_doctor in doctor_slots:for sid, available in enumerate(doctor_slots[preferred_doctor]):if available:return {"type": "book","patient_id": pid,"doctor_id": preferred_doctor,"slot_id": sid}# 2. Try any other doctorfor did, slots in doctor_slots.items():if did == preferred_doctor:continuefor sid, available in enumerate(slots):if available:return {"type": "book","patient_id": pid,"doctor_id": did,"slot_id": sid}# 3. No slots available, waitlist the first patient in queuereturn {"type": "waitlist", "patient_id": waiting_queue[0]}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182"""Rule-based baseline agent for the Healthcare Scheduling environment.Strategy:1. Sort waiting patients by priority (1 = highest).2. For each patient, try their preferred doctor first.3. If preferred doctor has no free slots, try any other doctor.4. If no slots at all, waitlist the patient."""from typing import Any, Dict, Listclass BaselineAgent:"""Rule-based agent for appointment scheduling.Works with both the typed HealthcareEnvironment and the dict-basedobservation format."""def __init__(self, env=None):self.env = envdef select_action(self, obs: Dict[str, Any]) -> Dict[str, Any]:"""Select the best action given the current observation.Args:obs: Dict with doctor_slots, patients, waiting_queue.Returns:Action dict with type, patient_id, doctor_id, slot_id."""waiting_queue = obs.get("waiting_queue", [])if not waiting_queue:return {"type": "waitlist", "patient_id": -1}patients = obs.get("patients", {})doctor_slots = obs.get("doctor_slots", {})# Sort waiting patients by priority (1 is highest)waiting_patients = [patients[pid] for pid in waiting_queue if pid in patients]waiting_patients.sort(key=lambda x: x["priority"])for patient in waiting_patients:pid = patient["id"]preferred_doctor = patient["preferred_doctor"]# Convert preferred_doctor to string key if neededpref_key = str(preferred_doctor) if str(preferred_doctor) in doctor_slots else preferred_doctor# 1. Try preferred doctorif pref_key in doctor_slots:slots = doctor_slots[pref_key]for sid, available in enumerate(slots):if available:return {"type": "book","patient_id": pid,"doctor_id": preferred_doctor,"slot_id": sid,}# 2. Try any other doctorfor did, slots in doctor_slots.items():did_int = int(did) if isinstance(did, str) else didif did_int == preferred_doctor:continuefor sid, available in enumerate(slots):if available:return {"type": "book","patient_id": pid,"doctor_id": did_int,"slot_id": sid,}# 3. No slots available, waitlist the first patientfirst_pid = waiting_queue[0]pid_int = int(first_pid) if isinstance(first_pid, str) else first_pidreturn {"type": "waitlist", "patient_id": pid_int}
123456789101112131415161718192021222324252 unmodified lines28293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576774 unmodified lines8283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311324 unmodified lines1371381391401411421431441451461471481491504 unmodified lines155156157158159160161162163164165166167168169import randomfrom typing import Dict, List, Any, Optional, Unionclass HealthcareEnv:"""Healthcare Appointment Scheduling RL Environment.Simulates a hospital appointment booking system with doctors, patients, and time slots."""def __init__(self):self.num_doctors = 3self.num_slots = 5 # 5 slots per doctor (e.g., 9 AM to 2 PM)self.num_patients = 10self.priorities = [1, 2, 3] # 1: High, 2: Medium, 3: Lowself.reset()def reset(self):"""Resets the environment to initial state."""# Doctors availability: {doctor_id: [slot_0_available, slot_1_available, ...]}# True means slot is available (free), False means booked.self.doctor_slots = {i: [True] * self.num_slots for i in range(self.num_doctors)}# Patients: {patient_id: {"priority": p, "preferred_doctor": d, "status": "waiting/booked/cancelled"}}self.patients = {}for i in range(self.num_patients):self.patients[i] = {2 unmodified lines"preferred_doctor": random.randint(0, self.num_doctors - 1),"status": "waiting","booked_slot": None,"booked_doctor": None}self.waiting_queue = list(self.patients.keys())self.current_step = 0self.max_steps = self.num_patients * 2 # Allow some buffer for reschedulingself.done = Falsereturn self._get_obs()def _get_obs(self) -> Dict[str, Any]:"""Returns the current observation of the environment with string keys for JSON serialization."""return {"doctor_slots": {str(k): v for k, v in self.doctor_slots.items()},"patients": {str(k): v for k, v in self.patients.items()},"waiting_queue": [str(p) for p in self.waiting_queue],"current_step": self.current_step}def state(self) -> Dict[str, Any]:"""Returns the full state of the environment (OpenEnv API)."""return self._get_obs()def step(self, action: Dict[str, Any]) -> tuple:"""Performs an action in the environment.Action format: {"type": "book/reschedule/cancel/waitlist", "patient_id": pid, "doctor_id": did, "slot_id": sid}Robustly handles string IDs from external clients/LLMs."""if self.done:return self._get_obs(), 0, True, {"error": "Environment done"}action_type = action.get("type")# Robustly convert IDs to integerstry:patient_id = int(action.get("patient_id")) if action.get("patient_id") is not None else Nonedoctor_id = int(action.get("doctor_id")) if action.get("doctor_id") is not None else Noneslot_id = int(action.get("slot_id")) if action.get("slot_id") is not None else Noneexcept (ValueError, TypeError):return self._get_obs(), -1, self.done, {"error": "Invalid ID format (must be numeric)"}reward = 0info = {}if action_type == "book":reward, info = self._handle_book(patient_id, doctor_id, slot_id)4 unmodified lineselif action_type == "waitlist":reward, info = self._handle_waitlist(patient_id)else:reward = -1info = {"error": "Invalid action type"}self.current_step += 1if self.current_step >= self.max_steps or not self.waiting_queue:self.done = Truereturn self._get_obs(), reward, self.done, infodef _handle_book(self, patient_id, doctor_id, slot_id) -> tuple:if patient_id not in self.patients or self.patients[patient_id]["status"] != "waiting":return -1, {"error": f"Patient ID {patient_id} not available for booking"}if doctor_id not in self.doctor_slots or slot_id is None or slot_id < 0 or slot_id >= self.num_slots:return -1, {"error": "Invalid doctor or slot ID"}if not self.doctor_slots[doctor_id][slot_id]:return -1, {"error": "Slot already booked (conflict)"}# Successful bookingself.doctor_slots[doctor_id][slot_id] = Falseself.patients[patient_id].update({"status": "booked","booked_slot": slot_id,"booked_doctor": doctor_id})if patient_id in self.waiting_queue:self.waiting_queue.remove(patient_id)# Reward based on priority and preferencereward = 1.0if self.patients[patient_id]["preferred_doctor"] == doctor_id:reward += 0.2 # Bonus for preferred doctorreturn reward, {"status": "success"}def _handle_reschedule(self, patient_id, doctor_id, slot_id) -> tuple:if patient_id not in self.patients or self.patients[patient_id]["status"] != "booked":return -1, {"error": "Patient not currently booked"}if doctor_id not in self.doctor_slots or slot_id is None or slot_id < 0 or slot_id >= self.num_slots:return -1, {"error": "Invalid doctor or slot ID"}if not self.doctor_slots[doctor_id][slot_id]:return -1, {"error": "Target slot already booked (conflict)"}# Free old slotold_doctor = self.patients[patient_id]["booked_doctor"]4 unmodified linesself.doctor_slots[doctor_id][slot_id] = Falseself.patients[patient_id].update({"booked_slot": slot_id,"booked_doctor": doctor_id})return 0.5, {"status": "success"}def _handle_cancel(self, patient_id) -> tuple:if patient_id not in self.patients or self.patients[patient_id]["status"] == "waiting":return -1, {"error": "Patient not booked"}# Free slot if bookedif self.patients[patient_id]["status"] == "booked":4 unmodified linesself.patients[patient_id].update({"status": "waiting","booked_slot": None,"booked_doctor": None})if patient_id not in self.waiting_queue:self.waiting_queue.append(patient_id)return -0.2, {"status": "cancelled"}def _handle_waitlist(self, patient_id) -> tuple:if patient_id not in self.patients or self.patients[patient_id]["status"] != "waiting":return -1, {"error": "Patient not in waiting queue"}return 0.3, {"status": "waitlisted"}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241252 unmodified lines1281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931944 unmodified lines1992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173184 unmodified lines3233243253263273283293303313323333343353364 unmodified lines341342343344345346347348349350351352353354355356357358359"""Healthcare Appointment Scheduling Environment.Implements the OpenEnv Environment interface for a hospital appointmentbooking system with doctors, patients, and time slots.Design:- Multi-step episodes: reset() initialises state, step() processes actions- 3 doctors × 5 time slots = 15 total bookable slots- 10 patients with random priorities (1=High, 2=Medium, 3=Low)- Episode ends when waiting queue is empty or max steps reachedRewards:+1.0 successful booking+0.2 bonus for preferred doctor match+0.5 successful reschedule+0.3 waitlisting (partial progress)-0.2 cancellation-1.0 invalid action / conflict"""import randomfrom typing import Any, Dict, List, Optionalfrom uuid import uuid4# ── OpenEnv base classes (with graceful fallback) ────────────────────try:from openenv.core.env_server.interfaces import Environmentfrom openenv.core.env_server.types import State_HAS_OPENENV = Trueexcept ImportError:# Fallback so the environment works standalone without openenv-core_HAS_OPENENV = Falseclass Environment:"""Minimal Environment stub when openenv-core is not installed."""SUPPORTS_CONCURRENT_SESSIONS = Falseclass State:"""Minimal State stub."""def __init__(self, episode_id: str = "", step_count: int = 0):self.episode_id = episode_idself.step_count = step_counttry:from app.models import HealthcareAction, HealthcareObservationexcept ImportError:from .models import HealthcareAction, HealthcareObservationclass HealthcareEnvironment(Environment):"""Healthcare Appointment Scheduling RL Environment.Simulates a hospital appointment booking system with doctors, patients,and time slots. Follows the OpenEnv Environment interface.Example:>>> env = HealthcareEnvironment()>>> obs = env.reset()>>> print(obs.waiting_queue) # ['0', '1', ..., '9']>>> obs = env.step(HealthcareAction(type='book', patient_id=0, doctor_id=0, slot_id=0))>>> print(obs.reward) # 1.0 or 1.2"""SUPPORTS_CONCURRENT_SESSIONS: bool = Truedef __init__(self, seed: Optional[int] = None):"""Initialise the Healthcare Scheduling environment.Args:seed: Optional random seed for reproducibility."""self.num_doctors = 3self.num_slots = 5 # 5 slots per doctor (e.g. 9 AM to 2 PM)self.num_patients = 10self.priorities = [1, 2, 3] # 1: High, 2: Medium, 3: Lowself._seed = seedself._state = State(episode_id=str(uuid4()), step_count=0)# Internal state (populated by reset)self.doctor_slots: Dict[int, List[bool]] = {}self.patients: Dict[int, Dict[str, Any]] = {}self.waiting_queue: List[int] = []self.current_step: int = 0self.max_steps: int = 0self.done: bool = False# Tracking for gradingself._action_history: List[Dict[str, Any]] = []# ── OpenEnv Interface ─────────────────────────────────────────────def reset(self,seed: Optional[int] = None,episode_id: Optional[str] = None,**kwargs,) -> HealthcareObservation:"""Reset the environment to an initial state.Args:seed: Random seed for reproducibility.episode_id: Optional episode ID.Returns:HealthcareObservation with initial state, done=False, reward=0.0"""if seed is not None:self._seed = seedif self._seed is not None:random.seed(self._seed)# Doctors availability: True means slot is freeself.doctor_slots = {i: [True] * self.num_slots for i in range(self.num_doctors)}# Patients with random priorities and preferred doctorsself.patients = {}for i in range(self.num_patients):self.patients[i] = {2 unmodified lines"preferred_doctor": random.randint(0, self.num_doctors - 1),"status": "waiting","booked_slot": None,"booked_doctor": None,}self.waiting_queue = list(self.patients.keys())self.current_step = 0self.max_steps = self.num_patients * 2 # buffer for reschedulingself.done = Falseself._action_history = []# Update episode stateself._state = State(episode_id=episode_id or str(uuid4()),step_count=0,)return HealthcareObservation(doctor_slots={str(k): v for k, v in self.doctor_slots.items()},patients={str(k): v for k, v in self.patients.items()},waiting_queue=[str(p) for p in self.waiting_queue],current_step=self.current_step,info={},done=False,reward=0.0,)def step(self, action: HealthcareAction) -> HealthcareObservation:"""Execute an action in the environment.Args:action: HealthcareAction with type, patient_id, doctor_id, slot_id.Returns:HealthcareObservation with updated state, reward, and done flag."""if hasattr(self, '_state'):self._state.step_count += 1if self.done:return HealthcareObservation(doctor_slots={str(k): v for k, v in self.doctor_slots.items()},patients={str(k): v for k, v in self.patients.items()},waiting_queue=[str(p) for p in self.waiting_queue],current_step=self.current_step,info={"error": "Environment done"},done=True,reward=0.0,)action_type = action.type# Robustly convert IDs to integerstry:patient_id = int(action.patient_id) if action.patient_id is not None else Nonedoctor_id = int(action.doctor_id) if action.doctor_id is not None else Noneslot_id = int(action.slot_id) if action.slot_id is not None else Noneexcept (ValueError, TypeError):return self._make_obs(-1.0, {"error": "Invalid ID format (must be numeric)"})reward = 0.0info: Dict[str, Any] = {}if action_type == "book":reward, info = self._handle_book(patient_id, doctor_id, slot_id)4 unmodified lineselif action_type == "waitlist":reward, info = self._handle_waitlist(patient_id)else:reward = -1.0info = {"error": "Invalid action type"}self._action_history.append({"type": action_type,"patient_id": patient_id,"doctor_id": doctor_id,"slot_id": slot_id,"reward": reward,"info": info,})self.current_step += 1if self.current_step >= self.max_steps or not self.waiting_queue:self.done = Truereturn self._make_obs(reward, info)@propertydef state(self) -> State:"""Get the current environment state.Returns:State with episode_id and step_count."""return self._state# ── Legacy compatibility (dict-based step) ───────────────────────def step_dict(self, action_dict: Dict[str, Any]) -> tuple:"""Dict-based step for backward compatibility with legacy endpoints.Args:action_dict: Action as a plain dictionary.Returns:Tuple of (obs_dict, reward, done, info)."""action = HealthcareAction(type=action_dict.get("type", "waitlist"),patient_id=action_dict.get("patient_id", 0),doctor_id=action_dict.get("doctor_id"),slot_id=action_dict.get("slot_id"),)obs = self.step(action)obs_dict = {"doctor_slots": obs.doctor_slots,"patients": obs.patients,"waiting_queue": obs.waiting_queue,"current_step": obs.current_step,}return obs_dict, obs.reward, obs.done, obs.info or {}def reset_dict(self) -> Dict[str, Any]:"""Reset and return observation as a plain dict."""obs = self.reset()return {"doctor_slots": obs.doctor_slots,"patients": obs.patients,"waiting_queue": obs.waiting_queue,"current_step": obs.current_step,}# ── Internal helpers ─────────────────────────────────────────────def _make_obs(self, reward: float, info: Dict[str, Any]) -> HealthcareObservation:"""Build an observation from current internal state."""return HealthcareObservation(doctor_slots={str(k): v for k, v in self.doctor_slots.items()},patients={str(k): v for k, v in self.patients.items()},waiting_queue=[str(p) for p in self.waiting_queue],current_step=self.current_step,info=info,done=self.done,reward=reward,)def _handle_book(self, patient_id, doctor_id, slot_id) -> tuple:if patient_id not in self.patients or self.patients[patient_id]["status"] != "waiting":return -1.0, {"error": f"Patient ID {patient_id} not available for booking"}if doctor_id not in self.doctor_slots or slot_id is None or slot_id < 0 or slot_id >= self.num_slots:return -1.0, {"error": "Invalid doctor or slot ID"}if not self.doctor_slots[doctor_id][slot_id]:return -1.0, {"error": "Slot already booked (conflict)"}# Successful bookingself.doctor_slots[doctor_id][slot_id] = Falseself.patients[patient_id].update({"status": "booked","booked_slot": slot_id,"booked_doctor": doctor_id,})if patient_id in self.waiting_queue:self.waiting_queue.remove(patient_id)reward = 1.0if self.patients[patient_id]["preferred_doctor"] == doctor_id:reward += 0.2 # Bonus for preferred doctorreturn reward, {"status": "success"}def _handle_reschedule(self, patient_id, doctor_id, slot_id) -> tuple:if patient_id not in self.patients or self.patients[patient_id]["status"] != "booked":return -1.0, {"error": "Patient not currently booked"}if doctor_id not in self.doctor_slots or slot_id is None or slot_id < 0 or slot_id >= self.num_slots:return -1.0, {"error": "Invalid doctor or slot ID"}if not self.doctor_slots[doctor_id][slot_id]:return -1.0, {"error": "Target slot already booked (conflict)"}# Free old slotold_doctor = self.patients[patient_id]["booked_doctor"]4 unmodified linesself.doctor_slots[doctor_id][slot_id] = Falseself.patients[patient_id].update({"booked_slot": slot_id,"booked_doctor": doctor_id,})return 0.5, {"status": "success"}def _handle_cancel(self, patient_id) -> tuple:if patient_id not in self.patients or self.patients[patient_id]["status"] == "waiting":return -1.0, {"error": "Patient not booked"}# Free slot if bookedif self.patients[patient_id]["status"] == "booked":4 unmodified linesself.patients[patient_id].update({"status": "waiting","booked_slot": None,"booked_doctor": None,})if patient_id not in self.waiting_queue:self.waiting_queue.append(patient_id)return -0.2, {"status": "cancelled"}def _handle_waitlist(self, patient_id) -> tuple:if patient_id not in self.patients or self.patients[patient_id]["status"] != "waiting":return -1.0, {"error": "Patient not in waiting queue"}return 0.3, {"status": "waitlisted"}# ── Backward-compatible alias ────────────────────────────────────────HealthcareEnv = HealthcareEnvironment
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116from fastapi import FastAPI, HTTPExceptionfrom fastapi.staticfiles import StaticFilesfrom fastapi.responses import FileResponsefrom app.env import HealthcareEnvfrom app.agent import BaselineAgentfrom app.tasks import TASKS, TaskGraderfrom app.models import Action, StepResponse, ResetResponse, StateResponse, TaskResponse, GraderResponse, BaselineResponsefrom typing import List, Dict, Anyimport osDESCRIPTION = """## OpenEnv Environment HTTP APIHTTP API for interacting with OpenEnv environments through a standardized interface.### Features- **Environment Reset**: Initialize or restart episodes- **Action Execution**: Send actions and receive observations- **State Inspection**: Query current environment state- **Schema Access**: Retrieve JSON schemas for actions and observations### Workflow1. Call `/reset` to start a new episode and get initial observation2. Call `/step` repeatedly with actions to interact with environment3. Episode ends when observation returns `done: true`4. Call `/state` anytime to inspect current environment state### Documentation- **Swagger UI**: Available at `/docs`- **ReDoc**: Available at `/redoc`- **OpenAPI Schema**: Available at `/openapi.json`[OpenEnv Team - Website](https://openenv.org) | BSD-3-Clause"""app = FastAPI(title="OpenEnv Environment HTTP API",version="1.0.0",description=DESCRIPTION,)# Serve static filesSTATIC_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "static")app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")# Global environment instanceenv = HealthcareEnv()@app.get("/", include_in_schema=False)def serve_frontend():return FileResponse(os.path.join(STATIC_DIR, "index.html"))@app.api_route("/reset", methods=["GET", "POST"], response_model=ResetResponse)def reset_env():obs = env.reset()return {"observation": obs,"info": {}}@app.post("/step", response_model=StepResponse)def step_env(action: Action):# Convert Pydantic model to dict for environment handlingaction_dict = action.model_dump() if hasattr(action, "model_dump") else action.dict()obs, reward, done, info = env.step(action_dict)return {"observation": obs,"reward": reward,"done": done,"info": info}@app.get("/state", response_model=StateResponse)def get_state():return {"state": env.state()}@app.get("/tasks", response_model=List[TaskResponse])def list_tasks():return [task.__dict__ for task in TASKS]@app.get("/grader", response_model=GraderResponse)def get_grader_scores():grader = TaskGrader(env)return {"task_scores": {"task_1": grader.grade_task_1(),"task_2": grader.grade_task_2(),"task_3": grader.grade_task_3()}}@app.get("/baseline", response_model=BaselineResponse)def run_baseline():""" Runs the rule-based baseline agent and returns scores. """env.reset()agent = BaselineAgent(env)observations = []while not env.done:obs = env._get_obs()observations.append(obs)action = agent.select_action(obs)env.step(action)grader = TaskGrader(env)return {"task_scores": {"task_1": grader.grade_task_1(),"task_2": grader.grade_task_2(),"task_3": grader.grade_task_3()},"observations": observations}if __name__ == "__main__":import uvicorn123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778"""Main FastAPI application — backward-compatible entry point.The primary server entry point is now ``server.app``, which uses the OpenEnv``create_app()`` factory. This module re-exports the app for legacy``python app/main.py`` usage and adds the custom ``/tasks``, ``/grader``,and ``/baseline`` endpoints."""from __future__ import annotationsimport osimport sysfrom pathlib import Path# Ensure the project root is on sys.pathPROJECT_ROOT = Path(__file__).resolve().parent.parentif str(PROJECT_ROOT) not in sys.path:sys.path.insert(0, str(PROJECT_ROOT))from server.app import app # re-export the canonical app# ── Additional domain-specific endpoints ─────────────────────────────# These are NOT part of the OpenEnv spec but are useful for the hackathon# grader and for debugging.from app.env import HealthcareEnvironmentfrom app.agent import BaselineAgentfrom app.tasks import TASKS, TaskGrader_env = HealthcareEnvironment()# Only register these routes if they don't already exist (avoids duplicates# when server.app's fallback path already added them)._existing = {r.path for r in app.routes}if "/tasks" not in _existing:@app.get("/tasks")def list_tasks():return [task.__dict__ for task in TASKS]if "/grader" not in _existing:@app.get("/grader")def get_grader_scores():grader = TaskGrader(_env)return {"task_scores": {"task_1": grader.grade_task_1(),"task_2": grader.grade_task_2(),"task_3": grader.grade_task_3(),}}if "/baseline" not in _existing:@app.get("/baseline")def run_baseline():_env.reset()agent = BaselineAgent(_env)while not _env.done:obs_dict = {"doctor_slots": {str(k): v for k, v in _env.doctor_slots.items()},"patients": {str(k): v for k, v in _env.patients.items()},"waiting_queue": [str(p) for p in _env.waiting_queue],}action = agent.select_action(obs_dict)_env.step_dict(action)grader = TaskGrader(_env)return {"task_scores": {"task_1": grader.grade_task_1(),"task_2": grader.grade_task_2(),"task_3": grader.grade_task_3(),}}if __name__ == "__main__":import uvicorn
123456789101112131415161718192021222324252627282930313233from pydantic import BaseModel, field_validatorfrom typing import Dict, Any, List, Optional, Unionclass Action(BaseModel):type: str # book/reschedule/cancel/waitlistpatient_id: Union[int, str]doctor_id: Optional[Union[int, str]] = Noneslot_id: Optional[Union[int, str]] = Noneclass StepResponse(BaseModel):observation: Dict[str, Any]reward: floatdone: boolinfo: Dict[str, Any]class ResetResponse(BaseModel):observation: Dict[str, Any]info: Dict[str, Any] = {}class StateResponse(BaseModel):state: Dict[str, Any]class TaskResponse(BaseModel):name: strdifficulty: strdescription: strclass GraderResponse(BaseModel):task_scores: Dict[str, float]class BaselineResponse(BaseModel):task_scores: Dict[str, float]observations: List[Dict[str, Any]]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104"""Data models for the Healthcare Scheduling Environment.Uses OpenEnv base types for framework compatibility.Fallback to plain Pydantic if openenv-core is not installed."""from typing import Any, Dict, List, Optional, Unionfrom pydantic import BaseModel, Field# ── OpenEnv base types (with graceful fallback) ────────────────────────try:from openenv.core.env_server.types import Action, Observationexcept ImportError:# Fallback: define minimal base classes so the env still works standaloneclass Action(BaseModel):"""Base action class (fallback when openenv-core is not installed)."""passclass Observation(BaseModel):"""Base observation class (fallback when openenv-core is not installed)."""done: bool = Falsereward: float = 0.0# ── Environment Action ────────────────────────────────────────────────class HealthcareAction(Action):"""Action for the Healthcare Scheduling environment."""type: str = Field(...,description="Action type: 'book', 'reschedule', 'cancel', or 'waitlist'",)patient_id: Union[int, str] = Field(...,description="ID of the patient",)doctor_id: Optional[Union[int, str]] = Field(default=None,description="ID of the doctor (required for 'book' and 'reschedule')",)slot_id: Optional[Union[int, str]] = Field(default=None,description="ID of the time slot (required for 'book' and 'reschedule')",)# ── Environment Observation ──────────────────────────────────────────class HealthcareObservation(Observation):"""Observation from the Healthcare Scheduling environment."""doctor_slots: Optional[Dict[str, List[bool]]] = Field(default=None,description="Availability of each doctor for each time slot (True = available)",)patients: Optional[Dict[str, Dict[str, Any]]] = Field(default=None,description="Patient information: priority, preferred doctor, status",)waiting_queue: Optional[List[str]] = Field(default=None,description="List of patient IDs currently waiting",)current_step: Optional[int] = Field(default=None,description="Current step number in the episode",)info: Optional[Dict[str, Any]] = Field(default=None,description="Additional info (errors, status messages)",)# ── API Response Models (for FastAPI endpoint compatibility) ──────────class StepResponse(BaseModel):observation: Dict[str, Any]reward: floatdone: boolinfo: Dict[str, Any]class ResetResponse(BaseModel):observation: Dict[str, Any]info: Dict[str, Any] = {}class StateResponse(BaseModel):state: Dict[str, Any]class TaskResponse(BaseModel):name: strdifficulty: strdescription: strclass GraderResponse(BaseModel):task_scores: Dict[str, float]class BaselineResponse(BaseModel):task_scores: Dict[str, float]observations: List[Dict[str, Any]]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081"""Remote client for the Healthcare Scheduling environment.
Follows the OpenEnv EnvClient pattern for async/sync remote access.
Usage (async): async with HealthcareEnvClient(base_url="http://localhost:7860") as env: result = await env.reset() result = await env.step(HealthcareAction(type="book", patient_id=0, doctor_id=0, slot_id=0))
Usage (sync): with HealthcareEnvClient(base_url="http://localhost:7860").sync() as env: result = env.reset() result = env.step(HealthcareAction(type="book", patient_id=0, doctor_id=0, slot_id=0))
Usage (Docker): env = HealthcareEnvClient.from_docker_image("healthcare-scheduling:latest") result = env.reset() env.close()"""
from __future__ import annotations
from app.models import HealthcareAction, HealthcareObservation
try: from openenv.core.env_client import EnvClient
class HealthcareEnvClient(EnvClient[HealthcareAction, HealthcareObservation]): """ Remote async client for the Healthcare Scheduling environment.
Connects to the environment server over WebSocket for low-latency persistent sessions. Falls back to HTTP if WebSocket is unavailable. """
ACTION_TYPE = HealthcareAction OBSERVATION_TYPE = HealthcareObservation
except ImportError: # Fallback: lightweight HTTP-only client using requests import requests from typing import Optional, Dict, Any
class HealthcareEnvClient: """ Simple HTTP client for Healthcare Scheduling (fallback, no openenv-core). """
def __init__(self, base_url: str = "http://localhost:7860"): self.base_url = base_url.rstrip("/")
def reset(self) -> Dict[str, Any]: resp = requests.post(f"{self.base_url}/reset") resp.raise_for_status() return resp.json()
def step(self, action: HealthcareAction) -> Dict[str, Any]: payload = action.model_dump() if hasattr(action, "model_dump") else action.dict() resp = requests.post(f"{self.base_url}/step", json=payload) resp.raise_for_status() return resp.json()
def state(self) -> Dict[str, Any]: resp = requests.get(f"{self.base_url}/state") resp.raise_for_status() return resp.json()
def health(self) -> Dict[str, Any]: resp = requests.get(f"{self.base_url}/health") resp.raise_for_status() return resp.json()
def close(self): pass
def __enter__(self): return self
def __exit__(self, *args): self.close()12345678910111213141516171819202122232425262728293031323334353637383940414243444546472 unmodified lines5051525354555657585960616263646566676869707172737475767778798081828384858687888990919214 unmodified lines1071081091101111121131141151161171181192 unmodified lines12212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415516 unmodified lines172173174175176177178"""Inference Script — Healthcare Appointment Scheduling=====================================================MANDATORY- Environment variables:API_BASE_URL The API endpoint for the LLM.MODEL_NAME The model identifier to use for inference.HF_TOKEN Your Hugging Face / API key.- Defaults are set only for API_BASE_URL and MODEL_NAME.- Uses OpenAI Client for all LLM calls.STDOUT FORMAT[START] task=<task_name> env=<benchmark> model=<model_name>[STEP] step=<n> action=<action_str> reward=<0.00> done=<true|false> error=<msg|null>[END] success=<true|false> steps=<n> score=<score> rewards=<r1,r2,...,rn>"""import osimport sysimport jsonfrom typing import List, Optionalfrom openai import OpenAIfrom app.env import HealthcareEnvfrom app.tasks import TaskGrader# ── Environment variables (match sample exactly) ──────────────────────────API_KEY = os.getenv("HF_TOKEN") or os.getenv("API_KEY")API_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")MODEL_NAME = os.getenv("MODEL_NAME", "meta-llama/Llama-3.1-8B-Instruct")BENCHMARK = "healthcare-scheduling"MAX_STEPS = 20client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)# ── Structured logging helpers (match sample exactly) ─────────────────────def log_start(task: str, env: str, model: str) -> None:print(f"[START] task={task} env={env} model={model}", flush=True)def log_step(step: int, action: str, reward: float, done: bool, error: Optional[str]) -> None:error_val = error if error else "null"done_val = str(done).lower()print(2 unmodified lines)def log_end(success: bool, steps: int, score: float, rewards: List[float]) -> None:rewards_str = ",".join(f"{r:.2f}" for r in rewards)print(f"[END] success={str(success).lower()} steps={steps} score={score:.2f} rewards={rewards_str}",flush=True,)# ── LLM action selection ─────────────────────────────────────────────────def get_action_from_llm(obs):"""Asks the LLM to choose an action based on the current environment state."""prompt = f"""You are an expert healthcare administrator and scheduling assistant.Your goal is to book appointments efficiently while respecting doctor availability and patient priorities.Current environment state:```json{json.dumps(obs, indent=2)}```Instructions:1. Analyze which patients are in the 'waiting_queue'.2. Check 'doctor_slots' to find available slots (True means available).3. Select a patient and an available slot.4. Respond ONLY with a valid JSON object.JSON Keys:- "type": "book", "reschedule", "cancel", or "waitlist"- "patient_id": Integer ID of the patient- "doctor_id": Integer ID of the doctor- "slot_id": Integer ID of the time slotExample Response:{{"type": "book", "patient_id": 0, "doctor_id": 1, "slot_id": 2}}Reply with only the JSON object:"""try:response = client.chat.completions.create(14 unmodified linesreturn json.loads(text)except Exception as e:print(f"[DEBUG] LLM error: {e}", flush=True)waiting_q = obs.get("waiting_queue", [])p_id = int(waiting_q[0]) if waiting_q else 0return {"type": "waitlist", "patient_id": p_id, "doctor_id": 0, "slot_id": 0}# ── Format action as a compact string for [STEP] logging ─────────────────def action_to_str(action: dict) -> str:"""Convert action dict to a compact string like book(patient=0,doctor=1,slot=2)"""a_type = action.get("type", "unknown")p = action.get("patient_id", "?")2 unmodified linesreturn f"{a_type}(patient={p},doctor={d},slot={s})"# ── Main inference loop ──────────────────────────────────────────────────def run_inference():# Task definitions from openenv.yamltask_defs = [{"name": "book_appointment", "grader": "grade_task_1"},{"name": "scheduling_conflicts", "grader": "grade_task_2"},{"name": "priority_scheduling", "grader": "grade_task_3"},]env = HealthcareEnv()obs = env.reset()# ── Run the agent loop and collect step data ──steps_taken = 0rewards: List[float] = []actions: List[str] = []dones: List[bool] = []errors: List[Optional[str]] = []while not env.done and steps_taken < MAX_STEPS:action = get_action_from_llm(obs)obs, reward, done, info = env.step(action)steps_taken += 1rewards.append(reward)actions.append(action_to_str(action))dones.append(done)errors.append(info.get("error"))# ── Grade all tasks ──grader = TaskGrader(env)16 unmodified lineserror=errors[i],)log_end(success=success, steps=steps_taken, score=task_score, rewards=rewards)sys.exit(0)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465662 unmodified lines6970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314 unmodified lines1581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072 unmodified lines21021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627716 unmodified lines294295296297298299300301"""Inference Script - Healthcare Appointment Scheduling=====================================================MANDATORY- Environment variables:API_BASE_URL The API endpoint for the LLM (must have default).MODEL_NAME The model identifier to use for inference (must have default).HF_TOKEN Your Hugging Face / API key (mandatory, no default).- Uses OpenAI Client for all LLM calls.STDOUT FORMAT (exact spec):[START] task=<task_name> env=<benchmark> model=<model_name>[STEP] step=<n> action=<action_str> reward=<0.00> done=<true|false> error=<msg|null>[END] success=<true|false> steps=<n> rewards=<r1,r2,...,rn>Rules:- One [START] line at episode begin.- One [STEP] line per step, immediately after env.step() returns.- One [END] line after episode ends, always emitted (even on exception).- reward and rewards are formatted to 2 decimal places.- done and success are lowercase booleans: true or false.- error is the raw last_action_error string, or null if none.- All fields on a single line with no newlines within a line."""import osimport sysimport jsonfrom typing import Any, Dict, List, Optionalfrom openai import OpenAI# ── Import environment components ────────────────────────────────────sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from app.env import HealthcareEnvironmentfrom app.models import HealthcareActionfrom app.tasks import TaskGrader# ── Environment variables (per submission guidelines) ────────────────API_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")MODEL_NAME = os.getenv("MODEL_NAME", "meta-llama/Llama-3.1-8B-Instruct")HF_TOKEN = os.getenv("HF_TOKEN")if HF_TOKEN is None:raise ValueError("HF_TOKEN environment variable is required")BENCHMARK = "healthcare-scheduling"MAX_STEPS = 20# Initialize OpenAI clientclient = OpenAI(base_url=API_BASE_URL, api_key=HF_TOKEN)# ── Structured logging helpers (match spec exactly) ─────────────────def log_start(task: str, env: str, model: str) -> None:"""Emit [START] line at episode begin."""print(f"[START] task={task} env={env} model={model}", flush=True)def log_step(step: int, action: str, reward: float, done: bool, error: Optional[str]) -> None:"""Emit [STEP] line immediately after env.step() returns."""error_val = error if error else "null"done_val = str(done).lower()print(2 unmodified lines)def log_end(success: bool, steps: int, rewards: List[float]) -> None:"""Emit [END] line after episode ends. Always emitted, even on exception."""rewards_str = ",".join(f"{r:.2f}" for r in rewards)print(f"[END] success={str(success).lower()} steps={steps} rewards={rewards_str}",flush=True,)# ── LLM action selection (with memory of past failures) ─────────────def get_action_from_llm(obs: Dict[str, Any],action_history: List[Dict[str, Any]],) -> Dict[str, Any]:"""Asks the LLM to choose an action based on the current environment state.Includes history of past actions so the LLM avoids repeating mistakes."""# Build a concise summary of past actions for the LLMhistory_lines = ""if action_history:history_lines = "\n\nPrevious actions taken this episode:\n"for h in action_history:status = "SUCCESS" if h.get("reward", 0) > 0 else "FAILED"err = h.get("error", "")err_str = f" - Error: {err}" if err else ""history_lines += f" - {h['action_str']} => {status} (reward={h['reward']:.2f}){err_str}\n"history_lines += "\nDO NOT repeat any failed actions. Choose a DIFFERENT doctor_id and slot_id.\n"# Build a compact view of which slots are actually availableavailable_slots = []doctor_slots = obs.get("doctor_slots", {})for did, slots in doctor_slots.items():for sid, avail in enumerate(slots):if avail:available_slots.append(f"doctor={did}, slot={sid}")available_str = "\n".join(f" - {s}" for s in available_slots) if available_slots else " NONE - all slots are booked!"# Build compact patient info for waiting patients onlywaiting_queue = obs.get("waiting_queue", [])patients = obs.get("patients", {})waiting_info = []for pid in waiting_queue:p = patients.get(str(pid), patients.get(pid, {}))waiting_info.append(f" - Patient {pid}: priority={p.get('priority','?')}, preferred_doctor={p.get('preferred_doctor','?')}")waiting_str = "\n".join(waiting_info) if waiting_info else " NONE - all patients are scheduled!"prompt = f"""You are an expert healthcare appointment scheduler. Book appointments efficiently.AVAILABLE SLOTS (True = free):{available_str}WAITING PATIENTS (need appointments):{waiting_str}{history_lines}RULES:- ONLY book slots that are available (True).- Prioritize patients with lower priority number (1=highest priority).- Match patients with their preferred_doctor when possible for bonus reward.- If no slots are available for a patient, use "waitlist".- NEVER book a slot that is False (already taken).Respond with ONLY a JSON object:{{"type": "book", "patient_id": <int>, "doctor_id": <int>, "slot_id": <int>}}Your action:"""try:response = client.chat.completions.create(14 unmodified linesreturn json.loads(text)except Exception as e:print(f"[DEBUG] LLM error: {e}", flush=True)# Smart fallback: try to find an available slot for a waiting patientreturn _fallback_action(obs)def _fallback_action(obs: Dict[str, Any]) -> Dict[str, Any]:"""Rule-based fallback when LLM fails. Picks the best available action."""waiting_q = obs.get("waiting_queue", [])if not waiting_q:return {"type": "waitlist", "patient_id": 0, "doctor_id": 0, "slot_id": 0}patients = obs.get("patients", {})doctor_slots = obs.get("doctor_slots", {})# Sort by priority (1 = highest)sorted_patients = []for pid in waiting_q:p = patients.get(str(pid), patients.get(pid, {}))sorted_patients.append((pid, p.get("priority", 3), p.get("preferred_doctor", 0)))sorted_patients.sort(key=lambda x: x[1])for pid, priority, pref_doc in sorted_patients:pid_int = int(pid)# Try preferred doctor firstpref_key = str(pref_doc)if pref_key in doctor_slots:for sid, avail in enumerate(doctor_slots[pref_key]):if avail:return {"type": "book", "patient_id": pid_int, "doctor_id": pref_doc, "slot_id": sid}# Try any doctorfor did, slots in doctor_slots.items():did_int = int(did)for sid, avail in enumerate(slots):if avail:return {"type": "book", "patient_id": pid_int, "doctor_id": did_int, "slot_id": sid}# No slots leftp_id = int(waiting_q[0])return {"type": "waitlist", "patient_id": p_id, "doctor_id": 0, "slot_id": 0}# ── Format action as a compact string for [STEP] logging ────────────def action_to_str(action: Dict[str, Any]) -> str:"""Convert action dict to a compact string like book(patient=0,doctor=1,slot=2)"""a_type = action.get("type", "unknown")p = action.get("patient_id", "?")2 unmodified linesreturn f"{a_type}(patient={p},doctor={d},slot={s})"# ── Main inference loop ─────────────────────────────────────────────def run_inference():# Task definitionstask_defs = [{"name": "book_appointment", "grader": "grade_task_1"},{"name": "scheduling_conflicts", "grader": "grade_task_2"},{"name": "priority_scheduling", "grader": "grade_task_3"},]env = HealthcareEnvironment(seed=42)obs = env.reset()# Convert observation to dict for the LLM promptobs_dict = {"doctor_slots": obs.doctor_slots,"patients": obs.patients,"waiting_queue": obs.waiting_queue,"current_step": obs.current_step,}# ── Run the agent loop and collect step data ──steps_taken = 0rewards: List[float] = []actions: List[str] = []dones: List[bool] = []errors: List[Optional[str]] = []action_history: List[Dict[str, Any]] = [] # memory for the LLMwhile not env.done and steps_taken < MAX_STEPS:action_dict = get_action_from_llm(obs_dict, action_history)# Step using typed actionaction = HealthcareAction(type=action_dict.get("type", "waitlist"),patient_id=action_dict.get("patient_id", 0),doctor_id=action_dict.get("doctor_id"),slot_id=action_dict.get("slot_id"),)obs = env.step(action)obs_dict = {"doctor_slots": obs.doctor_slots,"patients": obs.patients,"waiting_queue": obs.waiting_queue,"current_step": obs.current_step,}step_error = obs.info.get("error") if obs.info else Nonestep_action_str = action_to_str(action_dict)steps_taken += 1rewards.append(obs.reward)actions.append(step_action_str)dones.append(obs.done)errors.append(step_error)# Track history so LLM can learn from mistakesaction_history.append({"action_str": step_action_str,"reward": obs.reward,"error": step_error,})# ── Grade all tasks ──grader = TaskGrader(env)16 unmodified lineserror=errors[i],)# [END] line — NO score= field, per submission speclog_end(success=success, steps=steps_taken, rewards=rewards)sys.exit(0)
123456789101112131415161718192021222324252627282930313233343536373839404142version: "1.0"metadata:name: "Healthcare Appointment Scheduling"description: "A reinforcement learning environment simulating a hospital appointment booking system."version: "1.0.0"author: "Antigravity AI"tags: ["healthcare", "scheduling", "optimization", "RL"]inference_script: "inference.py"environment:type: "discrete"observation_space:type: "dict"description: "Contains doctor slots, patient info, and waiting queue."action_space:type: "dict"description: "Actions include book, reschedule, cancel, and waitlist."endpoints:reset: "/reset"step: "/step"state: "/state"tasks: "/tasks"grader: "/grader"baseline: "/baseline"tasks:- id: task_1name: "Book an Appointment"difficulty: easydescription: "Successfully book an appointment when slots are available."score_range: [0.0, 1.0]- id: task_2name: "Handle Scheduling Conflicts"difficulty: mediumdescription: "Handle scheduling conflicts and rescheduling efficiently."score_range: [0.0, 1.0]- id: task_3name: "Priority Scheduling"difficulty: harddescription: "Optimize scheduling for multiple patients with different priorities."score_range: [0.0, 1.0]123456spec_version: 1name: healthcare_schedulingtype: spaceruntime: fastapiapp: server.app:appport: 7860
123456789101112131415161718192021222324[build-system]requires = ["setuptools>=61.0"]build-backend = "setuptools.backends.legacy:build"[project]name = "openenv-hackathon"version = "1.0.0"description = "Healthcare Appointment Scheduling RL Environment"requires-python = ">=3.10"dependencies = ["fastapi","uvicorn[standard]","pydantic","typing-extensions","openai","openenv-core>=0.2.0",][project.scripts]server = "server.app:main"[tool.setuptools.packages.find]where = ["."]include = ["app*", "server*"]123456789101112131415161718192021222324252627282930313233343536373839[build-system]requires = ["setuptools>=45", "wheel"]build-backend = "setuptools.build_meta"[project]name = "openenv-healthcare-scheduling"version = "1.0.0"description = "Healthcare Appointment Scheduling RL Environment for OpenEnv"requires-python = ">=3.10"dependencies = ["openenv-core>=0.2.0","openenv>=0.1.13","fastapi>=0.110.0","uvicorn[standard]>=0.27.0","pydantic>=2.5.0","httpx>=0.25.2","requests>=2.32.5","websockets","openai","aiofiles","typing-extensions",][project.optional-dependencies]dev = ["pytest>=8.0.0","pytest-cov>=4.0.0",][project.scripts]server = "server.app:main"[tool.setuptools]include-package-data = truepackages = ["app", "app.server", "server"]package-dir = { "app" = "app", "server" = "server" }[tool.setuptools.package-data]app = ["**/*.yaml", "**/*.yml", "**/*.md"]
123456fastapiuvicorn[standard]pydantictyping-extensionsopenaiaiofiles1234567891011fastapi>=0.110.0uvicorn[standard]>=0.27.0pydantic>=2.5.0openenv>=0.1.13openenv-core>=0.2.0httpx>=0.25.2requests>=2.32.5websocketsopenaiaiofilestyping-extensions
1# server package1"""Server package — OpenEnv HTTP server for Healthcare Scheduling."""
12345678from app.main import appimport uvicorndef main():uvicorn.run(app, host="0.0.0.0", port=7860)if __name__ == "__main__":main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188"""FastAPI application entry point for the Healthcare Scheduling environment.This module creates the HTTP server using the OpenEnv framework's create_app()factory, which automatically provides standardised endpoints:- POST /reset : Reset the environment- POST /step : Execute an action- GET /state : Get current environment state- GET /health : Health check- GET /schema : Action/Observation JSON schemas- WS /ws : WebSocket for persistent sessions- GET /web : Interactive web interface- GET /docs : Swagger/OpenAPI documentationUsage:uvicorn server.app:app --host 0.0.0.0 --port 7860"""from __future__ import annotationsimport osimport sysfrom pathlib import Path# ── Ensure project root is importable ───────────────────────────────SERVER_DIR = Path(__file__).resolve().parentPROJECT_ROOT = SERVER_DIR.parent# Insert PROJECT_ROOT first so 'app' resolves to the app/ package,# not server/app.py (which would shadow it).if str(PROJECT_ROOT) not in sys.path:sys.path.insert(0, str(PROJECT_ROOT))# ── Import environment and models ───────────────────────────────────from app.env import HealthcareEnvironmentfrom app.models import HealthcareAction, HealthcareObservation# ── Build the FastAPI app ───────────────────────────────────────────try:from openenv.core.env_server.http_server import create_appapp = create_app(HealthcareEnvironment,HealthcareAction,HealthcareObservation,env_name="healthcare_scheduling",max_concurrent_envs=1,)except ImportError:# Fallback: build a plain FastAPI app when openenv-core isn't availablefrom fastapi import FastAPIfrom fastapi.staticfiles import StaticFilesfrom fastapi.responses import FileResponse, JSONResponsefrom app.agent import BaselineAgentfrom app.tasks import TASKS, TaskGraderDESCRIPTION = """\## Healthcare Appointment Scheduling — OpenEnv EnvironmentRL environment simulating a hospital appointment booking system.### Endpoints- `POST /reset` — Start a new episode- `POST /step` — Execute an action- `GET /state` — Current observation- `GET /health` — Container health check- `GET /tasks` — Task definitions- `GET /grader` — Grading scores- `GET /baseline` — Baseline agent performance"""app = FastAPI(title="Healthcare Scheduling — OpenEnv",version="1.0.0",description=DESCRIPTION,)# Serve static filesSTATIC_DIR = os.path.join(PROJECT_ROOT, "static")if os.path.isdir(STATIC_DIR):app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")@app.get("/", include_in_schema=False)def serve_frontend():return FileResponse(os.path.join(STATIC_DIR, "index.html"))# Global environment instanceenv = HealthcareEnvironment()@app.get("/health")def health_check():return {"status": "healthy", "service": "healthcare_scheduling"}@app.api_route("/reset", methods=["GET", "POST"])def reset_env():obs = env.reset()return {"observation": obs.model_dump() if hasattr(obs, "model_dump") else obs.__dict__,"info": {},}@app.post("/step")def step_env(action: HealthcareAction):obs = env.step(action)return {"observation": obs.model_dump() if hasattr(obs, "model_dump") else obs.__dict__,"reward": obs.reward,"done": obs.done,"info": obs.info or {},}@app.get("/state")def get_state():return {"state": {"doctor_slots": {str(k): v for k, v in env.doctor_slots.items()},"patients": {str(k): v for k, v in env.patients.items()},"waiting_queue": [str(p) for p in env.waiting_queue],"current_step": env.current_step,}}@app.get("/schema")def get_schema():return {"action_schema": HealthcareAction.model_json_schema(),"observation_schema": HealthcareObservation.model_json_schema(),}@app.get("/tasks")def list_tasks():return [task.__dict__ for task in TASKS]@app.get("/grader")def get_grader_scores():grader = TaskGrader(env)return {"task_scores": {"task_1": grader.grade_task_1(),"task_2": grader.grade_task_2(),"task_3": grader.grade_task_3(),}}@app.get("/baseline")def run_baseline():env.reset()agent = BaselineAgent(env)while not env.done:obs_dict = {"doctor_slots": {str(k): v for k, v in env.doctor_slots.items()},"patients": {str(k): v for k, v in env.patients.items()},"waiting_queue": [str(p) for p in env.waiting_queue],}action = agent.select_action(obs_dict)env.step_dict(action)grader = TaskGrader(env)return {"task_scores": {"task_1": grader.grade_task_1(),"task_2": grader.grade_task_2(),"task_3": grader.grade_task_3(),}}# ── Direct execution ────────────────────────────────────────────────def main(host: str = "0.0.0.0", port: int | None = None):"""Run the Healthcare Scheduling server."""import uvicornif port is None:port = int(os.getenv("API_PORT", "7860"))uvicorn.run(app, host=host, port=port)if __name__ == "__main__":import argparseparser = argparse.ArgumentParser()parser.add_argument("--port", type=int, default=7860)args = parser.parse_args()main(port=args.port)
123456789101112131415161718192021222324252627282930313233343536373839404142import sysimport ossys.path.append('d:/Meta_Hackathon')from app.env import HealthcareEnvfrom app.agent import BaselineAgentfrom app.tasks import TaskGraderdef test():print("Testing Healthcare RL Environment...")env = HealthcareEnv()obs = env.reset()print("Reset successful.")agent = BaselineAgent(env)print("Agent initialized.")steps = 0while not env.done:action = agent.select_action(obs)obs, reward, done, info = env.step(action)steps += 1print(f"Environment finished in {steps} steps.")grader = TaskGrader(env)scores = {"task_1": grader.grade_task_1(),"task_2": grader.grade_task_2(),"task_3": grader.grade_task_3()}print(f"Grader Scores: {scores}")assert scores["task_1"] > 0assert scores["task_2"] > 0assert scores["task_3"] > 0print("Verification successful!")if __name__ == "__main__":test()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081"""Quick verification script for the Healthcare RL Environment.Tests:1. Environment reset works2. Baseline agent can play a full episode3. Grader returns positive scores for all 3 tasks4. Typed action/observation interface works"""import sysimport ossys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from app.env import HealthcareEnvironmentfrom app.models import HealthcareActionfrom app.agent import BaselineAgentfrom app.tasks import TaskGraderdef test():print("=" * 60)print("Testing Healthcare RL Environment (OpenEnv)")print("=" * 60)# 1. Resetenv = HealthcareEnvironment(seed=42)obs = env.reset()print(f"[OK] Reset successful - {len(obs.waiting_queue)} patients waiting")# 2. Test typed stepaction = HealthcareAction(type="book", patient_id=0, doctor_id=0, slot_id=0)obs = env.step(action)print(f"[OK] Typed step works - reward={obs.reward:.2f}, done={obs.done}")# 3. Reset and run baseline agentenv = HealthcareEnvironment(seed=42)obs = env.reset()agent = BaselineAgent(env)print("[OK] Agent initialized")steps = 0while not env.done:obs_dict = {"doctor_slots": obs.doctor_slots,"patients": obs.patients,"waiting_queue": obs.waiting_queue,}action_dict = agent.select_action(obs_dict)action = HealthcareAction(type=action_dict["type"],patient_id=action_dict["patient_id"],doctor_id=action_dict.get("doctor_id"),slot_id=action_dict.get("slot_id"),)obs = env.step(action)steps += 1print(f"[OK] Environment finished in {steps} steps")# 4. Gradegrader = TaskGrader(env)scores = {"task_1": grader.grade_task_1(),"task_2": grader.grade_task_2(),"task_3": grader.grade_task_3(),}print(f"[OK] Grader Scores: {scores}")assert scores["task_1"] > 0, f"task_1 score should be > 0, got {scores['task_1']}"assert scores["task_2"] > 0, f"task_2 score should be > 0, got {scores['task_2']}"assert scores["task_3"] > 0, f"task_3 score should be > 0, got {scores['task_3']}"print("\n[PASS] All verifications passed!")print("=" * 60)if __name__ == "__main__":test()
.gitignoreAdded+12
Dockerfile+31-4
README.md+135-49
app/__init__.py+11-1
app/__pycache__/__init__.cpython-310.pycDeleted
app/__pycache__/__init__.cpython-311.pycDeleted
app/__pycache__/__init__.cpython-313.pycDeleted
app/__pycache__/agent.cpython-310.pycDeleted
app/__pycache__/agent.cpython-311.pycDeleted
app/__pycache__/agent.cpython-313.pycDeleted
app/__pycache__/env.cpython-310.pycDeleted
app/__pycache__/env.cpython-311.pycDeleted
app/__pycache__/env.cpython-313.pycDeleted
app/__pycache__/main.cpython-310.pycDeleted
app/__pycache__/models.cpython-310.pycDeleted
app/__pycache__/tasks.cpython-310.pycDeleted
app/__pycache__/tasks.cpython-311.pycDeleted
app/__pycache__/tasks.cpython-313.pycDeleted
app/agent.py+46-21
app/env.py+253-63
app/main.py+63-101
app/models.py+78-7
client.pyAdded+81
inference.py+174-51
openenv.yaml+6-42
pyproject.toml+27-12
requirements.txt+9-4
server/__init__.py+1-1
server/app.py+185-5
test_env.py+61-22