File size: 8,732 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
"""
Crisis Detection Agent β€” first reasoning stage of the CIRO pipeline.

Responsibility
--------------
Given a list of `CrisisSignal` instances aggregated by Phase 4, decide:

    1.  Is a crisis occurring at all?
    2.  If yes, which type (from a closed taxonomy)?
    3.  Where exactly?  (location label + coordinates, copied β€” never
        invented β€” from the signals).
    4.  How confident is the agent?

This agent is intentionally narrow. It does *not* estimate severity (Phase 7),
classify risk tier (Phase 6), or plan a response (Phase 8). Keeping the
detection step single-purpose is a deliberate context-isolation choice
(see the multi-agent-patterns skill) β€” the prompt and tool surface stay
small, so the model stays accurate.

Output contract
---------------
The agent returns a `DetectionOutput` Pydantic model via the SDK's
structured-output path (`output_type=DetectionOutput`). The base runner
wraps it into an `AgentResult` with `output = DetectionOutput.model_dump()`,
which is what downstream pipeline stages read.
"""

from __future__ import annotations

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.signal import CrisisSignal


# Closed taxonomy. Keeping this as a Literal is what lets the SDK reject
# free-form crisis types ("Flooding", "WaterAccumulation") at schema level.
CrisisType = Literal[
    "flood",
    "fire",
    "accident",
    "traffic_jam",
    "rainfall",
    "heatwave",
    "infrastructure",
]


class DetectionOutput(BaseModel):
    """Structured response shape the detection agent must return.

    Field semantics
    ---------------
    crisis_detected
        Binary verdict. If False, every other field describing a crisis
        must be None (the agent is told this explicitly in the prompt).

    crisis_type
        Closed-taxonomy label. None iff crisis_detected is False.

    location_label / coordinates
        Copied verbatim from the most-credible signal that named a
        location. NEVER invented. If no signal contains a recognizable
        location, both are None even when a crisis is detected.

    confidence
        Self-reported, in [0, 1]. Higher weight should track higher
        signal trust_weight and stronger inter-signal agreement.

    reasoning
        One short paragraph in plain language. Rendered directly in
        the agent-trace UI for end users, so it must read like an
        explanation, not a JSON dump.

    supporting_signals
        Short references to the specific signals that drove the verdict
        β€” e.g. `'social_media: "G-10 mein pani bhar gaya hai..."'`.
        Used for the trace UI and for downstream debugging.
    """

    # Forbid extra fields so the SDK enforces strict structured output.
    model_config = ConfigDict(extra="forbid")

    crisis_detected: bool
    crisis_type: CrisisType | None = None
    location_label: str | None = None
    coordinates: tuple[float, float] | None = None
    confidence: float = Field(ge=0.0, le=1.0)
    reasoning: str
    supporting_signals: list[str] = Field(default_factory=list)


# ── Agent definition ──────────────────────────────────────────────────────

_INSTRUCTIONS = """\
You are CIRO's crisis detection agent for Pakistani urban areas
(Islamabad, Karachi, Lahore). You receive a structured list of signals
aggregated from weather APIs, simulated social-media posts, and
CNIC-verified in-app reports. Each signal is tagged with its `source`,
its `trust_weight` in [0, 1], a `signal_type`, an optional location, an
optional severity hint, and the raw text (which may be Urdu, English,
or mixed).

Your job is to decide:

  1. Whether a crisis is currently occurring.
  2. If yes, which type β€” strictly one of:
     flood, fire, accident, traffic_jam, rainfall, heatwave, infrastructure.
  3. Where exactly β€” copy the most precise `location_label` and
     `coordinates` from the signals. Never invent a location.
  4. How confident you are, in [0, 1].

Rules:
  - Signals with higher `trust_weight` are stronger evidence. A single
    app_report (trust=1.0) confirming a flood outweighs three
    social_media posts (trust=0.5) that disagree. Use the provided
    weights as data β€” do not assume fixed weights of your own.
  - Handle Urdu, English, and mixed-language input natively. Do not
    translate in your reasoning β€” just understand and classify.
  - If the signals do not consistently support a crisis (e.g. benign
    weather + no eyewitness reports), set `crisis_detected=False` and
    leave `crisis_type`, `location_label`, and `coordinates` as null.
    Confidence in that case is your confidence in the *no-crisis*
    verdict.
  - NEVER invent a location. If no signal contains a recognizable
    location, set `location_label=null` and `coordinates=null`, even
    when a crisis is detected.
  - `supporting_signals` must reference the actual signals you used,
    each as a short string like
      'social_media (trust=0.5): "G-10 mein pani bhar gaya hai..."'
  - `reasoning` must be one short paragraph in plain language. It is
    shown directly to end-users in the live agent-trace UI, so write
    it like an explanation, not a JSON dump.

Return the result strictly as the `DetectionOutput` schema. Do not add
prose outside the schema.
"""


detection_agent = Agent(
    name="crisis_detection_agent",
    instructions=_INSTRUCTIONS,
    model=get_gemini_model(),
    output_type=DetectionOutput,
)


# ── Helpers ───────────────────────────────────────────────────────────────


def _format_signals(signals: list[CrisisSignal]) -> str:
    """Render the signal list as a structured prompt for the agent.

    The format is deliberately verbose-but-uniform: each signal occupies
    a fixed-key block. The agent reasons over this directly; no
    serialization tricks needed at the model end.
    """
    lines: list[str] = [f"You have received {len(signals)} signal(s):\n"]
    for idx, sig in enumerate(signals, start=1):
        lat, lon = sig.coordinates
        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(
        "Reason across these signals and return a DetectionOutput. "
        "Remember: do not invent a location, and use trust_weight as "
        "the strength of each piece of evidence."
    )
    return "\n".join(lines)


def _synthetic_no_crisis(reason: str) -> AgentResult:
    """Build an AgentResult representing 'no crisis' without calling Gemini.

    Used when there are zero signals to reason about β€” saving a model
    round-trip while keeping the same contract every other stage expects.
    """
    out = DetectionOutput(
        crisis_detected=False,
        confidence=1.0,
        reasoning=reason,
        supporting_signals=[],
    )
    return AgentResult(
        agent_name=detection_agent.name,
        success=True,
        output=out.model_dump(),
        reasoning=reason,
        confidence=1.0,
    )


# ── Public entry point ────────────────────────────────────────────────────


async def run_detection(signals: list[CrisisSignal]) -> AgentResult:
    """Run the detection agent over an aggregated signal list.

    Args:
        signals: The list returned by `aggregate_signals(...)` β€” or any
            list of `CrisisSignal` instances, including a hand-built
            list for tests or for raw app-report submissions.

    Returns:
        An `AgentResult` whose `output` is a `DetectionOutput` dict.
        Never raises β€” any underlying SDK failure collapses to
        `success=False` via the base runner.
    """
    if not signals:
        return _synthetic_no_crisis(
            "No signals were provided to the detection agent β€” "
            "treating as no crisis."
        )

    prompt = _format_signals(signals)
    return await run_agent(detection_agent, prompt)