""" 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)