Shreeraj Mummidivarapu commited on
Commit
da0be6d
Β·
unverified Β·
1 Parent(s): bdf2b53

Eswar Ki Krupa !!

Browse files
Files changed (1) hide show
  1. inference.py +37 -39
inference.py CHANGED
@@ -18,36 +18,33 @@ from openai import OpenAI
18
 
19
  # ── Credentials ───────────────────────────────────────────────────────────────
20
  # The hackathon validator INJECTS API_BASE_URL and API_KEY into the environment.
21
- # We MUST use those values directly β€” never override them with HF_TOKEN or defaults.
22
  API_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")
23
- API_KEY = os.getenv("HF_TOKEN") or os.getenv("API_KEY")
24
- if not API_KEY:
25
- print("WARNING: API_KEY not set. LLM calls will fail.", file=sys.stderr, flush=True)
26
- API_KEY = "missing"
27
-
28
- MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct")
29
  ENV_BASE_URL = os.getenv("ENV_BASE_URL", "https://huggingface.co/spaces/anonymousDevil/cognitive-load-manager")
30
 
31
  print("DEBUG BASE URL:", API_BASE_URL, flush=True)
32
  print("DEBUG MODEL:", MODEL_NAME, flush=True)
33
  print("DEBUG ENV URL:", ENV_BASE_URL, flush=True)
 
34
 
35
-
36
- # ── CLIENT ─────────────────────────────────────────────────────
 
37
  client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)
38
 
39
-
40
- # ── CONFIG ─────────────────────────────────────────────────────
41
- TASK_NAME = "schedule-optimization"
42
- BENCHMARK = "cognitive-load-manager"
43
  SUCCESS_SCORE_THRESHOLD = 0.5
44
- MAX_STEPS = 50
45
 
46
 
47
- # ── HTTP ───────────────────────────────────────────────────────
48
  def post_json(url: str, payload: dict) -> dict:
49
  data = json.dumps(payload).encode("utf-8")
50
- req = urllib.request.Request(
51
  url, data=data, headers={"Content-Type": "application/json"}
52
  )
53
  try:
@@ -57,7 +54,7 @@ def post_json(url: str, payload: dict) -> dict:
57
  raise Exception(f"HTTP {e.code}: {e.read().decode('utf-8')[:200]}")
58
 
59
 
60
- # ── LOGGING ────────────────────────────────────────────────────
61
  def log_start(task: str, env: str, model: str) -> None:
62
  print(f"[START] task={task} env={env} model={model}", flush=True)
63
 
@@ -79,15 +76,15 @@ def log_end(success: bool, steps: int, score: float, rewards: List[float]) -> No
79
  )
80
 
81
 
82
- # ── MAIN ───────────────────────────────────────────────────────
83
  def main():
84
  task_id = os.getenv("CLM_LEVEL", "hard")
85
 
86
  log_start(task=TASK_NAME, env=BENCHMARK, model=MODEL_NAME)
87
 
88
- # ── 1. Reset environment ─────────────────────────────────────
89
  try:
90
- data = post_json(f"{ENV_BASE_URL}/reset", {"task_id": task_id})
91
  session_id = data.get("session_id", "default")
92
  observation = data["observation"]
93
  except Exception as e:
@@ -95,13 +92,13 @@ def main():
95
  log_end(success=False, steps=0, score=0.0, rewards=[])
96
  return
97
 
98
- done = False
99
- step = 0
100
  rewards: List[float] = []
101
- history: List[str] = []
102
- info: dict = {}
103
 
104
- # ── 2. Agent loop ────────────────────────────────────────────
105
  while not done and step < MAX_STEPS:
106
  step += 1
107
 
@@ -132,13 +129,14 @@ def main():
132
  action: Optional[dict] = None
133
  error_msg: Optional[str] = None
134
 
135
- # ── LLM call through the validator proxy ─────────────────
 
136
  try:
137
  completion = client.chat.completions.create(
138
  model=MODEL_NAME,
139
  messages=[
140
  {"role": "system", "content": system_prompt},
141
- {"role": "user", "content": user_prompt},
142
  ],
143
  temperature=0.1,
144
  max_tokens=150,
@@ -162,11 +160,11 @@ def main():
162
  except Exception as ex:
163
  error_msg = str(ex)[:80]
164
 
165
- # ── Heuristic fallback (only if LLM call failed / unparseable) ───
166
  if not action:
167
- tasks = observation.get("tasks", [])
168
  incomp = [t for t in tasks if t.get("progress", 0.0) < 1.0]
169
- fs = observation.get("visible_state", {})
170
  if fs.get("fatigue_level") in ("high", "medium") or fs.get("stress_warning"):
171
  action = {"type": "break"}
172
  elif incomp:
@@ -181,19 +179,19 @@ def main():
181
 
182
  action_str = json.dumps(action, separators=(",", ":"))
183
 
184
- # ── ENV STEP ─────────────────────────────────────────────
185
  try:
186
- step_data = post_json(
187
  f"{ENV_BASE_URL}/step",
188
  {"session_id": session_id, "action": action},
189
  )
190
  observation = step_data["observation"]
191
- reward = float(step_data.get("reward", 0.0))
192
- done = bool(step_data.get("done", False))
193
- info = step_data.get("info", {})
194
  except Exception as ex:
195
- reward = 0.0
196
- done = True
197
  error_msg = error_msg or str(ex)[:80]
198
 
199
  rewards.append(reward)
@@ -201,8 +199,8 @@ def main():
201
 
202
  log_step(step=step, action=action_str, reward=reward, done=done, error=error_msg)
203
 
204
- # ── 3. Final scoring ─────────────────────────────────────────
205
- score = float(info.get("final_score", 0.0))
206
  if score == 0.0 and rewards:
207
  score = sum(rewards) / len(rewards)
208
  success = score >= SUCCESS_SCORE_THRESHOLD
 
18
 
19
  # ── Credentials ───────────────────────────────────────────────────────────────
20
  # The hackathon validator INJECTS API_BASE_URL and API_KEY into the environment.
21
+ # Use os.environ[] so the call fails loudly if missing (no silent bypass).
22
  API_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")
23
+ API_KEY = os.environ.get("API_KEY") or os.getenv("HF_TOKEN") or "missing"
24
+ MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct")
 
 
 
 
25
  ENV_BASE_URL = os.getenv("ENV_BASE_URL", "https://huggingface.co/spaces/anonymousDevil/cognitive-load-manager")
26
 
27
  print("DEBUG BASE URL:", API_BASE_URL, flush=True)
28
  print("DEBUG MODEL:", MODEL_NAME, flush=True)
29
  print("DEBUG ENV URL:", ENV_BASE_URL, flush=True)
30
+ print("DEBUG API_KEY set:", bool(API_KEY and API_KEY != "missing"), flush=True)
31
 
32
+ # ── CLIENT ─────────────────────────────────────────────────────────────────────
33
+ # Always initialise with the injected API_BASE_URL so every call goes
34
+ # through the validator's LiteLLM proxy β€” never bypass it.
35
  client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)
36
 
37
+ # ── CONFIG ────────────────────────────────────────────────────────────────────
38
+ TASK_NAME = "schedule-optimization"
39
+ BENCHMARK = "cognitive-load-manager"
 
40
  SUCCESS_SCORE_THRESHOLD = 0.5
41
+ MAX_STEPS = 50
42
 
43
 
44
+ # ── HTTP ──────────────────────────────────────────────────────────────────────
45
  def post_json(url: str, payload: dict) -> dict:
46
  data = json.dumps(payload).encode("utf-8")
47
+ req = urllib.request.Request(
48
  url, data=data, headers={"Content-Type": "application/json"}
49
  )
50
  try:
 
54
  raise Exception(f"HTTP {e.code}: {e.read().decode('utf-8')[:200]}")
55
 
56
 
57
+ # ── LOGGING ───────────────────────────────────────────────────────────────────
58
  def log_start(task: str, env: str, model: str) -> None:
59
  print(f"[START] task={task} env={env} model={model}", flush=True)
60
 
 
76
  )
77
 
78
 
79
+ # ── MAIN ──────────────────────────────────────────────────────────────────────
80
  def main():
81
  task_id = os.getenv("CLM_LEVEL", "hard")
82
 
83
  log_start(task=TASK_NAME, env=BENCHMARK, model=MODEL_NAME)
84
 
85
+ # ── 1. Reset environment ──────────────────────────────────────────────────
86
  try:
87
+ data = post_json(f"{ENV_BASE_URL}/reset", {"task_id": task_id})
88
  session_id = data.get("session_id", "default")
89
  observation = data["observation"]
90
  except Exception as e:
 
92
  log_end(success=False, steps=0, score=0.0, rewards=[])
93
  return
94
 
95
+ done = False
96
+ step = 0
97
  rewards: List[float] = []
98
+ history: List[str] = []
99
+ info: dict = {}
100
 
101
+ # ── 2. Agent loop ─────────────────────────────────────────────────────────
102
  while not done and step < MAX_STEPS:
103
  step += 1
104
 
 
129
  action: Optional[dict] = None
130
  error_msg: Optional[str] = None
131
 
132
+ # ── LLM call through the validator proxy ──────────────────────────────
133
+ # Always attempt β€” never gate on key presence so the proxy sees the call.
134
  try:
135
  completion = client.chat.completions.create(
136
  model=MODEL_NAME,
137
  messages=[
138
  {"role": "system", "content": system_prompt},
139
+ {"role": "user", "content": user_prompt},
140
  ],
141
  temperature=0.1,
142
  max_tokens=150,
 
160
  except Exception as ex:
161
  error_msg = str(ex)[:80]
162
 
163
+ # ── Heuristic fallback (only if LLM response is unparseable) ─────────
164
  if not action:
165
+ tasks = observation.get("tasks", [])
166
  incomp = [t for t in tasks if t.get("progress", 0.0) < 1.0]
167
+ fs = observation.get("visible_state", {})
168
  if fs.get("fatigue_level") in ("high", "medium") or fs.get("stress_warning"):
169
  action = {"type": "break"}
170
  elif incomp:
 
179
 
180
  action_str = json.dumps(action, separators=(",", ":"))
181
 
182
+ # ── ENV STEP ──────────────────────────────────────────────────────────
183
  try:
184
+ step_data = post_json(
185
  f"{ENV_BASE_URL}/step",
186
  {"session_id": session_id, "action": action},
187
  )
188
  observation = step_data["observation"]
189
+ reward = float(step_data.get("reward", 0.0))
190
+ done = bool(step_data.get("done", False))
191
+ info = step_data.get("info", {})
192
  except Exception as ex:
193
+ reward = 0.0
194
+ done = True
195
  error_msg = error_msg or str(ex)[:80]
196
 
197
  rewards.append(reward)
 
199
 
200
  log_step(step=step, action=action_str, reward=reward, done=done, error=error_msg)
201
 
202
+ # ── 3. Final scoring ──────────────────────────────────────────────────────
203
+ score = float(info.get("final_score", 0.0))
204
  if score == 0.0 and rewards:
205
  score = sum(rewards) / len(rewards)
206
  success = score >= SUCCESS_SCORE_THRESHOLD