HAK-16's picture
Initial deploy
1ffd0a4 verified
Raw History Blame Contribute Delete
6.2 kB
"""
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())