Spaces:
Running
Running
Update inferenc.py
#5
by gensis88 - opened
- inference.py +519 -337
inference.py
CHANGED
|
@@ -1,337 +1,519 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Inference Script
|
| 3 |
-
===================================
|
| 4 |
-
Uses HuggingFace Inference Router (OpenAI-compatible API) to drive
|
| 5 |
-
|
| 6 |
-
OpenEnv spec exactly.
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
from
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
{
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
"
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
"
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|