Spaces:
Sleeping
Sleeping
Subhash Vadaparthi commited on
Commit Β·
a9589c9
1
Parent(s): 7ad1b08
fix: rewrite inference.py to match sample format exactly - [START]/[STEP]/[END] with all required fields
Browse files123456789101112131415161728 unmodified lines464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120import 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.28 unmodified linesmodel=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():"""Runs LLM-based inference on the Healthcare Scheduling environmentand prints structured [START]/[STEP]/[END] output required by the OpenEnv validator."""# Define the tasks we will report ontask_defs = [{"name": "Book an Appointment", "grader": "grade_task_1"},{"name": "Handle Scheduling Conflicts", "grader": "grade_task_2"},{"name": "Priority Scheduling", "grader": "grade_task_3"},]env = HealthcareEnv()obs = env.reset()# ---------- Run the agent loop ----------step_num = 0cumulative_reward = 0.0step_log = [] # collect (step, reward) for each stepwhile not env.done and step_num < 20:action = get_action_from_llm(obs)obs, reward, done, info = env.step(action)cumulative_reward += rewardstep_num += 1step_log.append((step_num, reward))# ---------- Grade ----------grader = TaskGrader(env)# ---------- Emit structured output per task ----------for task_def in task_defs:task_name = task_def["name"]grade_fn = getattr(grader, task_def["grader"])task_score = grade_fn()# [START] blockprint(f"[START] task={task_name}", flush=True)# [STEP] blocks β replay the step log for each taskfor s, r in step_log:print(f"[STEP] step={s} reward={r}", flush=True)# [END] blockprint(f"[END] task={task_name} score={task_score:.4f} steps={step_num}", flush=True)# Also print a human-readable summary (after structured blocks)print(f"\nInference finished in {step_num} steps.", flush=True)print(f"Total Cumulative Reward: {cumulative_reward:.2f}", flush=True)sys.exit(0)if __name__ == "__main__":run_inference()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636428 unmodified lines93949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181"""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(f"[STEP] step={step} action={action} reward={reward:.2f} done={done_val} error={error_val}",flush=True,)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.28 unmodified linesmodel=MODEL_NAME,messages=[{"role": "user", "content": prompt}],max_tokens=150,temperature=0.1,)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"[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", "?")d = action.get("doctor_id", "?")s = action.get("slot_id", "?")return 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)# ββ Emit one structured [START]/[STEP]/[END] block per task ββfor task_def in task_defs:task_name = task_def["name"]grade_fn = getattr(grader, task_def["grader"])task_score = min(max(grade_fn(), 0.0), 1.0) # clamp to [0, 1]success = task_score > 0.0log_start(task=task_name, env=BENCHMARK, model=MODEL_NAME)for i in range(steps_taken):log_step(step=i + 1,action=actions[i],reward=rewards[i],done=dones[i],error=errors[i],)log_end(success=success, steps=steps_taken, score=task_score, rewards=rewards)sys.exit(0)if __name__ == "__main__":run_inference()
inference.py+97-36