adityss commited on
Commit
fe2f8c9
·
1 Parent(s): 588b24a

fix: provide fallback API key and add safety check for empty observations in inference client

Browse files
Files changed (2) hide show
  1. inference.py +3 -2
  2. python/inference.py +0 -557
inference.py CHANGED
@@ -170,7 +170,7 @@ class LLMAgent:
170
  # The OPENAI_API_KEY variable contains the HF_TOKEN value passed by evaluators
171
  self.client = OpenAI(
172
  base_url=API_BASE_URL,
173
- api_key=OPENAI_API_KEY,
174
  )
175
  self.model = MODEL_NAME
176
  self.fallback_mode = False
@@ -324,7 +324,8 @@ def run_episode(
324
  "sub_scores": {},
325
  "exploit_detected": False,
326
  }
327
- obs = reset_resp.get("observations", [{}])[0]
 
328
 
329
  task_name = f"gridmind-task-{task_id}"
330
 
 
170
  # The OPENAI_API_KEY variable contains the HF_TOKEN value passed by evaluators
171
  self.client = OpenAI(
172
  base_url=API_BASE_URL,
173
+ api_key=OPENAI_API_KEY or "dummy-key-for-fast-mode",
174
  )
175
  self.model = MODEL_NAME
176
  self.fallback_mode = False
 
324
  "sub_scores": {},
325
  "exploit_detected": False,
326
  }
327
+ obs_list = reset_resp.get("observations", [{}])
328
+ obs = obs_list[0] if obs_list else {}
329
 
330
  task_name = f"gridmind-task-{task_id}"
331
 
python/inference.py DELETED
@@ -1,557 +0,0 @@
1
- """
2
- GridMind-RL Baseline Inference Script
3
- --------------------------------------
4
- Runs an LLM agent against all 3 tasks for N episodes each.
5
- Uses the OpenAI Python client pointed at any OpenAI-compatible endpoint.
6
-
7
- Required environment variables (set in .env or shell):
8
- API_BASE_URL — The API endpoint for the LLM (default: OpenRouter)
9
- MODEL_NAME — The model identifier to use for inference
10
- OPENAI_API_KEY — API key for authentication (works with any provider)
11
-
12
- Usage:
13
- # Option 1: Use .env file (recommended — just paste your key)
14
- python inference.py
15
-
16
- # Option 2: Set env vars manually
17
- export API_BASE_URL=https://openrouter.ai/api/v1
18
- export MODEL_NAME=meta-llama/llama-3.1-8b-instruct:free
19
- export OPENAI_API_KEY=sk-or-v1-xxxx
20
- python inference.py
21
-
22
- # Option 3: Fast mode (no LLM, heuristic only)
23
- python inference.py --fast-mode --episodes 1
24
- """
25
-
26
- from __future__ import annotations
27
-
28
- import argparse
29
- import json
30
- import os
31
- import sys
32
- import time
33
- from typing import Any
34
-
35
- import requests
36
- from openai import OpenAI
37
-
38
- # ── Load .env file (if present) ────────────────────────────────────────────
39
- try:
40
- from dotenv import load_dotenv
41
- load_dotenv() # reads .env from current directory or project root
42
- except ImportError:
43
- pass # python-dotenv not installed — env vars must be set manually
44
-
45
- # ── Constants ──────────────────────────────────────────────────────────────
46
-
47
- ENV_URL = os.getenv("ENV_URL", "http://localhost:7860")
48
- MODEL_NAME = os.getenv("MODEL_NAME", "<your-active-model>")
49
- API_BASE_URL = os.getenv("API_BASE_URL", "<your-active-endpoint>")
50
-
51
- # ── Environment Variable Handling ─────────────────────────────────────────
52
- # The LLM API credential is read from HF_TOKEN or OPENAI_API_KEY environment variables
53
- # and passed directly to the OpenAI client for initialization.
54
- # Primary: HF_TOKEN
55
- # Fallback: OPENAI_API_KEY (for local testing/development)
56
- HF_TOKEN = os.getenv("HF_TOKEN")
57
- OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") or HF_TOKEN
58
- if not OPENAI_API_KEY:
59
- print("[WARN] No HF_TOKEN or OPENAI_API_KEY set - will use heuristic mode if --fast-mode is set")
60
- DEFAULT_EPISODES = 1
61
- DEFAULT_SEED_BASE = 1000
62
- MAX_RETRIES = 3
63
- # 96 steps × 15 min = 24 h (must match env.EpisodeSteps)
64
- EPISODE_STEPS = 96
65
- LAST_STEP_INDEX = EPISODE_STEPS - 1
66
-
67
- SYSPROMPT = """You are GridMind, an expert industrial energy management controller.
68
- You control a building's HVAC, thermal storage, batch job scheduling, and load shedding.
69
- Your goal is to minimize electricity costs while maintaining comfort and meeting grid demand-response signals.
70
- Always respond with a single valid JSON object matching the action schema. No explanation needed."""
71
-
72
- TASK_DESCRIPTIONS = {
73
- 1: "Task 1 (Easy - Cost Minimization): Minimize total energy cost over 24 hours. No temperature or batch constraints. Use cheap off-peak periods and thermal storage.",
74
- 2: "Task 2 (Medium - Temperature Management): Minimize cost AND keep indoor temperature within 19-23°C at all times. Balance comfort vs cost.",
75
- 3: "Task 3 (Hard - Full Demand Response): Minimize cost, maintain temperature, respond to grid stress (shed when grid_stress_signal > 0.7), schedule batch jobs, minimize carbon.",
76
- }
77
-
78
- ACTION_SCHEMA_STR = """{
79
- "hvac_power_level": <float 0.0-1.0>,
80
- "thermal_charge_rate": <float -1.0 to 1.0>,
81
- "batch_job_slot": <int 0-4>,
82
- "load_shed_fraction": <float 0.0-0.5>,
83
- "building_id": 0
84
- }"""
85
-
86
-
87
- def extract_json_object(text: str) -> dict[str, Any] | None:
88
- """Parse first balanced {...} JSON object from text (handles nested braces)."""
89
- start = text.find("{")
90
- if start < 0:
91
- return None
92
- depth = 0
93
- for i in range(start, len(text)):
94
- c = text[i]
95
- if c == "{":
96
- depth += 1
97
- elif c == "}":
98
- depth -= 1
99
- if depth == 0:
100
- try:
101
- return json.loads(text[start : i + 1])
102
- except json.JSONDecodeError:
103
- return None
104
- return None
105
-
106
-
107
- # ── Environment client ───────────────────────────────────────────────────────
108
-
109
-
110
- class GridMindEnvClient:
111
- """Simple HTTP client for the GridMind-RL Go environment server."""
112
-
113
- def __init__(self, base_url: str = ENV_URL, timeout: int = 30):
114
- self.base = base_url.rstrip("/")
115
- self.timeout = timeout
116
-
117
- def health(self) -> bool:
118
- try:
119
- r = requests.get(f"{self.base}/health", timeout=5)
120
- return r.status_code == 200
121
- except Exception:
122
- return False
123
-
124
- def reset(self, task_id: int = 1, seed: int = 42, num_buildings: int = 1) -> dict | None:
125
- try:
126
- payload = {"task_id": task_id, "seed": seed, "num_buildings": num_buildings}
127
- r = requests.post(f"{self.base}/reset", json=payload, timeout=self.timeout)
128
- r.raise_for_status()
129
- return r.json()
130
- except Exception as e:
131
- print(f"[ERROR] Failed to reset environment: {e}", file=sys.stderr)
132
- return None
133
-
134
- def step(self, action: dict) -> dict | None:
135
- try:
136
- r = requests.post(f"{self.base}/step", json=action, timeout=self.timeout)
137
- r.raise_for_status()
138
- return r.json()
139
- except Exception as e:
140
- print(f"[ERROR] Failed to step environment: {e}", file=sys.stderr)
141
- return None
142
-
143
- def grade(self) -> dict:
144
- try:
145
- r = requests.get(f"{self.base}/grade", timeout=self.timeout)
146
- r.raise_for_status()
147
- return r.json()
148
- except Exception as e:
149
- print(f"[ERROR] Failed to grade: {e}", file=sys.stderr)
150
- return {"score": 0.0, "sub_scores": {}, "exploit_detected": False}
151
-
152
- def state(self) -> dict | None:
153
- try:
154
- r = requests.get(f"{self.base}/state", timeout=self.timeout)
155
- r.raise_for_status()
156
- return r.json()
157
- except Exception as e:
158
- print(f"[ERROR] Failed to get state: {e}", file=sys.stderr)
159
- return None
160
-
161
-
162
- # ── LLM agent ───────────────────────────────────────────────────────────────
163
-
164
-
165
- class LLMAgent:
166
- """OpenAI-compatible LLM agent that chooses actions given observations."""
167
-
168
- def __init__(self):
169
- # Initialize OpenAI client with credentials from HF_TOKEN (per hackathon spec)
170
- # The OPENAI_API_KEY variable contains the HF_TOKEN value passed by evaluators
171
- self.client = OpenAI(
172
- base_url=API_BASE_URL,
173
- api_key=OPENAI_API_KEY,
174
- )
175
- self.model = MODEL_NAME
176
- self.fallback_mode = False
177
-
178
- def choose_action(self, obs: dict, task_id: int) -> dict:
179
- """Prompt the LLM with current observation, return parsed action dict."""
180
- if self.fallback_mode:
181
- return self._heuristic_action(obs)
182
- task_desc = TASK_DESCRIPTIONS.get(task_id, TASK_DESCRIPTIONS[1])
183
-
184
- prompt = f"""{task_desc}
185
-
186
- Current observation:
187
- - Indoor temperature: {obs.get('indoor_temperature', 21):.1f}°C (target: 21°C, bounds: 19-23°C)
188
- - Thermal storage level: {obs.get('thermal_storage_level', 0.5):.2f} (0=empty, 1=full)
189
- - Process demand: {obs.get('process_demand', 15):.1f} kW
190
- - Current electricity price: ${obs.get('current_price', 0.10):.4f}/kWh
191
- - Grid stress signal: {obs.get('grid_stress_signal', 0):.3f} (>0.7 = critical, shed load!)
192
- - Carbon intensity: {obs.get('carbon_intensity', 300):.0f} gCO2/kWh
193
- - Hour of day: {obs.get('hour_of_day', 12)} (0=midnight, peak prices 8-12 and 17-21)
194
- - Pending batch job deadlines: {obs.get('batch_queue', [])}
195
- - Cumulative cost so far: ${obs.get('cumulative_cost', 0):.4f}
196
- - Episode step: {obs.get('step', 0)}/{LAST_STEP_INDEX}
197
-
198
- Strategy hints:
199
- - Charge thermal storage when price < $0.08/kWh, discharge when price > $0.15/kWh
200
- - Set HVAC low during peak prices (0.3-0.4) and use storage for temperature control
201
- - Shed 30-50% load if grid_stress_signal > 0.7
202
- - Schedule batch jobs early if deadline is close (slot 0 or 1)
203
-
204
- Respond with ONLY a JSON action:
205
- {ACTION_SCHEMA_STR}"""
206
-
207
- for attempt in range(MAX_RETRIES):
208
- try:
209
- completion = self.client.chat.completions.create(
210
- model=self.model,
211
- messages=[
212
- {"role": "system", "content": SYSPROMPT},
213
- {"role": "user", "content": prompt},
214
- ],
215
- max_tokens=128,
216
- temperature=0.0,
217
- )
218
- content = completion.choices[0].message.content.strip()
219
- parsed = extract_json_object(content)
220
- if parsed is not None:
221
- return self._clamp_action(parsed)
222
- action = json.loads(content)
223
- return self._clamp_action(action)
224
- except Exception as e:
225
- err_str = str(e)
226
- print(f" [LLM attempt {attempt+1}/{MAX_RETRIES}] error: {err_str}")
227
- if "402" in err_str or "depleted" in err_str:
228
- print(" [WARN] Hugging Face free credits depleted! Switching to local heuristic agent for the rest of the simulation.")
229
- self.fallback_mode = True
230
- return self._heuristic_action(obs)
231
- time.sleep(1)
232
-
233
- return self._heuristic_action(obs)
234
-
235
- def _clamp_action(self, action: dict) -> dict:
236
- return {
237
- "hvac_power_level": max(0.0, min(1.0, float(action.get("hvac_power_level", 0.5)))),
238
- "thermal_charge_rate": max(-1.0, min(1.0, float(action.get("thermal_charge_rate", 0.0)))),
239
- "batch_job_slot": max(0, min(4, int(action.get("batch_job_slot", 0)))),
240
- "load_shed_fraction": max(0.0, min(0.5, float(action.get("load_shed_fraction", 0.0)))),
241
- "building_id": int(action.get("building_id", 0)),
242
- }
243
-
244
- def _heuristic_action(self, obs: dict) -> dict:
245
- """Rule-based policy (deterministic given obs)."""
246
- price = obs.get("current_price", 0.10)
247
- stress = obs.get("grid_stress_signal", 0.0)
248
- temp = obs.get("indoor_temperature", 21.0)
249
- storage = obs.get("thermal_storage_level", 0.5)
250
- queue = obs.get("batch_queue", [])
251
-
252
- hvac = 0.7 if price < 0.08 else (0.3 if price > 0.15 else 0.5)
253
- if temp > 23.0:
254
- hvac = max(hvac, 0.8)
255
- elif temp < 19.0:
256
- hvac = min(hvac, 0.2)
257
-
258
- charge = 0.0
259
- if price < 0.07 and storage < 0.8:
260
- charge = 0.5
261
- elif price > 0.15 and storage > 0.3:
262
- charge = -0.5
263
-
264
- shed = 0.0
265
- if stress > 0.7:
266
- shed = 0.4
267
- elif stress > 0.5:
268
- shed = 0.2
269
-
270
- slot = 2
271
- if queue and min(queue) < 8:
272
- slot = 0
273
-
274
- return {
275
- "hvac_power_level": hvac,
276
- "thermal_charge_rate": charge,
277
- "batch_job_slot": slot,
278
- "load_shed_fraction": shed,
279
- "building_id": 0,
280
- }
281
-
282
- def _default_action(self) -> dict:
283
- return {
284
- "hvac_power_level": 0.5,
285
- "thermal_charge_rate": 0.0,
286
- "batch_job_slot": 0,
287
- "load_shed_fraction": 0.0,
288
- "building_id": 0,
289
- }
290
-
291
-
292
- # ── Episode runner ───────────────────────────────────────────────────────────
293
-
294
-
295
- def run_episode(
296
- env_client: GridMindEnvClient,
297
- agent: LLMAgent,
298
- task_id: int,
299
- seed: int,
300
- *,
301
- fast_mode: bool,
302
- llm_every: int,
303
- max_steps: int | None,
304
- verbose: bool = False,
305
- ) -> dict[str, Any]:
306
- """Run a single episode and emit hackathon-compliant stdout format.
307
-
308
- Emits:
309
- [START] task=<name> env=gridmind model=<model>
310
- [STEP] step=<n> action=<json> reward=<0.00> done=<true|false> error=<msg|null>
311
- ...
312
- [END] success=<true|false> steps=<n> rewards=<r1,r2,...>
313
- """
314
- reset_resp = env_client.reset(task_id=task_id, seed=seed)
315
- if reset_resp is None:
316
- print(f"[END] success=false steps=0 rewards=", flush=True)
317
- return {
318
- "task_id": task_id,
319
- "seed": seed,
320
- "total_reward": 0.0,
321
- "total_steps": 0,
322
- "elapsed_sec": 0.0,
323
- "score": 0.0,
324
- "sub_scores": {},
325
- "exploit_detected": False,
326
- }
327
- obs = reset_resp.get("observations", [{}])[0]
328
-
329
- task_name = f"gridmind-task-{task_id}"
330
-
331
- # Emit [START] with required fields
332
- print(f"[START] task={task_name} env=gridmind model={MODEL_NAME}", flush=True)
333
-
334
- total_reward = 0.0
335
- total_steps = 0
336
- start_time = time.time()
337
- step_resp: dict[str, Any] = {}
338
- step_limit = EPISODE_STEPS if max_steps is None else min(max_steps, EPISODE_STEPS)
339
-
340
- llm_reuse_remaining = 0
341
- cached_action = agent._default_action()
342
-
343
- step_rewards: list[float] = []
344
- last_error: str | None = None
345
-
346
- while not step_resp.get("done", False):
347
- if total_steps >= step_limit:
348
- break
349
-
350
- try:
351
- if fast_mode:
352
- action = agent._heuristic_action(obs)
353
- else:
354
- if llm_reuse_remaining <= 0:
355
- cached_action = agent.choose_action(obs, task_id)
356
- llm_reuse_remaining = max(1, llm_every)
357
- action = cached_action
358
-
359
- step_resp = env_client.step(action)
360
- if step_resp is None or not isinstance(step_resp, dict) or "observation" not in step_resp:
361
- last_error = "invalid step response from environment"
362
- print(
363
- f"[STEP] step={total_steps + 1} action=null "
364
- f"reward=0.00 done=true error=\"{last_error}\"",
365
- flush=True
366
- )
367
- break
368
-
369
- if not fast_mode:
370
- llm_reuse_remaining -= 1
371
-
372
- obs = step_resp["observation"]
373
- reward = float(step_resp["reward"])
374
- total_reward += reward
375
- step_rewards.append(reward)
376
- total_steps += 1
377
- done = bool(step_resp.get("done", False))
378
-
379
- # Emit [STEP] with required fields (action as compact JSON, reward to 2 decimals)
380
- action_json = json.dumps(action, separators=(',', ':'))
381
- error_field = "null" if last_error is None else f'"{last_error}"'
382
- print(
383
- f"[STEP] step={total_steps} action={action_json} "
384
- f"reward={reward:.2f} done={'true' if done else 'false'} error={error_field}",
385
- flush=True
386
- )
387
-
388
- last_error = None # Clear error after successful step
389
-
390
- if verbose and total_steps % 16 == 0:
391
- print(
392
- f" step={total_steps:02d} price=${obs['current_price']:.3f} "
393
- f"temp={obs['indoor_temperature']:.1f}°C "
394
- f"stress={obs['grid_stress_signal']:.2f} "
395
- f"cost=${obs['cumulative_cost']:.2f}",
396
- flush=True,
397
- )
398
-
399
- except Exception as e:
400
- last_error = str(e)
401
- print(
402
- f"[STEP] step={total_steps + 1} action=null "
403
- f"reward=0.00 done=true error=\"{last_error}\"",
404
- flush=True
405
- )
406
- break
407
-
408
- elapsed = time.time() - start_time
409
- grade = env_client.grade()
410
-
411
- # Emit [END] with required fields
412
- success = last_error is None and step_resp.get("done", False)
413
- rewards_str = ",".join(f"{r:.2f}" for r in step_rewards)
414
- print(
415
- f"[END] success={'true' if success else 'false'} steps={total_steps} rewards={rewards_str}",
416
- flush=True
417
- )
418
-
419
- return {
420
- "task_id": task_id,
421
- "seed": seed,
422
- "total_reward": total_reward,
423
- "total_steps": total_steps,
424
- "elapsed_sec": elapsed,
425
- "score": grade.get("score", 0.0),
426
- "sub_scores": grade.get("sub_scores", {}),
427
- "exploit_detected": grade.get("exploit_detected", False),
428
- }
429
-
430
-
431
- # ── Main ─────────────────────────────────────────────────────────────────────
432
-
433
-
434
- def main() -> None:
435
- parser = argparse.ArgumentParser(description="GridMind-RL baseline inference")
436
- parser.add_argument("--episodes", type=int, default=DEFAULT_EPISODES)
437
- parser.add_argument("--env-url", type=str, default=ENV_URL)
438
- parser.add_argument("--verbose", action="store_true")
439
- parser.add_argument("--output", type=str, default="baseline_scores.json")
440
- parser.add_argument(
441
- "--fast-mode",
442
- action="store_true",
443
- help="Heuristic policy only (no LLM calls; fastest, fully reproducible).",
444
- )
445
- parser.add_argument(
446
- "--llm-every",
447
- type=int,
448
- default=4,
449
- metavar="N",
450
- help="Reuse the same LLM action for N consecutive steps (default: 4).",
451
- )
452
- parser.add_argument(
453
- "--max-steps",
454
- type=int,
455
- default=None,
456
- metavar="N",
457
- help="Stop after N steps (default: full episode). Grade uses partial episode.",
458
- )
459
- args = parser.parse_args()
460
-
461
- # Validate API key AFTER argparse (allows --fast-mode to bypass)
462
- if not OPENAI_API_KEY and not args.fast_mode:
463
- print("[WARN] No API key set, switching to fast-mode (heuristic)", file=sys.stderr)
464
- args.fast_mode = True
465
-
466
- print("=" * 60)
467
- print("GridMind-RL Baseline Inference")
468
- print(f" Model: {MODEL_NAME}")
469
- print(f" API: {API_BASE_URL}")
470
- print(f" Env: {args.env_url}")
471
- print(f" Episodes per task: {args.episodes}")
472
- print(f" Fast mode: {args.fast_mode} | LLM every: {args.llm_every} steps")
473
- print("=" * 60)
474
-
475
- env_client = GridMindEnvClient(base_url=args.env_url)
476
-
477
- print("\nWaiting for environment server...")
478
- for attempt in range(30):
479
- if env_client.health():
480
- print(" [OK] Environment server is healthy")
481
- break
482
- time.sleep(2)
483
- if attempt == 29:
484
- print(" [FAIL] Environment server not reachable. Exiting.")
485
- sys.exit(1)
486
-
487
- agent = LLMAgent()
488
- all_results: list[dict[str, Any]] = []
489
-
490
- for task_id in [1, 2, 3]:
491
- print(f"\n-- Task {task_id}: {TASK_DESCRIPTIONS[task_id][:60]}...")
492
- task_scores: list[float] = []
493
- for ep in range(args.episodes):
494
- seed = DEFAULT_SEED_BASE + task_id * 100 + ep
495
- print(f" Episode {ep+1}/{args.episodes} (seed={seed})")
496
- result = run_episode(
497
- env_client,
498
- agent,
499
- task_id=task_id,
500
- seed=seed,
501
- fast_mode=args.fast_mode,
502
- llm_every=args.llm_every,
503
- max_steps=args.max_steps,
504
- verbose=args.verbose,
505
- )
506
- task_scores.append(float(result["score"]))
507
- all_results.append(result)
508
- print(
509
- f" → score={result['score']:.4f} | reward={result['total_reward']:.3f} | "
510
- f"{result['elapsed_sec']:.1f}s | steps={result['total_steps']}"
511
- )
512
-
513
- avg_score = sum(task_scores) / len(task_scores)
514
- print(f" Task {task_id} average score: {avg_score:.4f}")
515
-
516
- print("\n" + "=" * 60)
517
- print("BASELINE SCORES SUMMARY")
518
- print("=" * 60)
519
- print(f"{'Task':<10} {'Model':<30} {'Score':<10} {'Episodes':<10}")
520
- print("-" * 60)
521
-
522
- task_avgs: dict[int, float] = {}
523
- for task_id in [1, 2, 3]:
524
- scores = [float(r["score"]) for r in all_results if r["task_id"] == task_id]
525
- avg = sum(scores) / len(scores) if scores else 0.0
526
- task_avgs[task_id] = avg
527
- print(f"Task {task_id:<6} {MODEL_NAME:<30} {avg:<10.4f} {len(scores)}")
528
-
529
- print("-" * 60)
530
- overall = sum(task_avgs.values()) / len(task_avgs)
531
- print(f"{'Overall':<10} {'':<30} {overall:<10.4f}")
532
-
533
- output = {
534
- "model": MODEL_NAME,
535
- "api_base": API_BASE_URL,
536
- "episodes_per_task": args.episodes,
537
- "seed_base": DEFAULT_SEED_BASE,
538
- "fast_mode": args.fast_mode,
539
- "llm_every": args.llm_every,
540
- "max_steps": args.max_steps,
541
- "task_averages": {str(k): v for k, v in task_avgs.items()},
542
- "overall_average": overall,
543
- "all_results": all_results,
544
- }
545
- with open(args.output, "w", encoding="utf-8") as f:
546
- json.dump(output, f, indent=2)
547
- print(f"\n[OK] Results saved to {args.output}")
548
-
549
-
550
- if __name__ == "__main__":
551
- try:
552
- main()
553
- except Exception as e:
554
- print(f"[FATAL] Unhandled exception: {e}", file=sys.stderr)
555
- import traceback
556
- traceback.print_exc(file=sys.stderr)
557
- sys.exit(1)