Spaces:
Runtime error
Runtime error
Download src/backend/services/risk_tiering.py from HAK-Tech/ciro-backend: direct link, hf CLI and curl.
- Browser
- Download file 6.71 kB
-
https://huggingface.co/spaces/HAK-Tech/ciro-backend/resolve/main/src/backend/services/risk_tiering.py
- Command line
-
hf download hf://spaces/HAK-Tech/ciro-backend/src/backend/services/risk_tiering.py
-
curl -L -o risk_tiering.py https://huggingface.co/spaces/HAK-Tech/ciro-backend/resolve/main/src/backend/services/risk_tiering.py
6.71 kB
| """ | |
| Deterministic crisis risk-tier classifier. | |
| This is the one stage of the CIRO pipeline that is *not* an LLM call. | |
| The phase doc is explicit: | |
| "Risk tiering is deterministic rule-based logic β fast, predictable, | |
| testable." | |
| Why deterministic here matters | |
| ------------------------------ | |
| The risk tier decides whether emergency services get involved at all, | |
| and whether to broadcast push notifications to nearby app users. We do | |
| not want that decision varying request-to-request based on model | |
| sampling. A rule-based classifier is faster, cheaper, and auditable. | |
| Classification rules (single source of truth) | |
| --------------------------------------------- | |
| crisis_type in LOW_RISK_TYPES β "low" (regardless of confidence) | |
| crisis_type in MEDIUM_HIGH_RISK_TYPES: | |
| confidence >= CONFIDENCE_THRESHOLD β "high" | |
| confidence < CONFIDENCE_THRESHOLD β "medium" (confidence cap) | |
| crisis_type otherwise / None β "medium" (fail-safe default) | |
| The confidence cap acts as a *ceiling* on high-risk types, not a floor | |
| on everything. A low-confidence rainfall stays low β raising it to | |
| medium just because confidence is low would be perverse. The cap exists | |
| specifically to make sure we don't skip crowd verification for a | |
| high-risk type when the agent is unsure. | |
| """ | |
| from __future__ import annotations | |
| from backend.agents.detection import DetectionOutput | |
| from backend.core.constants import ( | |
| CONFIDENCE_THRESHOLD, | |
| LOW_RISK_TYPES, | |
| MEDIUM_HIGH_RISK_TYPES, | |
| ) | |
| from backend.models.agent_result import AgentResult | |
| from backend.models.risk import RiskTieringResult | |
| # Actions safe to fire automatically for a low-risk crisis. The simulation | |
| # agent (Phase 12) is what actually executes them; tiering only declares | |
| # intent. Kept here so the list lives next to the rule that produces it. | |
| _LOW_RISK_AUTO_ACTIONS: list[str] = ["reroute_traffic", "send_area_alert"] | |
| RISK_TIER_AGENT_NAME = "risk_tier_classifier" | |
| # ββ Pure classifier βββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def classify_risk(detection: DetectionOutput) -> RiskTieringResult: | |
| """Apply the risk-tiering rules to a detection result. | |
| Args: | |
| detection: The structured output of Phase 5's detection agent. | |
| This function does not re-validate that a crisis was detected β | |
| callers (the pipeline) decide whether to even ask. If the | |
| detection has `crisis_detected=False`, we still produce a | |
| sensible "low" result so the function stays total. | |
| Returns: | |
| A `RiskTieringResult` describing the response path. Never raises. | |
| """ | |
| # Defensive: no crisis β no need to escalate anything. The pipeline | |
| # short-circuits before reaching here, but if a caller does invoke | |
| # us with crisis_detected=False, return a coherent low-risk result | |
| # rather than letting the caller see garbage. | |
| if not detection.crisis_detected: | |
| return RiskTieringResult( | |
| risk_level="low", | |
| requires_crowd_verification=False, | |
| requires_emergency_services=False, | |
| auto_response_actions=[], | |
| reasoning="No crisis detected; nothing to escalate.", | |
| ) | |
| crisis_type = detection.crisis_type | |
| confidence = detection.confidence | |
| # ββ Low-risk path: automated response, no humans involved. βββββββββββ | |
| if crisis_type in LOW_RISK_TYPES: | |
| return RiskTieringResult( | |
| risk_level="low", | |
| requires_crowd_verification=False, | |
| requires_emergency_services=False, | |
| auto_response_actions=list(_LOW_RISK_AUTO_ACTIONS), | |
| reasoning=( | |
| f"Crisis type {crisis_type!r} is low-risk. " | |
| "Automated response initiated; no crowd verification or " | |
| "emergency dispatch required." | |
| ), | |
| ) | |
| # ββ Medium/high path with confidence cap. ββββββββββββββββββββββββββββ | |
| if crisis_type in MEDIUM_HIGH_RISK_TYPES: | |
| if confidence < CONFIDENCE_THRESHOLD: | |
| return RiskTieringResult( | |
| risk_level="medium", | |
| requires_crowd_verification=True, | |
| requires_emergency_services=True, | |
| auto_response_actions=[], | |
| reasoning=( | |
| f"Crisis type {crisis_type!r} is high-risk but " | |
| f"detection confidence is {confidence:.2f} " | |
| f"(< {CONFIDENCE_THRESHOLD}); capping at medium. " | |
| "Crowd verification required before emergency dispatch." | |
| ), | |
| ) | |
| return RiskTieringResult( | |
| risk_level="high", | |
| requires_crowd_verification=True, | |
| requires_emergency_services=True, | |
| auto_response_actions=[], | |
| reasoning=( | |
| f"Crisis type {crisis_type!r} is high-risk with " | |
| f"confidence {confidence:.2f}. Crowd verification " | |
| "required before emergency dispatch." | |
| ), | |
| ) | |
| # ββ Unknown crisis type β fail-safe default. βββββββββββββββββββββββββ | |
| # We never silently skip verification for an unrecognized label. | |
| return RiskTieringResult( | |
| risk_level="medium", | |
| requires_crowd_verification=True, | |
| requires_emergency_services=True, | |
| auto_response_actions=[], | |
| reasoning=( | |
| f"Crisis type {crisis_type!r} is not in the known taxonomy; " | |
| "defaulting to medium risk so crowd verification is performed." | |
| ), | |
| ) | |
| # ββ Pipeline-facing wrapper (synthesizes an AgentResult) βββββββββββββββββ | |
| def run_risk_tiering(detection: DetectionOutput) -> AgentResult: | |
| """Run the classifier and wrap the result as an `AgentResult`. | |
| The trace UI and downstream pipeline expect every stage to produce an | |
| `AgentResult`. Since this stage is deterministic, we synthesize one: | |
| `success=True`, `confidence=1.0`, the reasoning copied from the | |
| classifier's verdict. | |
| This wrapper is the only thing the pipeline imports from this module β | |
| `classify_risk` itself stays pure so it can be unit-tested without | |
| touching the AgentResult shape. | |
| """ | |
| tiering = classify_risk(detection) | |
| return AgentResult( | |
| agent_name=RISK_TIER_AGENT_NAME, | |
| success=True, | |
| output=tiering.model_dump(), | |
| reasoning=tiering.reasoning, | |
| confidence=1.0, | |
| ) | |