Spaces:
Runtime error
Runtime error
Download src/backend/agents/pipeline.py from HAK-Tech/ciro-backend: direct link, hf CLI and curl.
- Browser
- Download file 13.9 kB
-
https://huggingface.co/spaces/HAK-Tech/ciro-backend/resolve/main/src/backend/agents/pipeline.py
- Command line
-
hf download hf://spaces/HAK-Tech/ciro-backend/src/backend/agents/pipeline.py
-
curl -L -o pipeline.py https://huggingface.co/spaces/HAK-Tech/ciro-backend/resolve/main/src/backend/agents/pipeline.py
13.9 kB
| """ | |
| CIRO multi-agent pipeline β top-level orchestrator. | |
| Architecture: supervisor-style sequential pipeline. | |
| Phase 4: aggregate CrisisSignal list (NOT done here β handled by | |
| services/signal_aggregator.py before this function is called) | |
| β | |
| βΌ | |
| Phase 5: [Detection] βββΊ if crisis_detected=False β stop, return | |
| β | |
| βΌ | |
| Phase 6: [Risk Tier] βββΊ deterministic, no LLM (rule-based) | |
| β | |
| βΌ | |
| Phase 10:[Crowd Verif]βββΊ medium/high only; FCM prompts to nearby | |
| β users. Non-blocking β pipeline continues. | |
| βΌ | |
| Phase 7: [Analysis] βββΊ severity, impacts, confidence (LLM) | |
| Phase 8: [Planning] βββΊ response plan + Maps routes (LLM + tool) | |
| Phase 11:[NGO Escal] βββΊ severity threshold check; real FCM to NGO | |
| β devices if confirmed + severity β₯ 3. | |
| βΌ | |
| Phase 12: [Simulation] (placeholder) | |
| Each stage produces an `AgentResult`. The trace accumulates every result | |
| in execution order β that's what the in-app agent-trace timeline renders. | |
| Why sequential supervisor and not swarm/handoff: the CIRO flow has fixed | |
| dependency-ordered shape. You cannot plan an action before you know the | |
| risk tier; you cannot tier risk before detection has produced a verdict. | |
| A swarm pattern would add coordination overhead with no upside. | |
| Avoiding the "telephone game" problem (see multi-agent-patterns skill): | |
| downstream stages get the previous stage's `output` dict verbatim, not a | |
| paraphrase. No supervisor LLM re-summarizes intermediate results. | |
| """ | |
| from __future__ import annotations | |
| import logging | |
| from typing import Any | |
| from pydantic import ValidationError | |
| from backend.agents.analysis import SituationReport, run_analysis | |
| from backend.agents.detection import DetectionOutput, run_detection | |
| from backend.agents.planning import run_planning | |
| 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.services.risk_tiering import RISK_TIER_AGENT_NAME, run_risk_tiering | |
| logger = logging.getLogger(__name__) | |
| # ββ Phase 10: crowd verification helper ββββββββββββββββββββββββββββββββββββββ | |
| async def _run_crowd_verification( | |
| crisis_id: str, | |
| detection_output: DetectionOutput, | |
| signals: list[CrisisSignal], | |
| ) -> AgentResult: | |
| """Send FCM verification prompts to nearby users and return a trace entry. | |
| Non-blocking: the pipeline does not wait for crowd responses. Responses | |
| arrive asynchronously via POST /api/crisis/{crisis_id}/verify. A failed | |
| dispatch is logged but never crashes the pipeline (FCM is best-effort). | |
| """ | |
| from backend.services.crowd_verification import send_verification_prompts # local import avoids circular dep | |
| coords = detection_output.coordinates | |
| if coords is None and signals: | |
| coords = signals[0].coordinates | |
| if coords is None: | |
| return AgentResult( | |
| agent_name="crowd_verification", | |
| success=False, | |
| output={"error": "NO_COORDINATES"}, | |
| reasoning="Cannot dispatch verification prompts β no coordinates in detection output or signals.", | |
| confidence=0.0, | |
| ) | |
| lat, lon = coords | |
| location = detection_output.location_label or "unknown location" | |
| crisis_type = detection_output.crisis_type or "unknown" | |
| try: | |
| prompt_result = await send_verification_prompts( | |
| crisis_id=crisis_id, | |
| crisis_type=crisis_type, | |
| location_label=location, | |
| lat=lat, | |
| lon=lon, | |
| ) | |
| return AgentResult( | |
| agent_name="crowd_verification", | |
| success=True, | |
| output={**prompt_result, "status": "pending"}, | |
| reasoning=( | |
| f"Verification prompts sent to {prompt_result['users_notified']} of " | |
| f"{prompt_result['users_found']} nearby users within 1 km of {location}. " | |
| "Awaiting crowd responses before emergency dispatch." | |
| ), | |
| confidence=1.0, | |
| ) | |
| except Exception as exc: # noqa: BLE001 | |
| logger.warning("Crowd verification dispatch failed for crisis %s: %s", crisis_id, exc) | |
| return AgentResult( | |
| agent_name="crowd_verification", | |
| success=False, | |
| output={"error": "DISPATCH_FAILED", "detail": str(exc)}, | |
| reasoning=f"FCM dispatch failed: {exc}. Pipeline continues without crowd verification.", | |
| confidence=0.0, | |
| ) | |
| # ββ Phase 11: NGO escalation helper ββββββββββββββββββββββββββββββββββββββββββ | |
| async def _run_ngo_escalation( | |
| crisis_id: str | None, | |
| detection_output: DetectionOutput, | |
| situation_report: SituationReport, | |
| planning_output: dict[str, Any], | |
| ) -> AgentResult: | |
| """Evaluate NGO escalation threshold and dispatch alerts if warranted. | |
| Fetches the current verification_result from Firestore when a crisis_id | |
| is available. Without a crisis_id the escalation always returns | |
| not-escalated (no persisted document to check or update). | |
| """ | |
| from backend.services.ngo_escalation import run_escalation # local import avoids circular dep | |
| verification_result = "inconclusive" | |
| if crisis_id: | |
| from backend.core.firebase import get_async_db | |
| db = get_async_db() | |
| doc = await db.collection("crises").document(crisis_id).get() | |
| if doc.exists: | |
| verification_result = doc.to_dict().get("verification_result") or "inconclusive" | |
| plan_summary: str = planning_output.get("plan_summary") or "" | |
| escalation = await run_escalation( | |
| crisis_id=crisis_id or "no_crisis_id", | |
| crisis_type=detection_output.crisis_type or "unknown", | |
| location_label=detection_output.location_label or "unknown", | |
| severity=situation_report.severity, | |
| response_plan_summary=plan_summary, | |
| verification_result=verification_result, | |
| ) | |
| return AgentResult( | |
| agent_name="ngo_escalation", | |
| success=True, | |
| output=escalation.model_dump(), | |
| reasoning=escalation.reason, | |
| confidence=1.0, | |
| ) | |
| # ββ Pipeline entry point ββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def _serialize(final: AgentResult, trace: list[AgentResult]) -> dict[str, Any]: | |
| """Pack the pipeline result into the shape FastAPI returns to clients.""" | |
| return { | |
| "final": final.model_dump(mode="json"), | |
| "trace": [r.model_dump(mode="json") for r in trace], | |
| } | |
| async def run_pipeline(signals: list[CrisisSignal], crisis_id: str | None = None) -> dict[str, Any]: | |
| """Run the full CIRO agent pipeline against an aggregated signal list. | |
| Args: | |
| signals: The list returned by `aggregate_signals(...)`. Empty list | |
| is a valid input β the detection agent will short-circuit | |
| with `crisis_detected=False` without burning a model call. | |
| crisis_id: Firestore document ID of the persisted crisis, if any. | |
| When provided and the crisis is medium/high risk, Phase 10 | |
| crowd verification prompts are sent to nearby users. When None | |
| (e.g. the demo /api/crisis/analyze route), crowd verification | |
| is skipped β the trace still records the risk tier verdict. | |
| Returns: | |
| A dict with two keys: | |
| * `final` β the final stage's `AgentResult` (mode='json'). | |
| When the pipeline stops early on no-crisis, this is | |
| the detection result itself. | |
| * `trace` β every `AgentResult` produced along the way, in | |
| execution order. Renders as the agent-trace timeline. | |
| """ | |
| trace: list[AgentResult] = [] | |
| # ββ Stage 1: detection βββββββββββββββββββββββββββββββββββββββββββββββ | |
| detection_result = await run_detection(signals) | |
| trace.append(detection_result) | |
| # Detection failed (SDK exception, validation error, etc.) β stop. | |
| if not detection_result.success: | |
| return _serialize(detection_result, trace) | |
| # No crisis β graceful stop. No further agents run. | |
| if not detection_result.output.get("crisis_detected"): | |
| return _serialize(detection_result, trace) | |
| # ββ Stage 2: risk tiering (deterministic β no LLM) βββββββββββββββββββ | |
| # Re-validate the detection dict back into its Pydantic shape before | |
| # passing it to the classifier. Validation should always succeed here | |
| # (detection just produced it), but if structured output ever drifts | |
| # we want a clean error rather than a KeyError further downstream. | |
| try: | |
| detection_output = DetectionOutput.model_validate(detection_result.output) | |
| except ValidationError as exc: | |
| failure = AgentResult( | |
| agent_name=RISK_TIER_AGENT_NAME, | |
| success=False, | |
| output={"error": "INVALID_DETECTION_OUTPUT"}, | |
| reasoning=f"Detection output failed schema validation: {exc}", | |
| confidence=0.0, | |
| ) | |
| trace.append(failure) | |
| return _serialize(failure, trace) | |
| risk_result = run_risk_tiering(detection_output) | |
| trace.append(risk_result) | |
| # Validate risk tiering output before any downstream stage reads it. | |
| try: | |
| risk_tiering_output = RiskTieringResult.model_validate(risk_result.output) | |
| except ValidationError as exc: | |
| failure = AgentResult( | |
| agent_name="situation_analysis_agent", | |
| success=False, | |
| output={"error": "INVALID_RISK_TIERING_OUTPUT"}, | |
| reasoning=f"Risk tiering output failed schema validation: {exc}", | |
| confidence=0.0, | |
| ) | |
| trace.append(failure) | |
| return _serialize(failure, trace) | |
| # ββ Stage 2.5: crowd verification (Phase 10) βββββββββββββββββββββββββ | |
| # Runs only for medium/high-risk crises AND only when the caller has | |
| # persisted a crisis document (crisis_id provided). Non-blocking: the | |
| # pipeline does not wait for crowd responses β they arrive async via | |
| # POST /api/crisis/{crisis_id}/verify. | |
| if risk_tiering_output.requires_crowd_verification and crisis_id: | |
| cv_result = await _run_crowd_verification( | |
| crisis_id=crisis_id, | |
| detection_output=detection_output, | |
| signals=signals, | |
| ) | |
| trace.append(cv_result) | |
| # ββ Stage 3: situation analysis (Phase 7) ββββββββββββββββββββββββββββ | |
| analysis_result = await run_analysis(signals, detection_output, risk_tiering_output) | |
| trace.append(analysis_result) | |
| if not analysis_result.success: | |
| return _serialize(analysis_result, trace) | |
| # ββ Stage 4: action planning (Phase 8) βββββββββββββββββββββββββββββββ | |
| try: | |
| situation_report = SituationReport.model_validate(analysis_result.output) | |
| except ValidationError as exc: | |
| failure = AgentResult( | |
| agent_name="action_planning_agent", | |
| success=False, | |
| output={"error": "INVALID_SITUATION_REPORT"}, | |
| reasoning=f"Situation report failed schema validation: {exc}", | |
| confidence=0.0, | |
| ) | |
| trace.append(failure) | |
| return _serialize(failure, trace) | |
| planning_result = await run_planning(detection_output, risk_tiering_output, situation_report) | |
| trace.append(planning_result) | |
| if not planning_result.success: | |
| return _serialize(planning_result, trace) | |
| # ββ Stage 5: NGO escalation (Phase 11) βββββββββββββββββββββββββββββββ | |
| # Runs for medium/high risk crises only. Checks Firestore for the | |
| # current verification_result β if "confirmed" and severity β₯ 3, fires | |
| # real FCM to registered NGO devices. Always adds a trace entry. | |
| escalation_result: AgentResult | None = None | |
| if risk_tiering_output.requires_crowd_verification: | |
| escalation_result = await _run_ngo_escalation( | |
| crisis_id=crisis_id, | |
| detection_output=detection_output, | |
| situation_report=situation_report, | |
| planning_output=planning_result.output, | |
| ) | |
| trace.append(escalation_result) | |
| # ββ Stage 6: simulation (Phase 12) βββββββββββββββββββββββββββββββββββ | |
| # Terminal stage β simulates plan execution, builds before/after state, | |
| # assembles the dispatch ticket, and fires WhatsApp emergency dispatch. | |
| from backend.agents.simulation import run_simulation # local import avoids circular dep | |
| simulation_result = await run_simulation( | |
| detection_output=detection_output, | |
| situation_report=situation_report, | |
| planning_output=planning_result.output, | |
| risk_tiering_output=risk_tiering_output, | |
| escalation_output=escalation_result.output if escalation_result else {}, | |
| crisis_id=crisis_id, | |
| ) | |
| trace.append(simulation_result) | |
| return _serialize(simulation_result, trace) | |