Spaces:
Sleeping
Sleeping
Subhash Vadaparthi commited on
Commit ·
41f9e98
1
Parent(s): 31993c7
Fix OpenEnv reset schema and enhance LLM inference script
Browse filesFiles changed (8)
12234533 unmodified lines3940414242434445464445464748495 unmodified lines555657585960616263636465646566676869707172737418 unmodified lines93949590969792989910010114 unmodified lines1161171181131141191201211221191231241211251261271281251291301311327 unmodified lines14014114213914314414514613 unmodified lines160161162159163164165166163167168165166169import randomfrom typing import Dict, List, Any, Optionalfrom typing import Dict, List, Any, Optional, Union
class HealthcareEnv: """33 unmodified lines return self._get_obs()
def _get_obs(self) -> Dict[str, Any]: """Returns the current observation of the environment.""" """Returns the current observation of the environment with string keys for JSON serialization.""" return { "doctor_slots": self.doctor_slots, "patients": self.patients, "waiting_queue": self.waiting_queue, "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 }
5 unmodified lines """ 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") patient_id = action.get("patient_id") doctor_id = action.get("doctor_id") slot_id = action.get("slot_id") # Robustly convert IDs to integers try: patient_id = int(action.get("patient_id")) if action.get("patient_id") is not None else None doctor_id = int(action.get("doctor_id")) if action.get("doctor_id") is not None else None slot_id = int(action.get("slot_id")) if action.get("slot_id") is not None else None except (ValueError, TypeError): return self._get_obs(), -1, self.done, {"error": "Invalid ID format (must be numeric)"}
reward = 0 info = {}18 unmodified lines
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, {"error": "Patient not in waiting queue or invalid ID"} return -1, {"error": f"Patient ID {patient_id} not available for booking"} if doctor_id not in self.doctor_slots or slot_id < 0 or slot_id >= self.num_slots: 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]:14 unmodified lines if self.patients[patient_id]["preferred_doctor"] == doctor_id: reward += 0.2 # Bonus for preferred doctor # Priority multiplier: higher priority (lower value) gets more weight? # Actually, let's just use fixed +1 and +0.3 for waitlist. return 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 booked"} return -1, {"error": "Patient not currently booked"}
if doctor_id not in self.doctor_slots or slot_id < 0 or slot_id >= self.num_slots: 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)"} return -1, {"error": "Target slot already booked (conflict)"}
# Free old slot old_doctor = self.patients[patient_id]["booked_doctor"]7 unmodified lines "booked_doctor": doctor_id }) return 0.5, {"status": "success"} # Partial reward for rescheduling 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":13 unmodified lines if patient_id not in self.waiting_queue: self.waiting_queue.append(patient_id) return -0.2, {"status": "cancelled"} # Penalty for cancellation 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 or already booked"} return -1, {"error": "Patient not in waiting queue"} # Just keep them in waiting queue, maybe prioritize later? # In this simple model, waitlist action is like "skip for now" return 0.3, {"status": "waitlisted"}13 unmodified lines141516171718192021222322232425262728292930313213 unmodified linesdef read_root(): return {"message": "Healthcare Appointment Scheduling RL Environment API"}
@app.post("/reset", response_model=ResetResponse)@app.api_route("/reset", methods=["GET", "POST"], response_model=ResetResponse)def reset_env(): obs = env.reset() return { "observation": obs, "reward": 0.0, "done": False, "info": {} }
@app.post("/step", response_model=StepResponse)def step_env(action: Action): # Convert Pydantic model to dict for environment handling action_dict = action.model_dump() if hasattr(action, "model_dump") else action.dict() obs, reward, done, info = env.step(action.dict()) obs, reward, done, info = env.step(action_dict) return { "observation": obs, "reward": reward,1212345678678910113 unmodified lines1516171819181920from pydantic import BaseModelfrom typing import Dict, Any, List, Optionalfrom pydantic import BaseModel, field_validatorfrom typing import Dict, Any, List, Optional, Union
class Action(BaseModel): type: str # book/reschedule/cancel/waitlist patient_id: int doctor_id: Optional[int] = None slot_id: Optional[int] = None patient_id: Union[int, str] doctor_id: Optional[Union[int, str]] = None slot_id: Optional[Union[int, str]] = None
class StepResponse(BaseModel): observation: Dict[str, Any]3 unmodified lines
class ResetResponse(BaseModel): observation: Dict[str, Any] reward: float = 0.0 done: bool = False info: Dict[str, Any] = {}
class StateResponse(BaseModel):1123454678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667688697071721213141573747518197677787980818283848586878823899091252692939495969798993334353637383940414210010110210310445105import sysimport osimport sysimport jsonfrom openai import OpenAIfrom app.env import HealthcareEnvfrom app.agent import BaselineAgentfrom app.tasks import TaskGrader
API_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")# Using HF_TOKEN or API_KEY, default to dummy for local testingAPI_KEY = os.getenv("HF_TOKEN") or os.getenv("API_KEY", "dummy")MODEL_NAME = os.getenv("MODEL_NAME", "meta-llama/Llama-3.1-8B-Instruct")
client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)
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 slot
Example Response:{{"type": "book", "patient_id": 0, "doctor_id": 1, "slot_id": 2}}
Reply with only the JSON object:"""
try: response = client.chat.completions.create( model=MODEL_NAME, messages=[{"role": "user", "content": prompt}], max_tokens=150, temperature=0.1 # Low temperature for more deterministic/stable responses ) text = response.choices[0].message.content.strip() # Strip potential markdown code blocks if text.startswith("```"): text = text.split("```")[1] if text.startswith("json"): text = text[4:].strip() text = text.strip() return json.loads(text) except Exception as e: print(f"Error parsing LLM response or calling API: {e}") # Fallback to a safe 'waitlist' action with valid numeric IDs if queue is not empty waiting_q = obs.get("waiting_queue", []) p_id = int(waiting_q[0]) if waiting_q else 0 return {"type": "waitlist", "patient_id": p_id, "doctor_id": 0, "slot_id": 0}
def run_inference(): print("Starting OpenEnv Inference...") print("Starting OpenEnv LLM Inference...") env = HealthcareEnv() obs = env.reset() print("Environment reset complete.") agent = BaselineAgent(env) print("Baseline Agent initialized.")
steps = 0 total_reward = 0 while not env.done: action = agent.select_action(obs)
while not env.done and steps < 20: print(f"\n--- Step {steps + 1} ---") action = get_action_from_llm(obs) print(f"Action Chosen: {action}") obs, reward, done, info = env.step(action) print(f"Reward: {reward}, Done: {done}") if "error" in info: print(f"Info Error: {info['error']}") total_reward += reward steps += 1
print("\n" + "="*30) print(f"Inference finished in {steps} steps.") print(f"Total Reward: {total_reward}") print(f"Total Cumulative Reward: {total_reward:.2f}")
grader = TaskGrader(env) scores = { "task_1": grader.grade_task_1(), "task_2": grader.grade_task_2(), "task_3": grader.grade_task_3() } print(f"Final Grader Scores: {scores}") # Ensure scores are valid if all(s >= 0 for s in scores.values()): print("Inference successful!") sys.exit(0) else: print("Inference failed: Negative scores detected.") sys.exit(1) print(f"Final Task Scores: {scores}") print("="*30) sys.exit(0)
if __name__ == "__main__": run_inference() run_inference()1 unmodified line23451 unmodified lineuvicorn[standard]pydantictyping-extensionsopenaiapp/__pycache__/agent.cpython-310.pyc
app/__pycache__/env.cpython-310.pyc
app/__pycache__/tasks.cpython-310.pyc
app/env.py+22-20
app/main.py+4-4
app/models.py+5-7
inference.py+83-23
requirements.txt+1