OpenEnv_Hackathon / inference.py
ayushrwt's picture gensis88's picture
Update inferenc.py (#5)
aeb4021
Raw History Blame Contribute Delete
18.6 kB
"""
Inference Script — Wildfire ICS Agent
======================================
Uses HuggingFace Inference Router (OpenAI-compatible API) to drive
a language model through wildfire suppression tasks, matching the
OpenEnv spec exactly.
Fixes applied vs original:
1. MAX_STEPS is now per-task (30 / 50 / 75) instead of a hard 15
2. LLM prompt includes full spatial context: grid map, asset positions,
wind direction, burning cells near assets, and firebreak tactics
3. Multi-crew dispatch: one action per burning division per step
4. Conversation history passed across steps so LLM has memory
5. Removed duplicate main() / run_inference() duplication
6. ActionType validated before sending to env
7. Firebreak-ahead-of-wind strategy hint added to prompt
"""
import asyncio
import os
import json
import argparse
from typing import List, Optional, Dict, Any, Tuple
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass
from openai import OpenAI
from client import WildfireClient
from models import WildfireAction
API_BASE_URL = os.getenv("API_BASE_URL") or "https://api.openai.com/v1"
API_KEY = os.getenv("HF_TOKEN") or os.getenv("API_KEY", "dummy")
MODEL_NAME = os.getenv("MODEL_NAME", "gpt-4o-mini")
BENCHMARK = os.getenv("BENCHMARK", "wildfireEnvironment")
IMAGE_NAME = os.getenv("IMAGE_NAME")
# Per-task step limits matching the environment spec
TASK_MAX_STEPS = {1: 30, 2: 50, 3: 75}
SUCCESS_SCORE_THRESHOLD = 0.5
VALID_ACTION_TYPES = {"SUPPRESS", "FIREBREAK", "MOVE", "HOLD"}
# Wind direction → where to place firebreaks AHEAD of the fire
WIND_AHEAD = {
"N": (-1, 0), # fire moves north → firebreak north of burning cell
"S": (1, 0),
"E": (0, 1),
"W": (0, -1),
}
# ---------------------------------------------------------------------------
# Logging helpers
# ---------------------------------------------------------------------------
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} "
f"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} "
f"score={score:.3f} rewards={rewards_str}",
flush=True,
)
# ---------------------------------------------------------------------------
# Observation helpers
# ---------------------------------------------------------------------------
def render_ascii_grid(grid: List[List[int]]) -> str:
"""
Render a compact 20-row ASCII map of the grid so the LLM can reason
spatially. Symbols: . = clear, F = burning, X = burnt, # = firebreak
"""
symbols = {0: ".", 1: "F", 2: "X", 3: "#"}
lines = []
for r, row in enumerate(grid):
line = "".join(symbols.get(cell, "?") for cell in row)
lines.append(f"{r:02d}|{line}")
header = " " + "".join(str(c % 10) for c in range(20))
return header + "\n" + "\n".join(lines)
def get_burning_cells(grid: List[List[int]]) -> List[Tuple[int, int]]:
return [
(r, c)
for r, row in enumerate(grid)
for c, val in enumerate(row)
if val == 1
]
def firebreak_target_ahead(grid: List[List[int]], burning_cell: Tuple[int, int],
wind_dir: str) -> Optional[Tuple[int, int]]:
"""Return the CLEAR cell directly ahead of a burning cell in wind direction."""
dr, dc = WIND_AHEAD.get(wind_dir, (0, 0))
r, c = burning_cell[0] + dr, burning_cell[1] + dc
if 0 <= r < 20 and 0 <= c < 20 and grid[r][c] == 0:
return (r, c)
return None
def build_division_summary(obs: Dict[str, Any]) -> Dict[str, Any]:
grid = obs.get("grid", [])
result = {}
for zone in obs.get("division_zones", []):
label = zone["label"]
burning = []
for r in range(zone["row_start"], zone["row_end"] + 1):
for c in range(zone["col_start"], zone["col_end"] + 1):
if grid and grid[r][c] == 1:
burning.append([r, c])
result[label] = {
"id": zone["id"],
"burning_count": len(burning),
"burning_cells": burning[:8], # first 8 to keep prompt short
"row_range": [zone["row_start"], zone["row_end"]],
"col_range": [zone["col_start"], zone["col_end"]],
}
return result
def asset_risk_summary(obs: Dict[str, Any]) -> List[Dict]:
"""Return assets with distance-to-nearest-fire appended."""
grid = obs.get("grid", [])
assets = obs.get("assets_at_risk", [])
if not assets:
return []
burning = get_burning_cells(grid)
summary = []
for a in assets:
r, c = a["cell"]
if burning:
dist = min(abs(r - br) + abs(c - bc) for br, bc in burning)
else:
dist = 999
summary.append({
"name": a["name"],
"cell": a["cell"],
"status": a["status"],
"steps_to_fire": dist,
})
# Sort by proximity so the LLM knows what to protect first
summary.sort(key=lambda x: x["steps_to_fire"])
return summary
# ---------------------------------------------------------------------------
# LLM action selection (single action)
# ---------------------------------------------------------------------------
SYSTEM_PROMPT = """You are an expert Incident Commander for wildfire suppression.
You control crew bosses on a 20×20 grid. Cell states: . = clear, F = burning, X = burnt, # = firebreak.
STRATEGY RULES (follow strictly):
1. SUPPRESS a burning cell (F) to extinguish it immediately (efficiency=1.0).
2. FIREBREAK on a CLEAR cell (.) directly AHEAD of fire in wind direction blocks spread
(efficiency=0.5 but prevents future cells from burning).
3. Prioritise assets that are closest to fire — place FIREBREAK between fire and asset.
4. Never HOLD when fire is nearby — it wastes a step.
5. Direct crews in divisions with the most burning cells first.
Always respond with ONLY a valid JSON object. No explanation, no markdown.
JSON keys: division_id (int 0-3), crew_id (int 0 or 1), action_type (SUPPRESS|FIREBREAK|MOVE|HOLD), target_cell ([row, col])"""
def get_action_from_llm(
client: OpenAI,
obs: Dict[str, Any],
history: List[Dict[str, str]],
task: int,
) -> Tuple[Dict[str, Any], List[Dict[str, str]]]:
"""
Ask the LLM for ONE action given the current observation.
Passes conversation history for continuity across steps.
Returns (action_dict, updated_history).
"""
grid = obs.get("grid", [])
wind = obs.get("wind", {"direction": "N", "speed": 0.3})
div_sum = build_division_summary(obs)
assets = asset_risk_summary(obs)
pct = obs.get("containment_pct", 0.0) * 100
timestep = obs.get("timestep", 0)
ascii_map = render_ascii_grid(grid)
# Suggest best suppression target (busiest division, first burning cell)
busiest = max(div_sum.items(), key=lambda x: x[1]["burning_count"])
b_label, b_info = busiest
b_div_id = b_info["id"]
b_burning = b_info["burning_cells"]
suppress_target = b_burning[0] if b_burning else [0, 0]
# Suggest best firebreak target (ahead of closest burning cell in wind dir)
firebreak_target = None
all_burning = get_burning_cells(grid)
for bc in all_burning:
ft = firebreak_target_ahead(grid, bc, wind["direction"])
if ft:
firebreak_target = list(ft)
break
if not firebreak_target:
firebreak_target = suppress_target # fallback
user_msg = f"""=== Timestep {timestep} | Task {task} | Containment {pct:.1f}% ===
Wind: {wind['direction']} speed={wind['speed']}
GRID MAP (F=burning, X=burnt, #=firebreak, .=clear):
{ascii_map}
Division fire summary:
{json.dumps({k: {"id": v["id"], "burning": v["burning_count"], "sample_cells": v["burning_cells"]} for k, v in div_sum.items()}, indent=2)}
Assets (sorted by proximity to fire):
{json.dumps(assets, indent=2)}
Suggested targets:
- Best SUPPRESS target (busiest division {b_label}): {suppress_target}
- Best FIREBREAK target (ahead of fire, wind={wind['direction']}): {firebreak_target}
Choose ONE action. Reply ONLY with JSON:
{{"division_id": <0-3>, "crew_id": <0 or 1>, "action_type": "<SUPPRESS|FIREBREAK|MOVE|HOLD>", "target_cell": [<row>, <col>]}}"""
updated_history = history + [{"role": "user", "content": user_msg}]
try:
response = client.chat.completions.create(
model=MODEL_NAME,
messages=[{"role": "system", "content": SYSTEM_PROMPT}] + updated_history,
max_tokens=120,
temperature=0.1,
)
text = response.choices[0].message.content.strip()
# Strip markdown fences if present
if "```" in text:
text = text.split("```")[1]
if text.startswith("json"):
text = text[4:].strip()
text = text.strip()
action = json.loads(text)
# Validate required keys and types
action["division_id"] = int(action.get("division_id", b_div_id))
action["crew_id"] = int(action.get("crew_id", 0))
action["action_type"] = str(action.get("action_type", "SUPPRESS")).upper()
action["target_cell"] = [int(x) for x in action.get("target_cell", suppress_target)]
if action["action_type"] not in VALID_ACTION_TYPES:
action["action_type"] = "SUPPRESS"
# Clamp cell coordinates to grid bounds
action["target_cell"][0] = max(0, min(19, action["target_cell"][0]))
action["target_cell"][1] = max(0, min(19, action["target_cell"][1]))
# Append assistant reply to history
updated_history = updated_history + [
{"role": "assistant", "content": text}
]
except Exception as e:
print(f"[DEBUG] LLM parse error: {e} — using fallback", flush=True)
action = {
"division_id": b_div_id,
"crew_id": 0,
"action_type": "SUPPRESS",
"target_cell": suppress_target,
}
updated_history = updated_history + [
{"role": "assistant", "content": json.dumps(action)}
]
return action, updated_history
# ---------------------------------------------------------------------------
# Multi-crew dispatch (one action per burning division per step)
# ---------------------------------------------------------------------------
def get_multi_crew_actions(
client: OpenAI,
obs: Dict[str, Any],
history: List[Dict[str, str]],
task: int,
) -> Tuple[List[Dict[str, Any]], List[Dict[str, str]]]:
"""
For tasks with multiple burning divisions, dispatch one crew action
per active division per step. Returns list of actions + updated history.
"""
div_sum = build_division_summary(obs)
grid = obs.get("grid", [])
wind_dir = obs.get("wind", {}).get("direction", "N")
# Collect burning divisions sorted by urgency
active = sorted(
[(label, info) for label, info in div_sum.items() if info["burning_count"] > 0],
key=lambda x: -x[1]["burning_count"],
)
if not active:
# Nothing burning — hold all crews
return [{
"division_id": 0, "crew_id": 0,
"action_type": "HOLD", "target_cell": [0, 0],
}], history
actions = []
current_history = history
for label, info in active[:3]: # cap at 3 divisions per step to avoid huge prompts
# Build focused single-division prompt instead of full LLM call for efficiency
div_id = info["id"]
burning = info["burning_cells"]
if not burning:
continue
# Heuristic: alternate between SUPPRESS and FIREBREAK
# SUPPRESS the closest burning cell; FIREBREAK ahead for the next crew
suppress_cell = burning[0]
fb_cell = None
for bc in burning:
ft = firebreak_target_ahead(grid, tuple(bc), wind_dir)
if ft:
fb_cell = list(ft)
break
# Crew 0: suppress
actions.append({
"division_id": div_id,
"crew_id": 0,
"action_type": "SUPPRESS",
"target_cell": suppress_cell,
})
# Crew 1: firebreak ahead of fire if possible, else suppress next cell
if fb_cell:
actions.append({
"division_id": div_id,
"crew_id": 1,
"action_type": "FIREBREAK",
"target_cell": fb_cell,
})
elif len(burning) > 1:
actions.append({
"division_id": div_id,
"crew_id": 1,
"action_type": "SUPPRESS",
"target_cell": burning[1],
})
# Also ask LLM for the primary (most critical) action with full context
if active:
llm_action, current_history = get_action_from_llm(
client, obs, current_history, task
)
# LLM action overrides our heuristic for the busiest division's crew 0
busiest_div_id = active[0][1]["id"]
for i, a in enumerate(actions):
if a["division_id"] == busiest_div_id and a["crew_id"] == 0:
actions[i] = llm_action
break
else:
actions.insert(0, llm_action)
return actions, current_history
# ---------------------------------------------------------------------------
# Main episode runner
# ---------------------------------------------------------------------------
async def run_inference(task: int = 1) -> dict:
max_steps = TASK_MAX_STEPS.get(task, 30)
task_name = {
1: "single_front_containment",
2: "asset_protection",
3: "multi_front_outbreak",
}.get(task, f"task_{task}")
client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)
rewards: List[float] = []
steps_taken = 0
score = 0.0
success = False
history: List[Dict[str, str]] = [] # conversation history for LLM
log_start(task=task_name, env=BENCHMARK, model=MODEL_NAME)
try:
if IMAGE_NAME:
env = await WildfireClient.from_docker_image(IMAGE_NAME)
eval_base_url = getattr(env, "_base_url", "http://localhost:8000")
else:
eval_base_url = "http://localhost:8000"
env = WildfireClient(base_url=eval_base_url)
async with env:
import httpx
async with httpx.AsyncClient() as http:
await http.post(f"{eval_base_url}/reset", json={"task": task})
result = await env.reset()
obs_obj = result.observation
obs = obs_obj.model_dump() if hasattr(obs_obj, "model_dump") else obs_obj.dict()
for step in range(1, max_steps + 1):
if result.done:
break
# Get actions — multi-crew for task 3, single LLM action otherwise
if task == 3:
actions, history = get_multi_crew_actions(client, obs, history, task)
else:
primary, history = get_action_from_llm(client, obs, history, task)
actions = [primary]
# Execute all actions for this step
step_reward = 0.0
last_result = result
for action_dict in actions:
try:
last_result = await env.step(WildfireAction(**action_dict))
step_reward += last_result.reward or 0.0
if last_result.done:
break
except Exception as e:
print(f"[DEBUG] step error: {e}", flush=True)
result = last_result
obs_obj = result.observation
obs = obs_obj.model_dump() if hasattr(obs_obj, "model_dump") else obs_obj.dict()
done = result.done
rewards.append(step_reward)
steps_taken = step
# Log the primary action
primary_action_str = json.dumps(actions[0], separators=(",", ":"))
log_step(step=step, action=primary_action_str,
reward=step_reward, done=done, error=None)
if done:
break
# Fetch final grader score
async with httpx.AsyncClient() as http:
resp = await http.get(f"{eval_base_url}/grader")
if resp.status_code == 200:
scores = resp.json().get("task_scores", {})
score = scores.get(f"task_{task}", 0.0)
else:
score = sum(rewards) / max(steps_taken, 1)
success = score >= SUCCESS_SCORE_THRESHOLD
except Exception as e:
print(f"[ERROR] Inference failed: {e}", flush=True)
success = False
finally:
log_end(success=success, steps=steps_taken, score=score, rewards=rewards)
return {
"success": success,
"steps": steps_taken,
"score": score,
"rewards": rewards,
"task": task_name,
}
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Run LLM inference on Wildfire ICS OpenEnv"
)
parser.add_argument(
"--task",
type=int,
default=None,
choices=[1, 2, 3],
help="Task number (1=easy, 2=medium, 3=hard). Omit to run all 3.",
)
args = parser.parse_args()
tasks_to_run = [args.task] if args.task else [1, 2, 3]
all_scores: Dict[str, float] = {}
for t in tasks_to_run:
result = asyncio.run(run_inference(task=t))
all_scores[f"task_{t}"] = result.get("score", 0.0)
print(f"[SCORES] {json.dumps(all_scores)}", flush=True)