Spaces:
Runtime error
Runtime error
Download src/backend/agents/simulation.py from HAK-Tech/ciro-backend: direct link, hf CLI and curl.
- Browser
- Download file 13.8 kB
-
https://huggingface.co/spaces/HAK-Tech/ciro-backend/resolve/main/src/backend/agents/simulation.py
- Command line
-
hf download hf://spaces/HAK-Tech/ciro-backend/src/backend/agents/simulation.py
-
curl -L -o simulation.py https://huggingface.co/spaces/HAK-Tech/ciro-backend/resolve/main/src/backend/agents/simulation.py
13.8 kB
| """ | |
| 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, | |
| ) | |