File size: 7,193 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
"""
Situation Analysis Agent β€” second reasoning stage of the CIRO pipeline.

Responsibility
--------------
Given the detection verdict, the assigned risk tier, and the raw signals,
this agent determines "how bad is it and why". It estimates severity (1-5),
identifies what is impacted, and produces a plain-language explanation for
a human coordinator.

Output contract
---------------
Returns a `SituationReport` Pydantic model via the SDK's structured-output path.
"""

from __future__ import annotations

from datetime import datetime, timezone
from typing import Literal

from agents import Agent
from pydantic import BaseModel, ConfigDict, Field

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.signal import CrisisSignal
from backend.agents.detection import DetectionOutput


class SituationReport(BaseModel):
    """Structured response shape the analysis agent must return."""

    model_config = ConfigDict(extra="forbid")

    severity: int = Field(ge=1, le=5)
    severity_label: Literal["minor", "moderate", "serious", "severe", "catastrophic"]
    affected_population_estimate: str
    impacts: list[str] = Field(default_factory=list)
    confidence: float = Field(ge=0.0, le=1.0)
    explanation: str
    missing_info: list[str] = Field(default_factory=list)
    timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))


_INSTRUCTIONS = """\
You are a crisis situation analyst for Pakistani urban areas (Islamabad, Karachi, Lahore).
You receive: the type of crisis detected, the location, the assigned risk level, the initial confidence score, and all raw signals.

Your job is to:
1. Estimate severity on a scale of 1 (minor) to 5 (catastrophic).
2. Assign the corresponding severity_label ("minor", "moderate", "serious", "severe", "catastrophic").
3. Identify who and what is impacted (e.g. traffic blocked, residents trapped, power lines down). List these explicitly.
4. Estimate the affected population in plain language (e.g. "500-1000 residents", "commuters on Main Highway").
5. Explain your reasoning in plain language that a non-technical coordinator can understand. Do not use JSON or technical jargon in the explanation.
6. Re-evaluate confidence based on cross-signal analysis.
7. Flag any missing information that would change the assessment.

Severity Scale Reference:
1 - Minor: Light rain causing slow traffic, localized issue. No disruption requiring response.
2 - Moderate: Traffic congestion (even severe jams), road blockage where vehicles can be rerouted, minor infrastructure impact. No casualties, no physical blockage.
3 - Serious: Flash flood with vehicles actually stranded, road physically impassable (debris, water level), localized property damage. A traffic jam β€” however severe β€” is NOT severity 3 unless there is confirmed physical damage or casualties.
4 - Severe: Flooding with confirmed casualties risk, fire actively spreading, building collapse risk, large area impacted.
5 - Catastrophic: Building collapse with casualties, mass casualty event, multi-zone systemic failure.

Calibration rules (apply strictly):
- traffic_jam, rainfall, road_blockage: severity MUST be 1 or 2 unless confirmed casualties or physical destruction are explicitly stated. Congestion β€” even "completely jammed for 40+ minutes" β€” is at most severity 2. Speculation about a possible accident does NOT justify severity 3+.
- flood: severity 3 when vehicles are physically stranded and road is impassable; severity 4 when casualties risk is confirmed or area is large.
- fire: any active fire requiring emergency services (fire brigade called, smoke visible from far, multiple reports) is severity 4 by default. Severity 3 only for a small isolated fire that is already being managed. Fire spreads fast β€” treat active fires as severe.
- accident, building_collapse: severity 3–5 based on confirmed casualties, structural damage, and area of impact.

Be specific to the Pakistani urban context β€” reference local infrastructure, population density patterns, and common constraints.
Return the result strictly as the SituationReport schema.
"""

analysis_agent = Agent(
    name="situation_analysis_agent",
    instructions=_INSTRUCTIONS,
    model=get_gemini_model(),
    output_type=SituationReport,
)


def _format_inputs(
    signals: list[CrisisSignal],
    detection: DetectionOutput,
    risk: RiskTieringResult,
) -> str:
    """Render the inputs as a structured prompt for the agent."""
    lines: list[str] = [
        "### Detection Verdict ###",
        f"Crisis Type: {detection.crisis_type}",
        f"Location: {detection.location_label} ({detection.coordinates})",
        f"Detection Confidence: {detection.confidence:.2f}",
        f"Detection Reasoning: {detection.reasoning}",
        "",
        "### Risk Assessment ###",
        f"Risk Level: {risk.risk_level}",
        f"Risk Reasoning: {risk.reasoning}",
        "",
        f"### Raw Signals ({len(signals)}) ###",
    ]

    for idx, sig in enumerate(signals, start=1):
        lat, lon = sig.coordinates if sig.coordinates else (0.0, 0.0)
        lines.append(
            f"Signal #{idx}\n"
            f"  source: {sig.source}\n"
            f"  trust_weight: {sig.trust_weight}\n"
            f"  signal_type_hint: {sig.signal_type}\n"
            f"  location: {sig.location_label} ({lat:.4f}, {lon:.4f})\n"
            f"  severity_hint: {sig.severity_hint}\n"
            f"  observed_at: {sig.timestamp.isoformat()}\n"
            f"  text: {sig.raw_text or '(none)'}\n"
        )
    
    lines.append(
        "Synthesize this information and return a complete SituationReport. "
        "Your explanation must be clear and actionable for a coordinator."
    )
    return "\n".join(lines)


def _synthetic_no_crisis_analysis(reason: str) -> AgentResult:
    """Build an AgentResult representing 'no crisis' without calling Gemini."""
    out = SituationReport(
        severity=1,
        severity_label="minor",
        affected_population_estimate="None",
        impacts=[],
        confidence=1.0,
        explanation=reason,
        missing_info=[],
    )
    return AgentResult(
        agent_name=analysis_agent.name,
        success=True,
        output=out.model_dump(),
        reasoning=reason,
        confidence=1.0,
    )


async def run_analysis(
    signals: list[CrisisSignal],
    detection: DetectionOutput,
    risk: RiskTieringResult,
) -> AgentResult:
    """Run the situation analysis agent over the detected crisis.

    Args:
        signals: The list of `CrisisSignal` instances.
        detection: The `DetectionOutput` from Phase 5.
        risk: The `RiskTieringResult` from Phase 6.

    Returns:
        An `AgentResult` whose `output` is a `SituationReport` dict.
    """
    if not detection.crisis_detected:
        return _synthetic_no_crisis_analysis(
            "No crisis detected in the previous stage; analysis skipped."
        )

    prompt = _format_inputs(signals, detection, risk)
    return await run_agent(analysis_agent, prompt)