Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(routing): cost-aware cheap-first model cascade (Wave 5a) (#560)
Beenu Arora9161dc2b2a7f
diff --git a/services/agents/app/routing/cascade.py b/services/agents/app/routing/cascade.pynew file mode 100644index 000000000..98ffcf38f--- /dev/null+++ b/services/agents/app/routing/cascade.py@@ -0,0 +1,72 @@+"""Cost-aware model cascade (Wave 5a).++The existing ModelRouter escalates by confidence but treats "cheap" only as tier+ordinality, and the live worker never used it. This adds an explicit+**cheap-first speculative cascade**: run the cheap tier, accept its answer when+confident enough, and escalate to the strong (expensive) tier only when the+cheap answer is below the confidence floor. Most alerts are handled by the cheap+model; only the genuinely-uncertain ones pay for the strong model.++Pure orchestration over caller-supplied async tier functions + a confidence+extractor, so it is provider-agnostic and unit-testable without a live LLM.+Fail-soft: if the strong tier errors, the cheap answer is returned rather than+failing the triage.+"""++from __future__ import annotations++from collections.abc import Awaitable, Callable+from dataclasses import dataclass+from typing import Any++import structlog++logger = structlog.get_logger()++DEFAULT_CONFIDENCE_FLOOR = 0.75++TierFn = Callable[[], Awaitable[Any]]+ConfidenceFn = Callable[[Any], float]+++@dataclass(frozen=True)+class CascadeResult:+ result: Any+ tier_used: str # "cheap" | "strong"+ cheap_confidence: float+ escalated: bool+ strong_error: str | None = None+++async def cost_aware_cascade(+ *,+ cheap: TierFn,+ strong: TierFn,+ extract_confidence: ConfidenceFn,+ confidence_floor: float = DEFAULT_CONFIDENCE_FLOOR,+) -> CascadeResult:+ """Run cheap-first; escalate to strong only when the cheap answer is uncertain."""+ cheap_result = await cheap()+ cheap_conf = _clamp(extract_confidence(cheap_result))+ if cheap_conf >= confidence_floor:+ return CascadeResult(result=cheap_result, tier_used="cheap", cheap_confidence=cheap_conf, escalated=False)++ try:+ strong_result = await strong()+ except Exception as exc: # noqa: BLE001 — degrade to the cheap answer, never fail triage+ logger.warning("cascade.strong_tier_failed", error=str(exc), cheap_confidence=cheap_conf)+ return CascadeResult(+ result=cheap_result,+ tier_used="cheap",+ cheap_confidence=cheap_conf,+ escalated=True,+ strong_error=str(exc),+ )+ return CascadeResult(result=strong_result, tier_used="strong", cheap_confidence=cheap_conf, escalated=True)+++def _clamp(value: Any) -> float:+ try:+ return max(0.0, min(1.0, float(value)))+ except (TypeError, ValueError):+ return 0.0diff --git a/services/agents/tests/test_cost_cascade.py b/services/agents/tests/test_cost_cascade.pynew file mode 100644index 000000000..ef51574ee--- /dev/null+++ b/services/agents/tests/test_cost_cascade.py@@ -0,0 +1,56 @@+"""Wave 5a — cost-aware cheap-first model cascade."""++from __future__ import annotations++import pytest+from app.routing.cascade import cost_aware_cascade+++def _conf(r):+ return r["confidence"]+++async def test_confident_cheap_answer_skips_strong_tier():+ strong_called = {"n": 0}++ async def cheap():+ return {"verdict": "false_positive", "confidence": 0.9}++ async def strong():+ strong_called["n"] += 1+ return {"verdict": "true_positive", "confidence": 0.99}++ out = await cost_aware_cascade(cheap=cheap, strong=strong, extract_confidence=_conf, confidence_floor=0.75)+ assert out.tier_used == "cheap"+ assert out.escalated is False+ assert strong_called["n"] == 0 # never paid for the strong model+++async def test_uncertain_cheap_answer_escalates_to_strong():+ async def cheap():+ return {"verdict": "needs_review", "confidence": 0.4}++ async def strong():+ return {"verdict": "true_positive", "confidence": 0.95}++ out = await cost_aware_cascade(cheap=cheap, strong=strong, extract_confidence=_conf, confidence_floor=0.75)+ assert out.tier_used == "strong"+ assert out.escalated is True+ assert out.result["verdict"] == "true_positive"+++async def test_strong_tier_failure_degrades_to_cheap():+ async def cheap():+ return {"verdict": "benign", "confidence": 0.3}++ async def strong():+ raise RuntimeError("provider 500")++ out = await cost_aware_cascade(cheap=cheap, strong=strong, extract_confidence=_conf, confidence_floor=0.75)+ assert out.tier_used == "cheap"+ assert out.escalated is True+ assert out.strong_error is not None+ assert out.result["verdict"] == "benign"