File size: 6,196 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
"""
Trace service — Phase 13.

Assembles the agent reasoning trace from pipeline AgentResult outputs and
persists it to Firestore agent_logs. Provides the read path for
GET /api/crisis/{crisis_id}/trace.
"""

from __future__ import annotations

from datetime import datetime, timezone

from backend.core.firebase import get_async_db
from backend.models.agent_result import AgentResult
from backend.models.trace import AgentTrace, AgentTraceStep, FinalOutcome


# Maps pipeline agent_name → human-readable action label.
_ACTION_LABELS: dict[str, str] = {
    "crisis_detection_agent": "Crisis Detected",
    "risk_tier_classifier": "Risk Classified",
    "crowd_verification": "Verification Sent",
    "situation_analysis_agent": "Situation Assessed",
    "action_planning_agent": "Response Plan Generated",
    "ngo_escalation": "NGOs Alerted",
    "simulation_agent": "Simulation Complete",
}


def _action_label(result: AgentResult) -> str:
    name = result.agent_name
    if name == "crisis_detection_agent":
        return "Crisis Detected" if result.output.get("crisis_detected") else "No Crisis Detected"
    if name == "ngo_escalation":
        ngos = result.output.get("ngos_alerted") or []
        return "NGOs Alerted" if ngos else "No Escalation"
    return _ACTION_LABELS.get(name, name.replace("_", " ").title())


def _output_summary(result: AgentResult) -> str:
    """Derive a one-line plain-English summary from the step's output dict."""
    out = result.output
    name = result.agent_name

    if name == "crisis_detection_agent":
        if out.get("crisis_detected"):
            ct = out.get("crisis_type", "unknown")
            loc = out.get("location_label", "unknown location")
            return f"Detected {ct} at {loc} (confidence: {result.confidence:.0%})."
        return "No crisis found in incoming signals."

    if name == "risk_tier_classifier":
        level = out.get("risk_level", "unknown")
        requires_cv = out.get("requires_crowd_verification", False)
        suffix = "Crowd verification required." if requires_cv else "Auto-response triggered."
        return f"Risk level: {level}. {suffix}"

    if name == "crowd_verification":
        if result.success:
            notified = out.get("users_notified", 0)
            return f"Prompts sent to {notified} nearby users. Awaiting crowd responses."
        return "Crowd verification dispatch failed; pipeline continued."

    if name == "situation_analysis_agent":
        severity = out.get("severity", "?")
        label = out.get("severity_label", "")
        population = out.get("affected_population_estimate", "unknown")
        return f"Severity {severity}/5 ({label}). Affected population: {population}."

    if name == "action_planning_agent":
        immediate = len(out.get("immediate_actions") or [])
        short_term = len(out.get("short_term_actions") or [])
        eta = out.get("estimated_response_time", "unknown")
        return f"Plan: {immediate} immediate, {short_term} short-term actions. ETA: {eta}."

    if name == "ngo_escalation":
        ngos = out.get("ngos_alerted") or []
        if ngos:
            names_str = ", ".join(str(n) for n in ngos[:3])
            return f"Escalated to {len(ngos)} NGO(s): {names_str}."
        return out.get("reason") or "No escalation threshold met."

    if name == "simulation_agent":
        after = out.get("after") or {}
        congestion = after.get("congestion_level", "unknown")
        alerted = after.get("citizens_alerted", 0)
        return f"Response executed. Congestion: '{congestion}', {alerted} citizens alerted."

    return (result.reasoning or "Step completed.")[:120]


def _final_outcome(results: list[AgentResult]) -> FinalOutcome:
    """Determine the overall pipeline outcome from the accumulated trace steps."""
    names = {r.agent_name for r in results}

    for r in results:
        if r.agent_name == "crisis_detection_agent" and not r.output.get("crisis_detected"):
            return "inconclusive"

    if "simulation_agent" not in names:
        return "inconclusive"

    for r in results:
        if r.agent_name == "risk_tier_classifier":
            if not r.output.get("requires_crowd_verification"):
                return "low_risk_auto"

    return "responded"


def assemble_trace(crisis_id: str, results: list[AgentResult]) -> AgentTrace:
    """Convert pipeline AgentResult list into a structured AgentTrace.

    Step numbers are sequential in execution order. Not every pipeline step
    runs for every scenario (e.g. crowd verification is medium/high only),
    so step numbers reflect what actually ran.
    """
    steps: list[AgentTraceStep] = []
    for i, r in enumerate(results, start=1):
        steps.append(
            AgentTraceStep(
                step_number=i,
                agent_name=r.agent_name,
                action=_action_label(r),
                reasoning=r.reasoning,
                confidence=r.confidence,
                output_summary=_output_summary(r),
                timestamp=r.timestamp,
            )
        )

    duration = 0.0
    if len(steps) >= 2:
        duration = max(
            (steps[-1].timestamp - steps[0].timestamp).total_seconds(),
            0.0,
        )

    return AgentTrace(
        crisis_id=crisis_id,
        steps=steps,
        total_duration_seconds=duration,
        final_outcome=_final_outcome(results),
        created_at=datetime.now(timezone.utc),
    )


async def save_trace(trace: AgentTrace) -> None:
    """Persist the assembled trace to Firestore agent_logs/{crisis_id}.

    Keyed by crisis_id so the mobile app fetches it with a single document
    read. Overwrites any existing trace for this crisis_id (idempotent).
    """
    db = get_async_db()
    await db.collection("agent_logs").document(trace.crisis_id).set(
        trace.model_dump(mode="json")
    )


async def get_trace(crisis_id: str) -> AgentTrace | None:
    """Read a trace from Firestore. Returns None if no trace exists."""
    db = get_async_db()
    doc = await db.collection("agent_logs").document(crisis_id).get()
    if not doc.exists:
        return None
    return AgentTrace.model_validate(doc.to_dict())