Spaces:
Runtime error
Runtime error
File size: 13,789 Bytes
1ffd0a4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 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 338 339 340 341 342 343 344 | """
Simulation Agent β Phase 12 (final pipeline stage).
Responsibility
--------------
Takes the response plan from Phase 8 and simulates its execution in a
mock environment, producing the before/after state comparison and dispatch
ticket that the mobile app's outcome visualization screen renders.
Architecture notes (multi-agent-patterns)
-----------------------------------------
This is the terminal stage of the sequential supervisor pipeline. It
receives verbatim outputs from detection, analysis, and planning β no
paraphrasing, no supervisor synthesis. The agent only reasons about AFTER
state and outcomes; before-state and dispatch-ticket are constructed
deterministically so they are always consistent and predictable.
Tool design (tool-design skill)
--------------------------------
This agent has no function tools β pure reasoning over provided context.
Adding tools would add coordination overhead with no upside: the simulation
is a one-shot structured-output call. The rich prompt context is sufficient.
"""
from __future__ import annotations
import logging
import random
from datetime import datetime, timezone
from typing import Any
from agents import Agent
from pydantic import ValidationError
from backend.agents.analysis import SituationReport
from backend.agents.detection import DetectionOutput
from backend.core.model import get_gemini_model
from backend.core.runner import run_agent
from backend.models.agent_result import AgentResult
from backend.models.risk import RiskTieringResult
from backend.models.simulation import (
DispatchTicket,
DispatchedUnit,
SimulationAgentOutput,
SimulationResult,
SystemState,
)
from backend.services.whatsapp import dispatch_emergency_whatsapp
logger = logging.getLogger(__name__)
# ββ Deterministic helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Severity β before-state congestion level (phase doc table).
_SEVERITY_TO_CONGESTION = {
1: "light",
2: "moderate",
3: "heavy",
4: "severe",
5: "severe",
}
# Standard Pakistani emergency units per crisis type.
_EMERGENCY_UNITS: dict[str, list[dict]] = {
"flood": [
{"service": "Rescue 1122", "units": 2, "eta_minutes": 8},
{"service": "Islamabad Police (15)", "units": 1, "eta_minutes": 5},
{"service": "EDHI Ambulance", "units": 1, "eta_minutes": 12},
],
"fire": [
{"service": "Islamabad Fire Brigade", "units": 2, "eta_minutes": 6},
{"service": "Rescue 1122", "units": 1, "eta_minutes": 8},
{"service": "Islamabad Police (15)", "units": 1, "eta_minutes": 5},
],
"accident": [
{"service": "EDHI Ambulance", "units": 2, "eta_minutes": 7},
{"service": "Islamabad Police (15)", "units": 1, "eta_minutes": 5},
{"service": "Rescue 1122", "units": 1, "eta_minutes": 10},
],
"building_collapse": [
{"service": "Rescue 1122", "units": 3, "eta_minutes": 8},
{"service": "Islamabad Fire Brigade", "units": 1, "eta_minutes": 6},
{"service": "EDHI Ambulance", "units": 2, "eta_minutes": 7},
],
"heatwave": [
{"service": "EDHI Ambulance", "units": 2, "eta_minutes": 10},
{"service": "CDA Emergency Services", "units": 1, "eta_minutes": 15},
],
"infrastructure": [
{"service": "CDA Emergency Services", "units": 2, "eta_minutes": 12},
{"service": "Islamabad Police (15)", "units": 1, "eta_minutes": 5},
],
"infrastructure_failure": [
{"service": "CDA Emergency Services", "units": 2, "eta_minutes": 12},
{"service": "Islamabad Police (15)", "units": 1, "eta_minutes": 5},
],
}
def build_before_state(situation_report: SituationReport) -> SystemState:
"""Construct the pre-response system state from the situation report.
Deterministic: severity maps directly to congestion level and area
status per the phase doc specification. All counters start at zero
(nothing has been deployed yet).
"""
return SystemState(
congestion_level=_SEVERITY_TO_CONGESTION.get(situation_report.severity, "heavy"),
affected_area_status="crisis active",
vehicles_rerouted=0,
emergency_units_deployed=0,
citizens_alerted=0,
ngos_activated=0,
)
def build_dispatch_ticket(
crisis_id: str,
detection_output: DetectionOutput,
situation_report: SituationReport,
risk_tiering_output: RiskTieringResult,
) -> DispatchTicket | None:
"""Build the emergency dispatch ticket, or None for low-risk crises.
Returns None when `requires_emergency_services=False` (traffic jam,
rainfall, road_blockage) β these crises use automated rerouting only.
"""
if not risk_tiering_output.requires_emergency_services:
return None
crisis_type = detection_output.crisis_type or "unknown"
raw_units = _EMERGENCY_UNITS.get(crisis_type, _EMERGENCY_UNITS["flood"])
units = [DispatchedUnit(**u) for u in raw_units]
year = datetime.now(timezone.utc).year
ticket_num = random.randint(1000, 9999) # noqa: S311 β demo ID, not security-critical
return DispatchTicket(
ticket_id=f"CIR-{year}-{ticket_num:04d}",
status="DISPATCHED",
crisis_id=crisis_id,
crisis_type=crisis_type,
location_label=detection_output.location_label or "unknown",
severity=situation_report.severity,
units_dispatched=units,
issued_at=datetime.now(timezone.utc),
)
# ββ Agent definition ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
_INSTRUCTIONS = """\
You are a crisis response simulation engine for Pakistani urban areas
(Islamabad, Karachi, Lahore).
You receive:
- A detected crisis (type, location, severity 1-5)
- A situation report (impacts, affected population)
- A response plan (immediate and short-term actions, resources needed)
- The BEFORE state of the affected area (congestion, status)
- Number of NGOs already alerted
Your job is to simulate the execution of the response plan and produce
the AFTER state plus a list of executed actions with realistic outcomes.
Rules:
1. AFTER state must show meaningful improvement from BEFORE:
- congestion_level must decrease (e.g. severe β heavy or moderate)
- affected_area_status must improve (crisis active β contained or resolved)
- vehicles_rerouted, emergency_units_deployed, citizens_alerted must be > 0
2. actions_executed must list at least 3 actions from the plan with:
- realistic simulated_effect in Pakistani urban context
- plausible duration_minutes (5β60)
- status: "completed" for immediate actions, "in_progress" for short-term
3. Use Pakistani emergency services where relevant:
Rescue 1122, Islamabad Police (15), EDHI, CDA, Islamabad Fire Brigade
4. Estimates must be plausible β not "100% resolved" or absurd numbers
5. ngos_activated in AFTER state must equal the provided NGO count
6. outcome_summary must be plain English readable by a non-technical coordinator
Return strictly as SimulationAgentOutput. Do not add prose outside the schema.
"""
simulation_agent = Agent(
name="simulation_agent",
instructions=_INSTRUCTIONS,
model=get_gemini_model(),
output_type=SimulationAgentOutput,
)
# ββ Prompt formatter ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _format_simulation_prompt(
detection_output: DetectionOutput,
situation_report: SituationReport,
planning_output: dict[str, Any],
before: SystemState,
ngos_activated: int,
) -> str:
"""Format all pipeline context into a single structured prompt for the agent.
Passes verbatim outputs from previous stages β no paraphrasing (avoids
the telephone-game problem described in the multi-agent-patterns skill).
"""
immediate = planning_output.get("immediate_actions", [])
short_term = planning_output.get("short_term_actions", [])
resources = planning_output.get("resources_needed", [])
lines = [
f"CRISIS: {detection_output.crisis_type} at {detection_output.location_label}",
f"SEVERITY: {situation_report.severity}/5 ({situation_report.severity_label})",
f"AFFECTED: {situation_report.affected_population_estimate}",
"",
"IMPACTS:",
*[f" - {impact}" for impact in situation_report.impacts],
"",
"BEFORE STATE:",
f" congestion_level: {before.congestion_level}",
f" affected_area_status: {before.affected_area_status}",
f" vehicles_rerouted: 0, emergency_units_deployed: 0, citizens_alerted: 0",
f" ngos_activated: 0",
"",
"NGOS ALREADY ALERTED: " + str(ngos_activated),
"",
"IMMEDIATE ACTIONS:",
*[f" [{i+1}] {a}" for i, a in enumerate(immediate)],
"",
"SHORT-TERM ACTIONS:",
*[f" [{i+1}] {a}" for i, a in enumerate(short_term)],
"",
"RESOURCES NEEDED:",
*[f" - {r}" for r in resources],
"",
f"PLANNED RESPONSE TIME: {planning_output.get('estimated_response_time', 'unknown')}",
"",
"Simulate the execution of this plan. Produce the AFTER state showing "
"meaningful improvements, list each executed action with its effect, "
"and write a plain-English outcome_summary for the crisis coordinator.",
]
return "\n".join(lines)
# ββ Public entry point ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async def run_simulation(
detection_output: DetectionOutput,
situation_report: SituationReport,
planning_output: dict[str, Any],
risk_tiering_output: RiskTieringResult,
escalation_output: dict[str, Any],
crisis_id: str | None = None,
) -> AgentResult:
"""Run the simulation agent and return an AgentResult wrapping SimulationResult.
Args:
detection_output: Validated detection agent output.
situation_report: Validated situation analysis output.
planning_output: Raw dict of the planning agent's ResponsePlan.
risk_tiering_output: Risk tier β determines dispatch_ticket presence.
escalation_output: Raw dict of the NGO escalation result (may be empty
for low-risk crises that skipped Phase 11).
crisis_id: Firestore document ID, used in the dispatch ticket.
Returns:
AgentResult whose output is SimulationResult.model_dump(mode="json").
Never raises β any failure collapses to success=False.
"""
# Build deterministic parts before calling the LLM.
before = build_before_state(situation_report)
dispatch = build_dispatch_ticket(
crisis_id=crisis_id or "DEMO",
detection_output=detection_output,
situation_report=situation_report,
risk_tiering_output=risk_tiering_output,
)
ngos_activated: int = len(escalation_output.get("ngos_alerted") or [])
prompt = _format_simulation_prompt(
detection_output=detection_output,
situation_report=situation_report,
planning_output=planning_output,
before=before,
ngos_activated=ngos_activated,
)
# Run the LLM agent.
agent_result = await run_agent(simulation_agent, prompt)
if not agent_result.success:
return agent_result
# Reconstruct structured output from the raw dict the runner stored.
try:
sim_output = SimulationAgentOutput.model_validate(agent_result.output)
except ValidationError as exc:
return AgentResult(
agent_name="simulation_agent",
success=False,
output={"error": "INVALID_SIMULATION_OUTPUT", "raw": agent_result.output},
reasoning=f"Simulation output failed schema validation: {exc}",
confidence=0.0,
)
# Assemble the final SimulationResult.
sim_result = SimulationResult(
before=before,
after=sim_output.after,
actions_executed=sim_output.actions_executed,
dispatch_ticket=dispatch,
outcome_summary=sim_output.outcome_summary,
time_to_resolution_estimate=sim_output.time_to_resolution_estimate,
)
# WhatsApp emergency dispatch β real side effect, non-fatal.
if dispatch:
units_summary = "\n".join(
f" - {u.service}: {u.units} unit(s), ETA {u.eta_minutes} min"
for u in dispatch.units_dispatched
)
try:
await dispatch_emergency_whatsapp(
ticket_id=dispatch.ticket_id,
crisis_type=dispatch.crisis_type,
location=detection_output.location_label or "",
severity=situation_report.severity,
units_summary=units_summary,
affected_population=situation_report.affected_population_estimate,
)
except Exception as exc: # noqa: BLE001
logger.warning("WhatsApp dispatch failed (non-fatal): %s", exc)
return AgentResult(
agent_name="simulation_agent",
success=True,
output=sim_result.model_dump(mode="json"),
reasoning=sim_output.reasoning,
confidence=sim_output.confidence,
)
|