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)
1234533 unmodified lines39404142434445464748495 unmodified lines555657585960616263646566676818 unmodified lines87888990919293949514 unmodified lines1101111121131141151161171181191201211221231241251261271287 unmodified lines13613713813914014114213 unmodified lines156157158159160161162163164165166167import randomfrom typing import Dict, List, Any, Optionalclass HealthcareEnv:"""33 unmodified linesreturn self._get_obs()def _get_obs(self) -> Dict[str, Any]:"""Returns the current observation of the environment."""return {"doctor_slots": self.doctor_slots,"patients": self.patients,"waiting_queue": 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}"""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")reward = 0info = {}18 unmodified linesdef _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"}if doctor_id not in self.doctor_slots 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 linesif 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"}if doctor_id not in self.doctor_slots 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)"}# Free old slotold_doctor = self.patients[patient_id]["booked_doctor"]7 unmodified lines"booked_doctor": doctor_id})return 0.5, {"status": "success"} # Partial reward for reschedulingdef _handle_cancel(self, patient_id) -> tuple:if patient_id not in self.patients or self.patients[patient_id]["status"] == "waiting":13 unmodified linesif patient_id not in self.waiting_queue:self.waiting_queue.append(patient_id)return -0.2, {"status": "cancelled"} # Penalty for cancellationdef _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"}# 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"}1234533 unmodified lines39404142434445464748495 unmodified lines555657585960616263646566676869707172737418 unmodified lines9394959697989910010114 unmodified lines1161171181191201211221231241251261271281291301311327 unmodified lines14014114214314414514613 unmodified lines160161162163164165166167168169import randomfrom typing import Dict, List, Any, Optional, Unionclass HealthcareEnv:"""33 unmodified linesreturn 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}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")# 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 = {}18 unmodified linesdef _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]:14 unmodified linesif 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"]7 unmodified lines"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":13 unmodified linesif 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"}
13 unmodified lines1415161718192021222324252627282930313213 unmodified linesdef read_root():return {"message": "Healthcare Appointment Scheduling RL Environment API"}@app.post("/reset", 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):obs, reward, done, info = env.step(action.dict())return {"observation": obs,"reward": reward,13 unmodified lines1415161718192021222324252627282930313213 unmodified linesdef read_root():return {"message": "Healthcare Appointment Scheduling RL Environment API"}@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,
12345678910113 unmodified lines1516171819202122from pydantic import BaseModelfrom typing import Dict, Any, List, Optionalclass Action(BaseModel):type: str # book/reschedule/cancel/waitlistpatient_id: intdoctor_id: Optional[int] = Noneslot_id: Optional[int] = Noneclass StepResponse(BaseModel):observation: Dict[str, Any]3 unmodified linesclass ResetResponse(BaseModel):observation: Dict[str, Any]reward: float = 0.0done: bool = Falseinfo: Dict[str, Any] = {}class StateResponse(BaseModel):12345678910113 unmodified lines151617181920from 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]3 unmodified linesclass ResetResponse(BaseModel):observation: Dict[str, Any]info: Dict[str, Any] = {}class StateResponse(BaseModel):
123456789101112131415161718192021222324252627282930313233343536373839404142434445import sysimport osfrom app.env import HealthcareEnvfrom app.agent import BaselineAgentfrom app.tasks import TaskGraderdef run_inference():print("Starting OpenEnv Inference...")env = HealthcareEnv()obs = env.reset()print("Environment reset complete.")agent = BaselineAgent(env)print("Baseline Agent initialized.")steps = 0total_reward = 0while not env.done:action = agent.select_action(obs)obs, reward, done, info = env.step(action)total_reward += rewardsteps += 1print(f"Inference finished in {steps} steps.")print(f"Total Reward: {total_reward}")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 validif all(s >= 0 for s in scores.values()):print("Inference successful!")sys.exit(0)else:print("Inference failed: Negative scores detected.")sys.exit(1)if __name__ == "__main__":run_inference()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105import osimport sysimport jsonfrom openai import OpenAIfrom app.env import HealthcareEnvfrom app.tasks import TaskGraderAPI_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 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(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 blocksif 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 emptywaiting_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}def run_inference():print("Starting OpenEnv LLM Inference...")env = HealthcareEnv()obs = env.reset()print("Environment reset complete.")steps = 0total_reward = 0while 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 += rewardsteps += 1print("\n" + "="*30)print(f"Inference finished in {steps} steps.")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 Task Scores: {scores}")print("="*30)sys.exit(0)if __name__ == "__main__":run_inference()
1 unmodified line2341 unmodified lineuvicorn[standard]pydantictyping-extensions1 unmodified line23451 unmodified lineuvicorn[standard]pydantictyping-extensionsopenai
app/__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