Auditable Multi-Agent Market Regime & Risk Committee Copilot combining strict point-in-time (PIT) quantitative ML (regimelab) with a LangGraph state machine. Every allocation memo is grounded in bi-temporal policy RAG and verified by a $0 deterministic Python Risk Auditor before release.
In institutional Asset Management and Market Risk Committees, asset allocation recommendations cannot rely on unconstrained LLM prose:
- Look-ahead bias: pulling model fits, policy amendments, or historical decisions from after
asof_dateinvalidates governance backtests. - Hallucinated metrics & sign flips: confusing VIX term-structure backwardation (
-0.072) with contango (+0.072) or inventing tail-risk VaR breaches risk limits. - Unpriced token burn: running a frontier reasoning model on routine status checks wastes latency and budget.
regime-desk solves this by keeping all quantitative inference inside regimelab (deterministic, cached, read-only tools) and wrapping three bounded LangGraph agents behind a $0 deterministic Python Risk Auditor that catches numeric hallucinations, policy limit breaches, and PIT violations before any memo leaves the desk.
flowchart TD
START((Request)) --> SUP["1. supervisor_router (Deterministic, Cost-Aware)"]
SUP -->|"New asof / portfolio"| QA["2. quant_analyst (Agent 1: regimelab Tools + Tier Routing)"]
SUP -->|"Same thread_id follow_up"| RAG["3. policy_rag (Hybrid BM25 + TF-IDF + RRF, PIT Filter)"]
QA -->|"intent == telemetry_only"| FIN["8. commit_and_finalize (Redact + Episodic Memory)"]
QA -->|"Committee / Stress Review"| RAG
RAG --> STRAT["4. portfolio_strategist (Agent 2: Structured CommitteeMemo)"]
STRAT --> AUD["5. risk_auditor (Deterministic Python Gate, 0 USD)"]
AUD -->|"Retryable fail & budget left"| STRAT
AUD -->|"Persistent fail / hard_block / budget hit"| FB["6. safe_fallback (Clamped regimelab Weights)"]
AUD -->|"PASS + research_brief"| EDIT["7. editorial_brief_agent (Agent 3: POL-EDIT-001)"]
AUD -->|"PASS + committee_memo"| FIN
FB --> FIN
EDIT --> FIN
FIN --> OUT((FinalCommitteeResponse))
CKPT[("SqliteSaver (pickle_fallback=False)")] -.-> SUP
CKPT -.-> FIN
MEM[("EpisodicMemoryStore (asof_date < current_asof)")] -.-> SUP
MEM -.-> FIN
- Clean Quantitative Separation:
regimelab>=0.5.1exposes three cached, read-only tools (get_regime_telemetry,compare_regime_models,simulate_allocation_stress) over deterministic synthetic and Parquet outage/correlation panels (plus opt-in live Yahoo Finance). - Bi-Temporal Hybrid RAG:
BM25Okapi+ L2 TF-IDF cosine + RRF (Protocol VectorEncoder), filtered toeffective_date <= asof_date < superseded_date(blockingPIT_SUPERSEDED_POLICY_LEAK), with prompt-injection sanitization and<untrusted_policy_excerpt>isolation. - Zero-Token Verification Gate (
I1–I8+ Editorial): enforces PIT causality, universe limits (POL-RISK-001/002,POL-CORR-001,POL-DATA-001,POL-MOD-001), exactCitedClaimgrounding, adaptive rounding +SIGN_CONTRADICTIONchecks, and abstention rules. - Cost-Aware Routing & Memory: routes calm regimes to
gemini-3.5-flash-liteand escalates stress, staleness, or disagreement togemini-4-hydrogen; persists thread state inSqliteSaver(follow_upreusesquant_bundle) and decisions inEpisodicMemoryStore.
# 1. Install environment with official google-genai SDK extra
uv sync --extra llm
# 2. Run multi-scenario CLI showcase (crisis + multi-turn follow-up + correlation break)
uv run --extra llm regime-desk demo
# 3. Run offline evaluation suite (Real RAG + Deterministic Auditor + Contract E2E)
uv run --extra llm regime-desk eval# Start REST API with interactive Swagger docs at http://127.0.0.1:8000/docs
uv run --extra llm uvicorn regime_desk.api:app --host 127.0.0.1 --port 8000Endpoints:
GET /health: readiness & active provider metadata (zero secret exposure).POST /v1/analyze: validated committee memo orresearch_briefexecution withthread_idsupport.GET /v1/threads/{thread_id}: inspect persistedSqliteSavercheckpoint state (200/404).
To enable live Gemini calls (via official google-genai SDK, accounting for prompt_token_count, candidates_token_count, and thoughts_token_count):
cp .env.example .env # Set REGIME_DESK_LLM_PROVIDER=gemini and GEMINI_API_KEY=...
uv run --extra llm regime-desk analyze --asof 2017-08-02 --query "Crisis SPY limit review" --live
uv run --extra llm regime-desk eval --liveOptional live Yahoo Finance market telemetry (--profile yahoo uses a 6-year trailing window ending at --asof; pytest, evals, and CI remain 100% deterministic offline):
# Optional: raise REGIME_DESK_MAX_COST_USD=0.10 to allow frontier self-repair + research_brief
uv run --extra llm regime-desk analyze --asof 2026-11-29 --profile yahoo --format research_brief --liveSample live run output (2026-11-29, Yahoo Finance + Gemini, PASS 30/30 grounded)
- Resolved session:
2026-11-27(asof_not_in_paneldisclosed cleanly) | Regime:RISK_OFF| Action:rebalance - Target weights:
SPY 0%/TLT 30%/GLD 20%/CASH 50%(citedPOL-RISK-002#c1,POL-DATA-001#c1,POL-MOD-001#c2,POL-EDIT-001#c1/#c2; repealedPOL-RISK-001excluded) - Auditor & Cost:
PASS(30/30grounded numbers,5citations) | Cost:$0.0403(13,706tokens)
Institutional Market Research Note: RISK_OFF Regime Rebalance
Under the RISK_OFF regime assessment for session date 2026-11-27, primary HMM telemetry indicates a confidence of 1.0000, risk_off_mass of 1.0000, and normalised_entropy of 0.0007. Supporting feature telemetry shows absorption_delta at 1.0307, vix_term_spread at 0.0004, defensive_correlation at 0.1775, and spy_tlt_corr at -0.2026. Cross-model comparison notes a disagreement with GMM which reports NEUTRAL_TRANSITION. The committee recommends rebalancing portfolio weights to SPY 0.00, TLT 0.30, GLD 0.20, and CASH 0.50.
Institutional Research Note Disclaimer: Regime classifications and model diagnostics are model-based research indicators rather than personalized investment advice and do not guarantee future performance.
Evaluation strictly separates real deterministic component metrics (HybridPolicyRetriever and Python risk_auditor), offline contract checks (ScriptedMockLLM, saved in evals/offline_report.json), and live Gemini runs (GeminiLLMClient). Mock responses are never presented as LLM accuracy.
| Mode | Recall@3 | MRR | Abstention Acc. | PIT Leakage |
|---|---|---|---|---|
bm25 |
100.0% | 1.0000 | 93.3% | 0.0% |
vector |
100.0% | 1.0000 | 100.0% | 0.0% |
hybrid |
100.0% | 1.0000 | 100.0% | 0.0% |
| Metric | Measured Result |
|---|---|
| Hallucination & Breach Catch Rate | 100.0% (6/6 fault injections caught) |
| False Positive Rate (Clean Rounded Memos) | 0.0% (5 canonical scenarios) |
| Self-Repair Recovery Rate | 100.0% (numeric + fake-citation repairs) |
| Safe Fallback Activation Rate | 100.0% (persistent fault + budget cap) |
Note: E2E rows below verify deterministic LangGraph state transitions, budget caps, and schema/policy invariants using
ScriptedMockLLM(not live LLM reasoning quality).
| Metric | Measured Result |
|---|---|
| Golden Cases Passed | 12/12 (100.0%) |
Tier Routing Accuracy (light vs frontier) |
100.0% |
| Simulated Cost Savings vs All-Frontier | 27.0% |
| Latency p50 / p95 (ms) | 220.0 ms / 8,874.7 ms |
Methodological Notes:
- The
100.0%Recall@3 across the 8 curated risk policy documents acts as a CI regression floor rather than a claim about large-corpus retrieval; the critical production invariants verified here are0.0%PIT leakage across the2019-01-01policy amendment cut and100.0%abstention accuracy inhybridmode (wherebm25alone false-accepted an out-of-scope leverage query at93.3%). - Latency splits cleanly between warm cached turns (
p50 = 220.0 ms) and cold walk-forward Hamilton Markov-switching regression fits insidecompare_regime_models(p95 = 8,874.7 ms), which are cached per(dataset_profile, classifier, train_end)fold.
Executed live under the default $0.05 cost budget (REGIME_DESK_MAX_COST_USD=0.05) against gemini-3.5-flash-lite (light) and gemini-4-hydrogen (frontier) across all 12 golden cases (including thoughts_token_count cost accounting; full trace in evals/live_benchmark.json):
| Metric | Measured Live Result |
|---|---|
| Cases Evaluated | 12 (11 passed cleanly, 1 routed to safe_fallback) |
Tier Routing Accuracy (light vs frontier) |
12/12 (100.0%) |
| Direct LLM Policy Compliance (Pre-Fallback) | 91.7% (11/12) |
| Effective Output Policy Compliance (Post-Fallback) | 100.0% (12/12) |
| Numeric Grounding (Approved Memos / All Checked) | 100.0% (219/219) / 98.8% (250/253) |
Avg Cost / Run (USD, incl. thoughts_tokens) |
$0.032994 |
| Cost Savings vs All-Frontier Routing | 19.1% |
| Latency p50 / p95 (ms) | 23,976.9 ms / 42,666.3 ms |
| Live Self-Repairs / Safe Fallbacks | 2 / 1 |
- Guardrails verified live:
case_09_adversarial_100_spywas intercepted into deterministicsafe_fallbackweights (CLAIM_VALUE_MISMATCH+BUDGET_EXCEEDED), andcase_03_crisis_risk_off_2017auto-repaired cleanly on retry 2. - Exact
250/253breakdown: all 3 unverified claims belong exclusively tocase_09_adversarial_100_spy(31/34checked figures flagged withCLAIM_VALUE_MISMATCHbeforeBUDGET_EXCEEDEDrouted tosafe_fallback); across the 11 approved memos, numeric grounding was219/219(100.0%). - Latency profile (
p50 ~24.0 s / p95 ~42.7 s): driven bygemini-4-hydrogenreasoningthoughts_tokenson escalatedfrontiercases (lighttier cases finished in3.6 s–7.6 s), which is an expected trade-off for an asynchronous Market Risk Committee workflow.
- 3 bounded role-specialized agents vs. 6 unconstrained conversational agents: Only
quant_analyst(tool selection),portfolio_strategist(structured synthesis), and conditionaleditorial_brief_agent(POL-EDIT-001) call LLMs. Routing, PIT policy retrieval, risk verification, and safe fallback stay deterministic Python to maximize auditability and keep latency and token cost predictable. - Read-only Python adapters over
regimelabvs. LLM code generation: Rather than executing LLM-generated backtest code in a sandbox,quant_analystinvokes typed, cached, side-effect-freeregimelabadapters with pinnedasof_dateanddataset_profile, eliminating look-ahead leakage and code-injection risk. - BM25 + TF-IDF cosine + RRF behind
Protocol VectorEncodervs. shippingtorch/sentence-transformers: Keeps container builds fast and CI dependencies lean (no multi-GB GPU/PyTorch stack) for crisp technical banking policy terms (SPY,^VIX3M,POL-RISK-002,defensive_correlation), while leaving a cleanProtocolswap-in point for neural embeddings if corpus scale grows. - Intentional Non-Goals: No custom React frontend (FastAPI Swagger + Typer CLI focus), no autonomous broker execution, and enterprise perimeter controls (OAuth2/OIDC, mTLS, distributed OpenTelemetry) are delegated to platform ingress/sidecars.
See SECURITY.md for the complete threat model covering indirect prompt injection, numeric hallucination & limit enforcement, secret redaction (SecretStr, redact_secrets(), CI gitleaks), PIT causality checks, checkpoint allowlisting (pickle_fallback=False), and non-root containerization (Dockerfile).