Files changed (1) hide show
  1. inference.py +519 -337
inference.py CHANGED
@@ -1,337 +1,519 @@
1
- """
2
- Inference Script Example (Wildfire ICS Agent)
3
- ===================================
4
- Uses HuggingFace Inference Router (OpenAI-compatible API) to drive
5
- the language model through wildfire suppression tasks, matching the
6
- OpenEnv spec exactly.
7
- """
8
-
9
- import asyncio
10
- import os
11
- import json
12
- import argparse
13
- from typing import List, Optional, Dict, Any
14
-
15
- try:
16
- from dotenv import load_dotenv
17
- load_dotenv()
18
- except ImportError:
19
- pass
20
-
21
- from openai import OpenAI
22
- from client import WildfireClient
23
- from models import WildfireAction
24
-
25
- API_BASE_URL = os.getenv("API_BASE_URL") or "https://api.openai.com/v1"
26
- API_KEY = os.getenv("HF_TOKEN") or os.getenv("API_KEY", "dummy")
27
- MODEL_NAME = os.getenv("MODEL_NAME", "gpt-4o-mini")
28
- BENCHMARK = os.getenv("BENCHMARK", "wildfireEnvironment")
29
- IMAGE_NAME = os.getenv("IMAGE_NAME") # If using docker image
30
-
31
- MAX_STEPS = 15
32
- SUCCESS_SCORE_THRESHOLD = 0.5
33
-
34
-
35
- def log_start(task: str, env: str, model: str) -> None:
36
- print(f"[START] task={task} env={env} model={model}", flush=True)
37
-
38
-
39
- def log_step(step: int, action: str, reward: float, done: bool, error: Optional[str]) -> None:
40
- error_val = error if error else "null"
41
- done_val = str(done).lower()
42
- print(
43
- f"[STEP] step={step} action={action} reward={reward:.2f} done={done_val} error={error_val}",
44
- flush=True,
45
- )
46
-
47
-
48
- def log_end(success: bool, steps: int, score: float, rewards: List[float]) -> None:
49
- rewards_str = ",".join(f"{r:.2f}" for r in rewards)
50
- print(f"[END] success={str(success).lower()} steps={steps} score={score:.3f} rewards={rewards_str}", flush=True)
51
-
52
-
53
- def get_action_from_llm(client: OpenAI, obs: Dict[str, Any]) -> Dict[str, Any]:
54
- """
55
- Ask the LLM to choose a fire suppression action based on the current observation.
56
- Returns a dict with division_id, crew_id, action_type, target_cell.
57
- """
58
- grid = obs.get("grid", [])
59
- division_summary = {}
60
- for zone_info in obs.get("division_zones", []):
61
- label = zone_info["label"]
62
- burning = sum(
63
- 1 for r in range(zone_info["row_start"], zone_info["row_end"] + 1)
64
- for c in range(zone_info["col_start"], zone_info["col_end"] + 1)
65
- if grid[r][c] == 1
66
- )
67
- division_summary[label] = {"id": zone_info["id"], "burning_cells": burning}
68
-
69
- # Default fallback target
70
- busiest = max(division_summary.items(), key=lambda x: x[1]["burning_cells"])
71
- busiest_div_id = busiest[1]["id"]
72
- busiest_label = busiest[0]
73
- zone_meta = next(z for z in obs.get("division_zones", []) if z["label"] == busiest_label)
74
- target_cell = [zone_meta.get("row_start", 0) + 2, zone_meta.get("col_start", 0) + 2]
75
-
76
- found = False
77
- for r in range(zone_meta.get("row_start", 0), zone_meta.get("row_end", 0) + 1):
78
- for c in range(zone_meta.get("col_start", 0), zone_meta.get("col_end", 0) + 1):
79
- if grid and r < len(grid) and c < len(grid[0]) and grid[r][c] == 1:
80
- target_cell = [r, c]
81
- found = True
82
- break
83
- if found:
84
- break
85
-
86
- pct = obs.get("containment_pct", 0.0) * 100
87
- wind = obs.get("wind", {"direction": "NONE", "speed": 0})
88
- assets = obs.get("assets_at_risk", [])
89
-
90
- prompt = f"""You are an Incident Commander for a wildfire suppression operation.
91
- Current timestep: {obs.get('timestep', 0)}
92
- Containment: {pct:.1f}%
93
- Wind: {wind['direction']} at speed {wind['speed']}
94
- Division fire summary (burning cell counts):
95
- {json.dumps(division_summary, indent=2)}
96
- Assets at risk:
97
- {json.dumps([{a['name']: a['status']} for a in assets], indent=2)}
98
- Choose ONE action to direct a crew boss. Respond ONLY with a JSON object.
99
- JSON Keys:
100
- - "division_id": integer 0-3 (0=A, 1=B, 2=C, 3=D)
101
- - "crew_id": integer 0 or 1 (two crews per division)
102
- - "action_type": "SUPPRESS", "FIREBREAK", "MOVE", or "HOLD"
103
- - "target_cell": [row, col] (integers 0-19)
104
- Busiest division is {busiest_label} (id={busiest_div_id}) — suggested target: {target_cell}
105
- Reply with ONLY the JSON object:"""
106
-
107
- try:
108
- response = client.chat.completions.create(
109
- model=MODEL_NAME,
110
- messages=[{"role": "user", "content": prompt}],
111
- max_tokens=150,
112
- temperature=0.1,
113
- )
114
- text = response.choices[0].message.content.strip()
115
-
116
- if text.startswith("```"):
117
- text = text.split("```")[1]
118
- if text.startswith("json"):
119
- text = text[4:].strip()
120
- text = text.strip()
121
-
122
- action = json.loads(text)
123
- for key in ["division_id", "crew_id", "action_type", "target_cell"]:
124
- if key not in action:
125
- raise ValueError(f"Missing key: {key}")
126
- return action
127
-
128
- except Exception as e:
129
- print(f"[DEBUG] LLM fallback due to {e}", flush=True)
130
- return {
131
- "division_id": busiest_div_id,
132
- "crew_id": 0,
133
- "action_type": "SUPPRESS",
134
- "target_cell": target_cell,
135
- }
136
-
137
-
138
- async def main() -> None:
139
- parser = argparse.ArgumentParser(description="Run LLM inference on Wildfire ICS OpenEnv")
140
- parser.add_argument("--task", type=int, default=1, choices=[1, 2, 3],
141
- help="Task number (1=easy, 2=medium, 3=hard).")
142
- args = parser.parse_args()
143
-
144
- task = args.task
145
- task_name = {1: "single_front_containment", 2: "asset_protection", 3: "multi_front_outbreak"}.get(task, f"task_{task}")
146
-
147
- client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)
148
-
149
- log_start(task=task_name, env=BENCHMARK, model=MODEL_NAME)
150
-
151
- rewards: List[float] = []
152
- steps_taken = 0
153
- score = 0.0
154
- success = False
155
-
156
- try:
157
- if IMAGE_NAME:
158
- env = await WildfireClient.from_docker_image(IMAGE_NAME)
159
- eval_base_url = getattr(env, "_base_url", "http://localhost:8000")
160
- else:
161
- # Fallback to local running instance
162
- eval_base_url = "http://localhost:8000"
163
- env = WildfireClient(base_url=eval_base_url)
164
-
165
- async with env:
166
- # The client reset usually lacks kwargs, but we want to specify task=task
167
- # We call the HTTP manually if `reset(task=x)` isn't properly supported on client.
168
- import httpx
169
- async with httpx.AsyncClient() as http:
170
- await http.post(f"{eval_base_url}/reset", json={"task": task})
171
-
172
- result = await env.reset()
173
- obs_obj = result.observation
174
- obs_dict = obs_obj.model_dump() if hasattr(obs_obj, "model_dump") else obs_obj.dict()
175
-
176
- for step in range(1, MAX_STEPS + 1):
177
- if result.done:
178
- break
179
-
180
- action_dict = get_action_from_llm(client, obs_dict)
181
- action_str = json.dumps(action_dict).replace('"', "'") # remove internal double quotes for stdout
182
-
183
- result = await env.step(WildfireAction(**action_dict))
184
-
185
- obs_obj = result.observation
186
- obs_dict = obs_obj.model_dump() if hasattr(obs_obj, "model_dump") else obs_obj.dict()
187
-
188
- reward = result.reward or 0.0
189
- done = result.done
190
- error = None
191
-
192
- rewards.append(reward)
193
- steps_taken = step
194
-
195
- log_step(step=step, action=action_str, reward=reward, done=done, error=error)
196
-
197
- if done:
198
- break
199
-
200
- # Let's fetch score from our custom grader remotely
201
- async with httpx.AsyncClient() as http:
202
- resp = await http.get(f"{eval_base_url}/grader")
203
- if resp.status_code == 200:
204
- scores = resp.json().get("task_scores", {})
205
- score = scores.get(f"task_{task}", 0.0)
206
- else:
207
- score = sum(rewards) / MAX_STEPS
208
-
209
- success = score >= SUCCESS_SCORE_THRESHOLD
210
-
211
- except Exception as e:
212
- print(f"[ERROR] Inference failed: {e}", flush=True)
213
-
214
- finally:
215
- log_end(success=success, steps=steps_taken, score=score, rewards=rewards)
216
-
217
- async def run_inference(task: int = 1) -> dict:
218
- client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)
219
-
220
- rewards: List[float] = []
221
- steps_taken = 0
222
- score = 0.0
223
- success = False
224
-
225
- task_name = {
226
- 1: "single_front_containment",
227
- 2: "asset_protection",
228
- 3: "multi_front_outbreak"
229
- }.get(task, f"task_{task}")
230
-
231
- # ✅ START LOG
232
- log_start(task=task_name, env=BENCHMARK, model=MODEL_NAME)
233
-
234
- try:
235
- if IMAGE_NAME:
236
- env = await WildfireClient.from_docker_image(IMAGE_NAME)
237
- eval_base_url = getattr(env, "_base_url", "http://localhost:8000")
238
- else:
239
- eval_base_url = "http://localhost:8000"
240
- env = WildfireClient(base_url=eval_base_url)
241
-
242
- async with env:
243
- import httpx
244
- async with httpx.AsyncClient() as http:
245
- await http.post(f"{eval_base_url}/reset", json={"task": task})
246
-
247
- result = await env.reset()
248
- obs_obj = result.observation
249
- obs_dict = obs_obj.model_dump() if hasattr(obs_obj, "model_dump") else obs_obj.dict()
250
-
251
- for step in range(1, MAX_STEPS + 1):
252
- if result.done:
253
- break
254
-
255
- action_dict = get_action_from_llm(client, obs_dict)
256
-
257
- # For logging (string format)
258
- action_str = json.dumps(action_dict, separators=(",", ":"))
259
-
260
- result = await env.step(WildfireAction(**action_dict))
261
-
262
- obs_obj = result.observation
263
- obs_dict = obs_obj.model_dump() if hasattr(obs_obj, "model_dump") else obs_obj.dict()
264
-
265
- reward = result.reward or 0.0
266
- done = result.done
267
- error = None
268
-
269
- rewards.append(reward)
270
- steps_taken = step
271
-
272
- # ✅ STEP LOG
273
- log_step(
274
- step=step,
275
- action=action_str,
276
- reward=reward,
277
- done=done,
278
- error=error
279
- )
280
-
281
- if done:
282
- break
283
-
284
- async with httpx.AsyncClient() as http:
285
- resp = await http.get(f"{eval_base_url}/grader")
286
- if resp.status_code == 200:
287
- scores = resp.json().get("task_scores", {})
288
- score = scores.get(f"task_{task}", 0.0)
289
- else:
290
- score = sum(rewards) / MAX_STEPS
291
-
292
- success = score >= SUCCESS_SCORE_THRESHOLD
293
-
294
- except Exception as e:
295
- print(f"[ERROR] {e}", flush=True)
296
- success = False
297
-
298
- finally:
299
- # ✅ END LOG (ALWAYS runs)
300
- log_end(
301
- success=success,
302
- steps=steps_taken,
303
- score=score,
304
- rewards=rewards
305
- )
306
-
307
- return {
308
- "success": success,
309
- "steps": steps_taken,
310
- "score": score,
311
- "rewards": rewards,
312
- "task": task_name
313
- }
314
-
315
- if __name__ == "__main__":
316
- parser = argparse.ArgumentParser(description="Run LLM inference on Wildfire ICS OpenEnv")
317
- parser.add_argument(
318
- "--task",
319
- type=int,
320
- default=None,
321
- choices=[1, 2, 3],
322
- help="Task number (1=easy, 2=medium, 3=hard). Omit to run all 3.",
323
- )
324
- args = parser.parse_args()
325
-
326
- tasks_to_run = [args.task] if args.task else [1, 2, 3]
327
- all_scores = {}
328
-
329
- for t in tasks_to_run:
330
- result = asyncio.run(run_inference(task=t))
331
-
332
- if isinstance(result, dict) and "score" in result:
333
- all_scores[f"task_{t}"] = result["score"]
334
- else:
335
- all_scores[f"task_{t}"] = 0.0
336
-
337
- print(f"[SCORES] {json.dumps(all_scores)}", flush=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Inference Script — Wildfire ICS Agent
3
+ ======================================
4
+ Uses HuggingFace Inference Router (OpenAI-compatible API) to drive
5
+ a language model through wildfire suppression tasks, matching the
6
+ OpenEnv spec exactly.
7
+
8
+ Fixes applied vs original:
9
+ 1. MAX_STEPS is now per-task (30 / 50 / 75) instead of a hard 15
10
+ 2. LLM prompt includes full spatial context: grid map, asset positions,
11
+ wind direction, burning cells near assets, and firebreak tactics
12
+ 3. Multi-crew dispatch: one action per burning division per step
13
+ 4. Conversation history passed across steps so LLM has memory
14
+ 5. Removed duplicate main() / run_inference() duplication
15
+ 6. ActionType validated before sending to env
16
+ 7. Firebreak-ahead-of-wind strategy hint added to prompt
17
+ """
18
+
19
+ import asyncio
20
+ import os
21
+ import json
22
+ import argparse
23
+ from typing import List, Optional, Dict, Any, Tuple
24
+
25
+ try:
26
+ from dotenv import load_dotenv
27
+ load_dotenv()
28
+ except ImportError:
29
+ pass
30
+
31
+ from openai import OpenAI
32
+ from client import WildfireClient
33
+ from models import WildfireAction
34
+
35
+ API_BASE_URL = os.getenv("API_BASE_URL") or "https://api.openai.com/v1"
36
+ API_KEY = os.getenv("HF_TOKEN") or os.getenv("API_KEY", "dummy")
37
+ MODEL_NAME = os.getenv("MODEL_NAME", "gpt-4o-mini")
38
+ BENCHMARK = os.getenv("BENCHMARK", "wildfireEnvironment")
39
+ IMAGE_NAME = os.getenv("IMAGE_NAME")
40
+
41
+ # Per-task step limits matching the environment spec
42
+ TASK_MAX_STEPS = {1: 30, 2: 50, 3: 75}
43
+
44
+ SUCCESS_SCORE_THRESHOLD = 0.5
45
+
46
+ VALID_ACTION_TYPES = {"SUPPRESS", "FIREBREAK", "MOVE", "HOLD"}
47
+
48
+ # Wind direction → where to place firebreaks AHEAD of the fire
49
+ WIND_AHEAD = {
50
+ "N": (-1, 0), # fire moves north → firebreak north of burning cell
51
+ "S": (1, 0),
52
+ "E": (0, 1),
53
+ "W": (0, -1),
54
+ }
55
+
56
+
57
+ # ---------------------------------------------------------------------------
58
+ # Logging helpers
59
+ # ---------------------------------------------------------------------------
60
+
61
+ def log_start(task: str, env: str, model: str) -> None:
62
+ print(f"[START] task={task} env={env} model={model}", flush=True)
63
+
64
+
65
+ def log_step(step: int, action: str, reward: float, done: bool,
66
+ error: Optional[str]) -> None:
67
+ error_val = error if error else "null"
68
+ done_val = str(done).lower()
69
+ print(
70
+ f"[STEP] step={step} action={action} reward={reward:.2f} "
71
+ f"done={done_val} error={error_val}",
72
+ flush=True,
73
+ )
74
+
75
+
76
+ def log_end(success: bool, steps: int, score: float,
77
+ rewards: List[float]) -> None:
78
+ rewards_str = ",".join(f"{r:.2f}" for r in rewards)
79
+ print(
80
+ f"[END] success={str(success).lower()} steps={steps} "
81
+ f"score={score:.3f} rewards={rewards_str}",
82
+ flush=True,
83
+ )
84
+
85
+
86
+ # ---------------------------------------------------------------------------
87
+ # Observation helpers
88
+ # ---------------------------------------------------------------------------
89
+
90
+ def render_ascii_grid(grid: List[List[int]]) -> str:
91
+ """
92
+ Render a compact 20-row ASCII map of the grid so the LLM can reason
93
+ spatially. Symbols: . = clear, F = burning, X = burnt, # = firebreak
94
+ """
95
+ symbols = {0: ".", 1: "F", 2: "X", 3: "#"}
96
+ lines = []
97
+ for r, row in enumerate(grid):
98
+ line = "".join(symbols.get(cell, "?") for cell in row)
99
+ lines.append(f"{r:02d}|{line}")
100
+ header = " " + "".join(str(c % 10) for c in range(20))
101
+ return header + "\n" + "\n".join(lines)
102
+
103
+
104
+ def get_burning_cells(grid: List[List[int]]) -> List[Tuple[int, int]]:
105
+ return [
106
+ (r, c)
107
+ for r, row in enumerate(grid)
108
+ for c, val in enumerate(row)
109
+ if val == 1
110
+ ]
111
+
112
+
113
+ def firebreak_target_ahead(grid: List[List[int]], burning_cell: Tuple[int, int],
114
+ wind_dir: str) -> Optional[Tuple[int, int]]:
115
+ """Return the CLEAR cell directly ahead of a burning cell in wind direction."""
116
+ dr, dc = WIND_AHEAD.get(wind_dir, (0, 0))
117
+ r, c = burning_cell[0] + dr, burning_cell[1] + dc
118
+ if 0 <= r < 20 and 0 <= c < 20 and grid[r][c] == 0:
119
+ return (r, c)
120
+ return None
121
+
122
+
123
+ def build_division_summary(obs: Dict[str, Any]) -> Dict[str, Any]:
124
+ grid = obs.get("grid", [])
125
+ result = {}
126
+ for zone in obs.get("division_zones", []):
127
+ label = zone["label"]
128
+ burning = []
129
+ for r in range(zone["row_start"], zone["row_end"] + 1):
130
+ for c in range(zone["col_start"], zone["col_end"] + 1):
131
+ if grid and grid[r][c] == 1:
132
+ burning.append([r, c])
133
+ result[label] = {
134
+ "id": zone["id"],
135
+ "burning_count": len(burning),
136
+ "burning_cells": burning[:8], # first 8 to keep prompt short
137
+ "row_range": [zone["row_start"], zone["row_end"]],
138
+ "col_range": [zone["col_start"], zone["col_end"]],
139
+ }
140
+ return result
141
+
142
+
143
+ def asset_risk_summary(obs: Dict[str, Any]) -> List[Dict]:
144
+ """Return assets with distance-to-nearest-fire appended."""
145
+ grid = obs.get("grid", [])
146
+ assets = obs.get("assets_at_risk", [])
147
+ if not assets:
148
+ return []
149
+
150
+ burning = get_burning_cells(grid)
151
+ summary = []
152
+ for a in assets:
153
+ r, c = a["cell"]
154
+ if burning:
155
+ dist = min(abs(r - br) + abs(c - bc) for br, bc in burning)
156
+ else:
157
+ dist = 999
158
+ summary.append({
159
+ "name": a["name"],
160
+ "cell": a["cell"],
161
+ "status": a["status"],
162
+ "steps_to_fire": dist,
163
+ })
164
+ # Sort by proximity so the LLM knows what to protect first
165
+ summary.sort(key=lambda x: x["steps_to_fire"])
166
+ return summary
167
+
168
+
169
+ # ---------------------------------------------------------------------------
170
+ # LLM action selection (single action)
171
+ # ---------------------------------------------------------------------------
172
+
173
+ SYSTEM_PROMPT = """You are an expert Incident Commander for wildfire suppression.
174
+ You control crew bosses on a 20×20 grid. Cell states: . = clear, F = burning, X = burnt, # = firebreak.
175
+
176
+ STRATEGY RULES (follow strictly):
177
+ 1. SUPPRESS a burning cell (F) to extinguish it immediately (efficiency=1.0).
178
+ 2. FIREBREAK on a CLEAR cell (.) directly AHEAD of fire in wind direction blocks spread
179
+ (efficiency=0.5 but prevents future cells from burning).
180
+ 3. Prioritise assets that are closest to fire — place FIREBREAK between fire and asset.
181
+ 4. Never HOLD when fire is nearby — it wastes a step.
182
+ 5. Direct crews in divisions with the most burning cells first.
183
+
184
+ Always respond with ONLY a valid JSON object. No explanation, no markdown.
185
+ JSON keys: division_id (int 0-3), crew_id (int 0 or 1), action_type (SUPPRESS|FIREBREAK|MOVE|HOLD), target_cell ([row, col])"""
186
+
187
+
188
+ def get_action_from_llm(
189
+ client: OpenAI,
190
+ obs: Dict[str, Any],
191
+ history: List[Dict[str, str]],
192
+ task: int,
193
+ ) -> Tuple[Dict[str, Any], List[Dict[str, str]]]:
194
+ """
195
+ Ask the LLM for ONE action given the current observation.
196
+ Passes conversation history for continuity across steps.
197
+ Returns (action_dict, updated_history).
198
+ """
199
+ grid = obs.get("grid", [])
200
+ wind = obs.get("wind", {"direction": "N", "speed": 0.3})
201
+ div_sum = build_division_summary(obs)
202
+ assets = asset_risk_summary(obs)
203
+ pct = obs.get("containment_pct", 0.0) * 100
204
+ timestep = obs.get("timestep", 0)
205
+
206
+ ascii_map = render_ascii_grid(grid)
207
+
208
+ # Suggest best suppression target (busiest division, first burning cell)
209
+ busiest = max(div_sum.items(), key=lambda x: x[1]["burning_count"])
210
+ b_label, b_info = busiest
211
+ b_div_id = b_info["id"]
212
+ b_burning = b_info["burning_cells"]
213
+ suppress_target = b_burning[0] if b_burning else [0, 0]
214
+
215
+ # Suggest best firebreak target (ahead of closest burning cell in wind dir)
216
+ firebreak_target = None
217
+ all_burning = get_burning_cells(grid)
218
+ for bc in all_burning:
219
+ ft = firebreak_target_ahead(grid, bc, wind["direction"])
220
+ if ft:
221
+ firebreak_target = list(ft)
222
+ break
223
+ if not firebreak_target:
224
+ firebreak_target = suppress_target # fallback
225
+
226
+ user_msg = f"""=== Timestep {timestep} | Task {task} | Containment {pct:.1f}% ===
227
+ Wind: {wind['direction']} speed={wind['speed']}
228
+
229
+ GRID MAP (F=burning, X=burnt, #=firebreak, .=clear):
230
+ {ascii_map}
231
+
232
+ Division fire summary:
233
+ {json.dumps({k: {"id": v["id"], "burning": v["burning_count"], "sample_cells": v["burning_cells"]} for k, v in div_sum.items()}, indent=2)}
234
+
235
+ Assets (sorted by proximity to fire):
236
+ {json.dumps(assets, indent=2)}
237
+
238
+ Suggested targets:
239
+ - Best SUPPRESS target (busiest division {b_label}): {suppress_target}
240
+ - Best FIREBREAK target (ahead of fire, wind={wind['direction']}): {firebreak_target}
241
+
242
+ Choose ONE action. Reply ONLY with JSON:
243
+ {{"division_id": <0-3>, "crew_id": <0 or 1>, "action_type": "<SUPPRESS|FIREBREAK|MOVE|HOLD>", "target_cell": [<row>, <col>]}}"""
244
+
245
+ updated_history = history + [{"role": "user", "content": user_msg}]
246
+
247
+ try:
248
+ response = client.chat.completions.create(
249
+ model=MODEL_NAME,
250
+ messages=[{"role": "system", "content": SYSTEM_PROMPT}] + updated_history,
251
+ max_tokens=120,
252
+ temperature=0.1,
253
+ )
254
+ text = response.choices[0].message.content.strip()
255
+
256
+ # Strip markdown fences if present
257
+ if "```" in text:
258
+ text = text.split("```")[1]
259
+ if text.startswith("json"):
260
+ text = text[4:].strip()
261
+ text = text.strip()
262
+
263
+ action = json.loads(text)
264
+
265
+ # Validate required keys and types
266
+ action["division_id"] = int(action.get("division_id", b_div_id))
267
+ action["crew_id"] = int(action.get("crew_id", 0))
268
+ action["action_type"] = str(action.get("action_type", "SUPPRESS")).upper()
269
+ action["target_cell"] = [int(x) for x in action.get("target_cell", suppress_target)]
270
+
271
+ if action["action_type"] not in VALID_ACTION_TYPES:
272
+ action["action_type"] = "SUPPRESS"
273
+
274
+ # Clamp cell coordinates to grid bounds
275
+ action["target_cell"][0] = max(0, min(19, action["target_cell"][0]))
276
+ action["target_cell"][1] = max(0, min(19, action["target_cell"][1]))
277
+
278
+ # Append assistant reply to history
279
+ updated_history = updated_history + [
280
+ {"role": "assistant", "content": text}
281
+ ]
282
+
283
+ except Exception as e:
284
+ print(f"[DEBUG] LLM parse error: {e} — using fallback", flush=True)
285
+ action = {
286
+ "division_id": b_div_id,
287
+ "crew_id": 0,
288
+ "action_type": "SUPPRESS",
289
+ "target_cell": suppress_target,
290
+ }
291
+ updated_history = updated_history + [
292
+ {"role": "assistant", "content": json.dumps(action)}
293
+ ]
294
+
295
+ return action, updated_history
296
+
297
+
298
+ # ---------------------------------------------------------------------------
299
+ # Multi-crew dispatch (one action per burning division per step)
300
+ # ---------------------------------------------------------------------------
301
+
302
+ def get_multi_crew_actions(
303
+ client: OpenAI,
304
+ obs: Dict[str, Any],
305
+ history: List[Dict[str, str]],
306
+ task: int,
307
+ ) -> Tuple[List[Dict[str, Any]], List[Dict[str, str]]]:
308
+ """
309
+ For tasks with multiple burning divisions, dispatch one crew action
310
+ per active division per step. Returns list of actions + updated history.
311
+ """
312
+ div_sum = build_division_summary(obs)
313
+ grid = obs.get("grid", [])
314
+ wind_dir = obs.get("wind", {}).get("direction", "N")
315
+
316
+ # Collect burning divisions sorted by urgency
317
+ active = sorted(
318
+ [(label, info) for label, info in div_sum.items() if info["burning_count"] > 0],
319
+ key=lambda x: -x[1]["burning_count"],
320
+ )
321
+
322
+ if not active:
323
+ # Nothing burning — hold all crews
324
+ return [{
325
+ "division_id": 0, "crew_id": 0,
326
+ "action_type": "HOLD", "target_cell": [0, 0],
327
+ }], history
328
+
329
+ actions = []
330
+ current_history = history
331
+
332
+ for label, info in active[:3]: # cap at 3 divisions per step to avoid huge prompts
333
+ # Build focused single-division prompt instead of full LLM call for efficiency
334
+ div_id = info["id"]
335
+ burning = info["burning_cells"]
336
+ if not burning:
337
+ continue
338
+
339
+ # Heuristic: alternate between SUPPRESS and FIREBREAK
340
+ # SUPPRESS the closest burning cell; FIREBREAK ahead for the next crew
341
+ suppress_cell = burning[0]
342
+ fb_cell = None
343
+ for bc in burning:
344
+ ft = firebreak_target_ahead(grid, tuple(bc), wind_dir)
345
+ if ft:
346
+ fb_cell = list(ft)
347
+ break
348
+
349
+ # Crew 0: suppress
350
+ actions.append({
351
+ "division_id": div_id,
352
+ "crew_id": 0,
353
+ "action_type": "SUPPRESS",
354
+ "target_cell": suppress_cell,
355
+ })
356
+
357
+ # Crew 1: firebreak ahead of fire if possible, else suppress next cell
358
+ if fb_cell:
359
+ actions.append({
360
+ "division_id": div_id,
361
+ "crew_id": 1,
362
+ "action_type": "FIREBREAK",
363
+ "target_cell": fb_cell,
364
+ })
365
+ elif len(burning) > 1:
366
+ actions.append({
367
+ "division_id": div_id,
368
+ "crew_id": 1,
369
+ "action_type": "SUPPRESS",
370
+ "target_cell": burning[1],
371
+ })
372
+
373
+ # Also ask LLM for the primary (most critical) action with full context
374
+ if active:
375
+ llm_action, current_history = get_action_from_llm(
376
+ client, obs, current_history, task
377
+ )
378
+ # LLM action overrides our heuristic for the busiest division's crew 0
379
+ busiest_div_id = active[0][1]["id"]
380
+ for i, a in enumerate(actions):
381
+ if a["division_id"] == busiest_div_id and a["crew_id"] == 0:
382
+ actions[i] = llm_action
383
+ break
384
+ else:
385
+ actions.insert(0, llm_action)
386
+
387
+ return actions, current_history
388
+
389
+
390
+ # ---------------------------------------------------------------------------
391
+ # Main episode runner
392
+ # ---------------------------------------------------------------------------
393
+
394
+ async def run_inference(task: int = 1) -> dict:
395
+ max_steps = TASK_MAX_STEPS.get(task, 30)
396
+ task_name = {
397
+ 1: "single_front_containment",
398
+ 2: "asset_protection",
399
+ 3: "multi_front_outbreak",
400
+ }.get(task, f"task_{task}")
401
+
402
+ client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)
403
+ rewards: List[float] = []
404
+ steps_taken = 0
405
+ score = 0.0
406
+ success = False
407
+ history: List[Dict[str, str]] = [] # conversation history for LLM
408
+
409
+ log_start(task=task_name, env=BENCHMARK, model=MODEL_NAME)
410
+
411
+ try:
412
+ if IMAGE_NAME:
413
+ env = await WildfireClient.from_docker_image(IMAGE_NAME)
414
+ eval_base_url = getattr(env, "_base_url", "http://localhost:8000")
415
+ else:
416
+ eval_base_url = "http://localhost:8000"
417
+ env = WildfireClient(base_url=eval_base_url)
418
+
419
+ async with env:
420
+ import httpx
421
+ async with httpx.AsyncClient() as http:
422
+ await http.post(f"{eval_base_url}/reset", json={"task": task})
423
+
424
+ result = await env.reset()
425
+ obs_obj = result.observation
426
+ obs = obs_obj.model_dump() if hasattr(obs_obj, "model_dump") else obs_obj.dict()
427
+
428
+ for step in range(1, max_steps + 1):
429
+ if result.done:
430
+ break
431
+
432
+ # Get actions — multi-crew for task 3, single LLM action otherwise
433
+ if task == 3:
434
+ actions, history = get_multi_crew_actions(client, obs, history, task)
435
+ else:
436
+ primary, history = get_action_from_llm(client, obs, history, task)
437
+ actions = [primary]
438
+
439
+ # Execute all actions for this step
440
+ step_reward = 0.0
441
+ last_result = result
442
+
443
+ for action_dict in actions:
444
+ try:
445
+ last_result = await env.step(WildfireAction(**action_dict))
446
+ step_reward += last_result.reward or 0.0
447
+ if last_result.done:
448
+ break
449
+ except Exception as e:
450
+ print(f"[DEBUG] step error: {e}", flush=True)
451
+
452
+ result = last_result
453
+ obs_obj = result.observation
454
+ obs = obs_obj.model_dump() if hasattr(obs_obj, "model_dump") else obs_obj.dict()
455
+
456
+ done = result.done
457
+ rewards.append(step_reward)
458
+ steps_taken = step
459
+
460
+ # Log the primary action
461
+ primary_action_str = json.dumps(actions[0], separators=(",", ":"))
462
+ log_step(step=step, action=primary_action_str,
463
+ reward=step_reward, done=done, error=None)
464
+
465
+ if done:
466
+ break
467
+
468
+ # Fetch final grader score
469
+ async with httpx.AsyncClient() as http:
470
+ resp = await http.get(f"{eval_base_url}/grader")
471
+ if resp.status_code == 200:
472
+ scores = resp.json().get("task_scores", {})
473
+ score = scores.get(f"task_{task}", 0.0)
474
+ else:
475
+ score = sum(rewards) / max(steps_taken, 1)
476
+
477
+ success = score >= SUCCESS_SCORE_THRESHOLD
478
+
479
+ except Exception as e:
480
+ print(f"[ERROR] Inference failed: {e}", flush=True)
481
+ success = False
482
+
483
+ finally:
484
+ log_end(success=success, steps=steps_taken, score=score, rewards=rewards)
485
+
486
+ return {
487
+ "success": success,
488
+ "steps": steps_taken,
489
+ "score": score,
490
+ "rewards": rewards,
491
+ "task": task_name,
492
+ }
493
+
494
+
495
+ # ---------------------------------------------------------------------------
496
+ # Entry point
497
+ # ---------------------------------------------------------------------------
498
+
499
+ if __name__ == "__main__":
500
+ parser = argparse.ArgumentParser(
501
+ description="Run LLM inference on Wildfire ICS OpenEnv"
502
+ )
503
+ parser.add_argument(
504
+ "--task",
505
+ type=int,
506
+ default=None,
507
+ choices=[1, 2, 3],
508
+ help="Task number (1=easy, 2=medium, 3=hard). Omit to run all 3.",
509
+ )
510
+ args = parser.parse_args()
511
+
512
+ tasks_to_run = [args.task] if args.task else [1, 2, 3]
513
+ all_scores: Dict[str, float] = {}
514
+
515
+ for t in tasks_to_run:
516
+ result = asyncio.run(run_inference(task=t))
517
+ all_scores[f"task_{t}"] = result.get("score", 0.0)
518
+
519
+ print(f"[SCORES] {json.dumps(all_scores)}", flush=True)