Spaces:
Sleeping
feat(llm+docs): KI-177 + KI-179 + KI-183 + ADR-040 docs cascade
Browse filesTHREE-TIER LLM CHAIN — Google Gemini PRIMARY, NIM Tier 1, OR Tier 2.
Live audit (KI-178) of OpenRouter's free-tier catalog killed my earlier
recommendation: gemini-2.0-flash isn't in OR's catalog, llama-3.3-70b-
:free and hermes-3-405b:free don't expose response_format. So OR's
free-with-JSON pool is only nemotron-3-super-120b / qwen3-next-80b /
gemma-4-31b. User obtained a Google AI Studio key, set up billing
($0 historical spend, $10 cap, free 1500/day quota active), confirmed
working live on gemini-2.5-flash + gemini-2.5-flash-lite.
NEW MODEL TIERS:
Brain Fast (sales_brain):
Tier 0 Google gemini-2.5-flash-lite (KI-183 — 2.0-flash retired)
Tier 1 NIM qwen3-next-80b → mistral-large-3 → llama-4-maverick
Tier 2 OR nemotron-3-super-120b:free → qwen3-next-80b:free → gemma-4-31b:free
Last NIM nemotron-super-49b (only when all else dies)
Brain Main (orchestrator):
Tier 0 Google gemini-2.5-flash
Tier 1+ same NIM/OR cascade
Judge (faithfulness):
NIM-only at top mistral-large-3 → llama-4-maverick → OR qwen-free → nemotron-49b
(cross-family from Gemini brain preserves grading invariant)
CODE (KI-179 + KI-177 + KI-183):
+ backend/providers/google_gemini_llm.py (NEW) — direct REST,
native responseMimeType=application/json, factory get_gemini_llm
+ backend/providers/tiered_brain_llm.py (NEW) — wrapper
walking Gemini → NIM → OR for orchestrator brain path
M backend/sales_brain.py — 3-tier cascade; brain_used now
sales_brain::{gemini,nim,or}:<model>; KI-169 think-strip retry stays
in-tier; KI-183 model defaults updated for retired gemini-2.0-flash
M backend/orchestrator.py — pick_brain returns get_tiered_brain_llm(role)
M backend/providers/openrouter_llm.py — supports models=[...] param
M frontend/public/admin/llm-control.html — KI-177 clearChildren null guard
M tools/set_hf_secrets.py — GOOGLE_API_KEY in SECRETS_TO_SET
DOCS CASCADE (KI-180 + KI-182):
+ 70-docs/60-decisions/ADR-040-google-gemini-primary.md (NEW)
M ARCHITECTURE.md, CLAUDE.md, README.md
M 70-docs/00-overview/{roadmap,problem-statement}.md
M 70-docs/10-architecture/{system-overview,stack-rationale,safety-architecture}.md
M 70-docs/30-engineering/{discovery-script,needs-analysis-flow}.md
M 70-docs/40-evaluation/{eval-methodology,known-issues,quality-sprint-2026-05-14}.md
M 70-docs/60-decisions/ADR-{014,016,019,026,030,031,032,038}.md
→ all marked Superseded by ADR-040 (2026-05-15)
M 80-audit/ENTERPRISE_AUDIT.md
M backend/README.md, frontend/README.md, rag/README.md, eval/README.md
M kb/AUDIT_TRAIL.md, tools/README.md
VERIFICATION:
py_compile all .py — clean
npx tsc --noEmit — clean
Live Gemini probe: HTTP 200 gemini-2.5-flash 943-1205ms; gemini-2.5-
flash-lite 739-1161ms; gemini-2.0-flash HTTP 404 (retired)
Tiered chain mock tests: gemini-up / gemini-down / gemini-nim-down /
all-down — all correct tag emission
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Files changed (36)
- 70-docs/00-overview/problem-statement.md+2-2
- 70-docs/00-overview/roadmap.md+11-2
- 70-docs/10-architecture/safety-architecture.md+6-6
- 70-docs/10-architecture/stack-rationale.md+9-6
- 70-docs/10-architecture/system-overview.md+160-99
- 70-docs/30-engineering/discovery-script.md+9-5
- 70-docs/30-engineering/needs-analysis-flow.md+76-59
- 70-docs/40-evaluation/eval-methodology.md+5-5
- 70-docs/40-evaluation/known-issues.md+52
- 70-docs/40-evaluation/quality-sprint-2026-05-14.md+42
- 70-docs/60-decisions/ADR-014-groq-llama-grader.md+5-1
- 70-docs/60-decisions/ADR-016-hybrid-brain-router.md+5-1
- 70-docs/60-decisions/ADR-019-nim-single-provider-consolidation.md+1-1
- 70-docs/60-decisions/ADR-026-provider-load-balancing.md+3-2
- 70-docs/60-decisions/ADR-030-llm-driven-fact-find.md+8-3
- 70-docs/60-decisions/ADR-031-sticky-primary-election.md+5-1
- 70-docs/60-decisions/ADR-032-llm-chain-architecture.md+5-5
- 70-docs/60-decisions/ADR-038-nim-only-chains.md+3-1
- 70-docs/60-decisions/ADR-040-google-gemini-primary.mdAdded+90
- 80-audit/ENTERPRISE_AUDIT.md+22-4
- ARCHITECTURE.md+95-50
- CLAUDE.md+17-12
- README.md+57-36
- backend/README.md+14-4
- backend/orchestrator.py+12-8
- backend/providers/google_gemini_llm.pyAdded+233
- backend/providers/openrouter_llm.py+63-1
- backend/providers/tiered_brain_llm.pyAdded+229
- backend/sales_brain.py+154-30
- eval/README.md+4-3
- frontend/README.md+3
- frontend/public/admin/llm-control.html+1
- kb/AUDIT_TRAIL.md+34-15
- rag/README.md+1-1
- tools/README.md+3-3
- tools/set_hf_secrets.py+1
218 unmodified lines219220221222223224225226227218 unmodified lines### 8.4 Technical envelope- v1 UI: Streamlit. Business logic is decoupled into a separate `app/` Python module so a future FastAPI + React v2 swaps the UI layer only.- v1 corpus: 15–20 health policies across 5 leading Indian insurers (Star Health, HDFC ERGO, Niva Bupa, Care Health, ICICI Lombard — exact list pending availability check).- v1 deployment: local development + a single-instance deploy (Streamlit Community Cloud or equivalent) for the interviewer to demo.---218 unmodified lines219220221222223224225226227218 unmodified lines### 8.4 Technical envelope- v1 UI: Next.js 14 (App Router) + Tailwind v4 + shadcn/ui, calling a FastAPI backend. (The original draft scoped Streamlit; the migration to Next.js + FastAPI is captured in [ADR-005](../60-decisions/ADR-005-nextjs-fastapi-frontend.md).)- v1 corpus: 15–20 health policies across 5 leading Indian insurers (Star Health, HDFC ERGO, Niva Bupa, Care Health, ICICI Lombard — exact list pending availability check).- v1 deployment: local development + a single-instance deploy on Hugging Face Spaces (Docker) for the interviewer to demo.---
9 unmodified lines1011121314151617181920211 unmodified line232425262728299 unmodified linesv1 is a **vertical slice**: 10 insurers × Health × ~80 policies × voice-first advisor. The architecture is built so v2 is a **data/config change, not a rebuild**. This document maps the path.## 1. What v1 ships**Working product:**- Voice-first chat advisor over a curated corpus of Indian health insurance policies (~76 PDFs from 10 insurers, ingested into Chroma + DuckDB)- Multi-language: English + Hindi/Hinglish via Sarvam Saarika STT + Sarvam Bulbul TTS- Brain router (D-019, KI-080): BRAIN_CHAIN with probe-elected primary across NIM Qwen 80B / Groq Llama-3.3 / OpenRouter candidates (heavy intents) + FAST_BRAIN_CHAIN with probe-elected primary across Nemotron 30B / Qwen 80B / Groq (voice + fact-find), Mistral Large 3 675B judge primary. Sarvam-M scoped to Indic translation + voice only.- 4-gate hallucination defense + auditable refusal log- 62-field structured extraction per policy- Clean Next.js + Tailwind frontend1 unmodified line- 8 design / decision documents totaling ~30 pages**Eval signal:**- Gold Q&A harness (~300 pairs targeted) + automated grader (the judge chain (Mistral Large 3 675B primary) — different family from DeepSeek brain)- `eval/results.md` versioned table per run- Live audit log `logs/hallucinations.jsonl` for every blocked claim9 unmodified lines1011121314151617181920212223242526272829301 unmodified line323334353637389 unmodified linesv1 is a **vertical slice**: 10 insurers × Health × ~80 policies × voice-first advisor. The architecture is built so v2 is a **data/config change, not a rebuild**. This document maps the path.## 0.1 Recently shipped (2026-05-15)- **KI-167 / [ADR-039](../60-decisions/ADR-039-llm-driven-sales-brain.md)** — Ripped out `backend/fact_find_brain.py` + canonical_fallback + the `<FF>` trailer convention. Replaced with `backend/sales_brain.py` — one LLM call per turn using native provider JSON mode. No scripted prompts, multi-fact capture per turn, ~500 LOC deleted.- **KI-168** — Hybrid voice capture: Web Speech API streams interim transcripts for live UX feel while MediaRecorder runs in parallel; Sarvam STT is the authoritative transcript posted on browser silence-detect.- **KI-171** — Skip faithfulness judge on `fact_find` + `recommendation` intents (the judge has no retrieved context to grade against on those turns).- **KI-173 / KI-174** — Voice heartbeat + `visibilitychange` / `focus` revival hooks keep the mic alive across tab and app switches.- **KI-175 / KI-176** — NIM chain reorder (Nemotron 49B demoted to last resort), OpenRouter re-added as cross-provider diversity via `models: [...]` server-side fallback.- **KI-178 / KI-179 / [ADR-040](../60-decisions/ADR-040-google-gemini-primary.md)** — OpenRouter free-tier `response_format` audit; added Google AI Studio (Gemini 2.0 / 2.5 Flash, 1500 req/day free) as Tier 0 primary on Brain Fast + Brain Main.## 1. What v1 ships**Working product:**- Voice-first chat advisor over a curated corpus of Indian health insurance policies (~76 PDFs from 10 insurers, ingested into Chroma + DuckDB)- Multi-language: English + Hindi/Hinglish via Sarvam Saarika STT + Sarvam Bulbul TTS- 3-tier brain chain (ADR-040, KI-179): Brain Fast (`backend/sales_brain.py`, fact-find) leads with **Gemini 2.0 Flash** (Google AI Studio, 1500 req/day free, native JSON mode) → NIM Qwen 80B / Mistral Large 3 675B / Llama-4 Maverick → OpenRouter `:free` (Nemotron-3-Super 120B, Qwen 80B) → NIM Nemotron 49B last resort. Brain Main (synthesis / comparison / recommendation) leads with **Gemini 2.5 Flash** → NIM Mistral 675B / Maverick / Qwen 80B → OR Nemotron-3-Super → NIM Nemotron 49B. Judge primary stays on **NIM Mistral Large 3 675B** (different family from the Gemini brain — preserves the cross-family invariant). Sticky-primary election (KI-080) per chain. Sarvam scoped to Indic translation + voice only.- 4-gate hallucination defense + auditable refusal log- 62-field structured extraction per policy- Clean Next.js + Tailwind frontend1 unmodified line- 8 design / decision documents totaling ~30 pages**Eval signal:**- Gold Q&A harness (~300 pairs targeted) + automated grader (the JUDGE_CHAIN with NIM Mistral Large 3 675B primary — different family from the Gemini brain so grading stays non-circular)- `eval/results.md` versioned table per run- Live audit log `logs/hallucinations.jsonl` for every blocked claim
18 unmodified lines1920212223242524 unmodified lines5051525354555638 unmodified lines959697989910010110210367 unmodified lines17117217317417517617712 unmodified lines19019119219319418 unmodified lines**Description:** Bot claims a policy covers something it doesn't, or quotes a wrong waiting period / sub-limit.**Detection:**- Run-time: Faithfulness Gate 4 (LLM-judge the judge chain (Mistral Large 3 675B primary) — different family from the brain (Qwen 80B primary); see D-019).- Run-time: Faithfulness Gate 3 (regex grounding — every ₹, %, day/month/year in the reply must appear in retrieved chunks).- Post-hoc: Gold Q&A eval (factual_accuracy metric).**Mitigation:** Block reply → return safe refusal → log to `logs/hallucinations.jsonl`. Audit log enables manual review and corpus improvement.24 unmodified lines**Description:** Sarvam-M emits `<think>...</think>` reasoning. If `max_tokens` is exhausted before `</think>` is reached, the reply is unusable. This was a recurring issue when Sarvam-M was the primary brain.**Detection:** `strip_think_tags()` checks for `<think>` without matching `</think>`.**Resolution (2026-05-14, D-019; refined 2026-05-15, KI-080):** Sarvam-M moved out of the brain role entirely. The NIM brain chains (Qwen 80B / Nemotron 30B / Groq Llama-3.3 / OpenRouter GPT-OSS as probe-elected candidates) handle all reasoning; they emit direct responses without `<think>` preambles. Per-turn primary is elected from a 60s background probe (KI-080, [ADR-031](../60-decisions/ADR-031-sticky-primary-election.md)) — adapts to live provider degradation. Sarvam-M remains only for Indic translation (Hinglish ↔ English), where its `<think>` doesn't interfere because translation outputs are short. F-04 cannot fire on the current stack.**Owner:** `backend/orchestrator.py`**Status:** Resolved by architecture change.38 unmodified lines**Description:** End-to-end (user speech end → bot speech start) p95 > 7s (Doc 01 C1).**Detection:** Per-turn latency logged in `logs/turns.jsonl`. Aggregate via eval harness.**Mitigation v1:**- Tiered brain routing (D-019): voice turns and fact-find go to the fast-brain chain (Nemotron Nano 30B primary) (~3-4s TTFT); only `comparison` and `recommendation` intents hit V4-Pro (slower but higher quality). Sarvam-M no longer in the brain hot path.- TTS happens server-side and is streamed via base64 in same response. Future: WebSocket for streaming TTS.**Status:** Mostly within budget for Llama brain (3-4s); Sarvam-M brain occasionally hits 15-25s due to reasoning.### F-10 — Streamlit-Cloud-Free / Render-Free cold start67 unmodified lines### F-16 — Translation cascade introduces drift after faithfulness gate**Description:** Indic queries use the cascade: Sarvam translates Hinglish → English, DeepSeek reasons → English answer, faithfulness gates run on English answer, Sarvam translates English answer → Hinglish. **Faithfulness does NOT re-verify the final Hinglish output.** If Sarvam corrupts the translation (drops a citation, changes a number, invents a benefit), we wouldn't catch it.**Detection v1:** None automated. Manual spot-check of bilingual eval set.**Mitigation v1:** Sarvam translator system prompt explicitly forbids changing numbers/citations + caps at 60 words; preserves `[Source: ...]` tags.**Mitigation v2:** Back-translate Hinglish→English; compare against original English; block if cosine similarity < 0.85.12 unmodified lines| M-07 | Nightly synthetic eval cron | Infra | v2 || M-08 | Live-traffic spot grading | Eval | v2 || M-09 | 3-judge consensus for grader | Eval | v2 || M-10 | Sarvam-M no longer brain — V4-Flash/V4-Pro on NIM | Orchestrator (D-019) | Live ✅ || M-11 | Faithfulness 4-gate verifier | Orchestrator | Live ✅ |18 unmodified lines1920212223242524 unmodified lines5051525354555638 unmodified lines959697989910010110210367 unmodified lines17117217317417517617712 unmodified lines19019119219319418 unmodified lines**Description:** Bot claims a policy covers something it doesn't, or quotes a wrong waiting period / sub-limit.**Detection:**- Run-time: Faithfulness Gate 4 (LLM-judge — JUDGE_CHAIN with NIM Mistral Large 3 675B primary; different family from the Gemini brain so grading stays non-circular; see [ADR-040](../60-decisions/ADR-040-google-gemini-primary.md)). KI-171 skips Gate 4 on `fact_find` + `recommendation` intents.- Run-time: Faithfulness Gate 3 (regex grounding — every ₹, %, day/month/year in the reply must appear in retrieved chunks).- Post-hoc: Gold Q&A eval (factual_accuracy metric).**Mitigation:** Block reply → return safe refusal → log to `logs/hallucinations.jsonl`. Audit log enables manual review and corpus improvement.24 unmodified lines**Description:** Sarvam-M emits `<think>...</think>` reasoning. If `max_tokens` is exhausted before `</think>` is reached, the reply is unusable. This was a recurring issue when Sarvam-M was the primary brain.**Detection:** `strip_think_tags()` checks for `<think>` without matching `</think>`.**Resolution (2026-05-14, D-019 → refined 2026-05-15 across KI-080 / KI-167 / KI-179):** Sarvam-M moved out of the brain role entirely. The current Brain Fast + Brain Main chains lead with Google AI Studio (Gemini 2.0 / 2.5 Flash) with NIM (Qwen 80B / Mistral Large 3 675B / Llama-4 Maverick) and OpenRouter `:free` (Nemotron-3-Super, Qwen 80B) as fallbacks; see [ADR-040](../60-decisions/ADR-040-google-gemini-primary.md). All chain primaries emit direct responses without `<think>` preambles, and native JSON mode (`response_mime_type=application/json` on Gemini, `response_format={"type":"json_object"}` on NIM / OpenRouter) provides server-side parseable output. Per-turn primary is elected from a 300s background probe (KI-080, [ADR-031](../60-decisions/ADR-031-sticky-primary-election.md)) — adapts to live provider degradation. Sarvam-M remains only for Indic translation. F-04 cannot fire on the current stack.**Owner:** `backend/orchestrator.py`**Status:** Resolved by architecture change.38 unmodified lines**Description:** End-to-end (user speech end → bot speech start) p95 > 7s (Doc 01 C1).**Detection:** Per-turn latency logged in `logs/turns.jsonl`. Aggregate via eval harness.**Mitigation v1:**- Tiered brain routing (ADR-040): voice turns and fact-find go to Brain Fast (Gemini 2.0 Flash primary, ~1-2s TTFT); `comparison` and `recommendation` intents hit Brain Main (Gemini 2.5 Flash primary, slightly higher latency but stronger synthesis). Sarvam-M no longer in the brain hot path.- TTS happens server-side and is streamed via base64 in same response. Future: WebSocket for streaming TTS.**Status:** Brain Fast / Brain Main typically respond in 2-6s; long-tail latency comes from heavy fallback candidates (NIM Mistral 675B) only when Google quota is exhausted.### F-10 — Streamlit-Cloud-Free / Render-Free cold start67 unmodified lines### F-16 — Translation cascade introduces drift after faithfulness gate**Description:** Indic queries use the cascade: Sarvam translates Hinglish → English, the elected Brain Main candidate (Gemini 2.5 Flash by default, NIM Mistral 675B / Maverick / Qwen as fallbacks) reasons → English answer, faithfulness gates run on English answer, Sarvam translates English answer → Hinglish. **Faithfulness does NOT re-verify the final Hinglish output.** If Sarvam corrupts the translation (drops a citation, changes a number, invents a benefit), we wouldn't catch it.**Detection v1:** None automated. Manual spot-check of bilingual eval set.**Mitigation v1:** Sarvam translator system prompt explicitly forbids changing numbers/citations + caps at 60 words; preserves `[Source: ...]` tags.**Mitigation v2:** Back-translate Hinglish→English; compare against original English; block if cosine similarity < 0.85.12 unmodified lines| M-07 | Nightly synthetic eval cron | Infra | v2 || M-08 | Live-traffic spot grading | Eval | v2 || M-09 | 3-judge consensus for grader | Eval | v2 || M-10 | Sarvam-M no longer brain — Gemini 2.0 / 2.5 Flash primary on Brain Fast / Brain Main, NIM fallback | Orchestrator (ADR-040) | Live ✅ || M-11 | Faithfulness 4-gate verifier | Orchestrator | Live ✅ |
61 unmodified lines626364656667686970717273747593 unmodified lines16917017117217317417517617717861 unmodified lines| 8 | Backend | FE↔BE type safety | **`openapi-typescript` codegen** from FastAPI's auto-generated OpenAPI | Locked | Single source of truth; backend route changes propagate automatically | tRPC (Node-only), GraphQL, manual TS types || 9 | Orchestration | STT | **Sarvam Saarika v2.5** | Locked | Sarvam-first; their newer Indic ASR model | Whisper-large-v3, Deepgram Nova-2, Sarvam Saaras v3 || 10 | Orchestration | TTS | **Sarvam Bulbul** | Locked | Sarvam-first; Indic prosody first-class | ElevenLabs, OpenAI TTS, Coqui local || 11 | Orchestration | LLM (brain) | **NVIDIA NIM tiered: Qwen 80B (current brain primary) (heavy) + Nemotron Nano 30B (current fast-brain primary) (fast)** | Locked (D-019) | V4-Pro (1.6T/49B MoE, frontier, beats Opus-4.6 + GPT-5.4 on SimpleQA) for comparison/recommendation; V4-Flash (284B/13B MoE, lower TTFT) for voice + fact-find. Single NIM key, free tier, no daily cap. Sarvam-M moved to Indic translation only — its 2048 output cap was truncating advisor responses. | Sarvam-M as brain (rejected — truncation), OpenRouter `:free` (rejected — 50/day cap), Gemini 2.5 Flash (rejected — adds 2nd provider ecosystem), GPT-4o via GitHub Models (rejected — same 50/day cap) || 12 | Orchestration | LLM (grader / self-critique) | **NVIDIA the judge chain (Mistral Large 3 675B primary) (Meta MoE)** | Locked (D-019) | Different family from the brain (Qwen 80B primary) — Meta MoE judging DeepSeek MoE, so the brain does not mark its own homework. Same NIM endpoint and key. 400B/17B MoE, frontier-tier. Replaces Groq Llama-3.3-70B (30 req/min cap blocked sweeps). | Groq Llama (rejected — rate limit), Cerebras Qwen-235B (rejected — same family as another DeepSeek path), Sarvam-M held-out || 13 | Orchestration | Embeddings | **BGE-small-en-v1.5 (local CPU, sentence-transformers)** | Locked | Free, runs offline, 384-dim, BEIR-strong on insurance/legal text. Voyage path kept for v2 swap (~3pp retrieval-quality delta in BEIR-style spot checks). | Voyage AI voyage-3 (rejected for v1 — 3 RPM free-tier blocked 104-PDF ingest), OpenAI text-embedding-3-small (rejected — no GPT), Cohere || 14 | Storage | Structured DB | **DuckDB** (single file) | Locked | One file, columnar, no server; deploys via `git clone` | SQLite, Postgres || 15 | Storage | Vector DB | **Chroma** (local persisted) | Locked | Embedded, no infra, supports metadata filtering | FAISS, Pinecone, Qdrant, Weaviate || 16 | Ingest | PDF parsing | **pdfplumber** | Locked | Clean text + page numbers — critical for citation grammar | PyMuPDF, Unstructured.io || 17 | Ingest | Chunking | **Custom 800-token chunks, 120-token overlap, page-aware** | Locked | Standard for technical docs; overlap protects clause boundaries | LangChain text splitter, fixed-size || 18 | Ingest | Structured extraction | **Sarvam-M (Llama-3.3-70B / DeepSeek-V3 fallback) with Pydantic structured output + self-critique pass** | Locked | Reliable JSON-mode extraction; self-critique gives per-field confidence; fallback brain handles tables / complex clauses Sarvam-M misses | Pure regex, LangChain extraction, Instructor lib || 19 | Pricing | Approach | **Hand-curated illustrative bands** from public PolicyBazaar quotes | Locked | Honest, defensible; "advisor-not-broker" positioning | Live scraping, actuarial model || 20 | Cross-cutting | Auth | **None for v1** (single-tenant demo) | Locked | Out of scope per `01-requirements.md` §7 | Auth0, Clerk, NextAuth || 21 | Cross-cutting | Observability | **JSONL turn log + cost tracker** | Locked | Lightweight; one log file, queryable post-hoc | Langfuse, Helicone, custom dashboard |93 unmodified lines| Consultative persona | D-008 || 10 insurers × all health policies | D-009 || Secret handling | D-010 || Embeddings provider (pending) | D-011 || Render deployment over alternatives | D-012 || Next.js + Tailwind + shadcn UI stack | D-013 || GPT-4o-mini as grader to avoid circular eval | D-014 |---61 unmodified lines62636465666768697071727374757693 unmodified lines17017117217317417517617717817918018161 unmodified lines| 8 | Backend | FE↔BE type safety | **`openapi-typescript` codegen** from FastAPI's auto-generated OpenAPI | Locked | Single source of truth; backend route changes propagate automatically | tRPC (Node-only), GraphQL, manual TS types || 9 | Orchestration | STT | **Sarvam Saarika v2.5** | Locked | Sarvam-first; their newer Indic ASR model | Whisper-large-v3, Deepgram Nova-2, Sarvam Saaras v3 || 10 | Orchestration | TTS | **Sarvam Bulbul** | Locked | Sarvam-first; Indic prosody first-class | ElevenLabs, OpenAI TTS, Coqui local || 11 | Orchestration | LLM — Brain Fast (sales_brain) | **Gemini 2.0 Flash** primary (Google AI Studio, 1500 req/day free, native JSON mode) → NIM Qwen 80B → NIM Mistral Large 3 675B → NIM Llama-4 Maverick → OR `:free` (Nemotron-3-Super 120B, Qwen 80B) → NIM Nemotron 49B last resort | Locked (ADR-040) | Frontier free-tier conversational quality on the fact-find surface; native JSON mode via `response_mime_type=application/json` matches NIM's `response_format` contract validated since [ADR-039](../60-decisions/ADR-039-llm-driven-sales-brain.md) / KI-167. 6-level fallback survives Google quota exhaustion or 429. | NIM-only (rejected — strictly worse free-tier primary post-Gemini), OR Llama 3.3 70B (rejected — no `response_format` on OR free per KI-178), Sarvam-M as brain (rejected long ago for `<think>` truncation) || 11a | Orchestration | LLM — Brain Main (QA / comparison / recommendation) | **Gemini 2.5 Flash** primary → NIM Mistral Large 3 675B → NIM Llama-4 Maverick → NIM Qwen 80B → OR Nemotron-3-Super 120B → NIM Nemotron 49B last resort | Locked (ADR-040) | Higher synthesis quality than 2.0 Flash on long-context recommendation; shares the 1500 req/day Google quota. | (see row 11) || 12 | Orchestration | LLM — Judge (faithfulness Gate 4) | **NIM Mistral Large 3 675B** primary → NIM Llama-4 Maverick → OR Qwen 80B `:free` → NIM Nemotron 49B last resort | Locked (ADR-040) | Different family from the Gemini brain — preserves the brain ↔ judge family-diversity invariant ([ADR-014](../60-decisions/ADR-014-groq-llama-grader.md) lineage). KI-171 skips the judge on `fact_find` + `recommendation` intents (no retrieved context to grade). | Gemini as judge (rejected — same family as brain, circular grading), Groq Llama (rejected — rate cap), Sarvam-M held out || 13 | Orchestration | Embeddings | **BGE-small-en-v1.5 (local CPU, sentence-transformers)** | Locked | Free, runs offline, 384-dim, BEIR-strong on insurance/legal text. Voyage path kept for v2 swap (~3pp retrieval-quality delta in BEIR-style spot checks). | Voyage AI voyage-3 (rejected for v1 — 3 RPM free-tier blocked 104-PDF ingest), OpenAI text-embedding-3-small (rejected — no GPT), Cohere || 14 | Storage | Structured DB | **DuckDB** (single file) | Locked | One file, columnar, no server; deploys via `git clone` | SQLite, Postgres || 15 | Storage | Vector DB | **Chroma** (local persisted) | Locked | Embedded, no infra, supports metadata filtering | FAISS, Pinecone, Qdrant, Weaviate || 16 | Ingest | PDF parsing | **pdfplumber** | Locked | Clean text + page numbers — critical for citation grammar | PyMuPDF, Unstructured.io || 17 | Ingest | Chunking | **Custom 800-token chunks, 120-token overlap, page-aware** | Locked | Standard for technical docs; overlap protects clause boundaries | LangChain text splitter, fixed-size || 18 | Ingest | Structured extraction | **`NimChainLLM(BRAIN_CHAIN)` with Pydantic structured output + self-critique pass** | Locked | Reliable JSON-mode extraction via native provider JSON mode; self-critique runs through `NimChainLLM(JUDGE_CHAIN)` for per-field confidence. | Pure regex, LangChain extraction, Instructor lib || 19 | Pricing | Approach | **Hand-curated illustrative bands** from public PolicyBazaar quotes | Locked | Honest, defensible; "advisor-not-broker" positioning | Live scraping, actuarial model || 20 | Cross-cutting | Auth | **None for v1** (single-tenant demo) | Locked | Out of scope per `01-requirements.md` §7 | Auth0, Clerk, NextAuth || 21 | Cross-cutting | Observability | **JSONL turn log + cost tracker** | Locked | Lightweight; one log file, queryable post-hoc | Langfuse, Helicone, custom dashboard |93 unmodified lines| Consultative persona | D-008 || 10 insurers × all health policies | D-009 || Secret handling | D-010 || Embeddings provider (pending → BGE local) | D-011 / ADR-011 || Render deployment (superseded by HF Spaces) | D-012 / ADR-012 || Next.js + Tailwind + shadcn UI stack | D-013 || Groq Llama grader (superseded → NIM Mistral) | D-014 / ADR-014 / ADR-040 || LLM-driven sales brain (rip-out of `<FF>` trailer) | ADR-039 || Google Gemini Flash as Tier 0 primary | ADR-040 |---
2 unmodified lines345678910111214 unmodified lines272829303132333435363738394041424344454647484950515253545556575859606162636465664 unmodified lines7172737475767778798081828384858687888990912 unmodified lines94959697989910010110210310410510610710810911011111211311411511611711811912012112212312426 unmodified lines15115215315415515615715815916016116216316416516616716877 unmodified lines2462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962974 unmodified lines3023033043053063073083093103113122 unmodified lines| Field | Value || --- | --- || Project | Insurance Sales Portfolio Expert || Document version | 0.1 (draft) || Date | 2026-05-13 || Depends on | `01-requirements.md` || Status | In review |---14 unmodified lines│ audio bytes / text / clicks▼┌─────────────────────────────────────────────────────────────────────┐│ STREAMLIT UI (app/main.py) ││ ─ chat pane · audio recorder · filter sidebar · comparison view ││ ─ session state · @st.cache_resource for heavy clients │└─────────────────────────────────────────────────────────────────────┘│ │ ││ audio bytes │ user_query (text) │ filter / select▼ ▼ ▼┌──────────────────┐ ┌─────────────────────┐ ┌──────────────────────┐│ VOICE (app/voice)│ │ ORCHESTRATOR │ │ STRUCTURED STORE ││ ─ Sarvam Saaras │ ──────► │ (app/orchestrator) │ ◄ │ DuckDB ││ (STT) │ text │ ─ persona prompt │ │ ─ 1 row per policy ││ ─ Sarvam Bulbul │ ◄────── │ ─ fact-find graph │ │ ─ 40-50 fields ││ (TTS) │ audio │ ─ tool routing │ │ ─ filter / compare │└──────────────────┘ │ ─ citation grammar │ └──────────────────────┘│ │ ▲│ │ │ extracted└──────────┬──────────┘ │ at ingest time│ │▼ │┌─────────────────────┐ ││ Sarvam-M (LLM) │ │└─────────────────────┘ │▲ ││ retrieved chunks ││ │┌──────────┴──────────┐ ││ VECTOR STORE │ ┌───────────┴──────────┐│ Chroma │ │ INGEST PIPELINE ││ ─ chunk + embedding │ ◄ │ (rag/ingest.py) ││ ─ metadata: policy, │ │ ─ download PDFs ││ page, clause │ │ ─ chunk + embed │└─────────────────────┘ │ ─ LLM extract → DB ││ ─ per-insurer adapter│└──────────────────────┘▲│ raw PDFs┌────────────┴─────────┐4 unmodified lines---## 2. Stack picks (v1)| Layer | Pick | Why | Alternative considered | Decision in `decisions.md` || --- | --- | --- | --- | --- || STT | **Sarvam Saaras** | Sarvam-first per assignment context; strong Indic/Hinglish handling | Whisper-large-v3, Deepgram Nova | D-006 || TTS | **Sarvam Bulbul** | First-party Indic prosody; Sarvam-first | ElevenLabs, OpenAI TTS | D-006 || LLM | **Sarvam-M** (or current Sarvam flagship) | Sarvam-first; Indic-tuned reasoning | GPT-4o, Claude Sonnet | D-006 || Embeddings | **Sarvam embedding API if available, else `text-embedding-3-small`** | Will benchmark; whichever scores higher on retrieval @5 against our gold set | OpenAI embeddings, BGE-large local | D-006 || Vector DB | **Chroma** (local, persisted to disk) | Zero-config, embedded, works on Streamlit Cloud | FAISS (no metadata filtering), Qdrant (overkill) | D-004 || Structured DB | **DuckDB** (single file, embedded) | One-file, columnar, no server, deployable to Streamlit Cloud | SQLite, Postgres | D-004 || UI | **Streamlit** | Fastest v1; business logic decoupled so v2 swaps UI only | FastAPI + React (v2) | D-005 || Audio capture | **`streamlit-mic-recorder`** or `streamlit-webrtc` (whichever proves stable in <1h spike) | Required for browser-side mic | Native HTML5 + WebSocket (too much glue) | — || Deployment | **Streamlit Community Cloud** | Free, GitHub-connected, supports Streamlit out of box, secrets UI for API keys | Render, Fly.io | — |**Provider abstraction:** every provider is behind a thin interface (`app/providers/stt.py`, `app/providers/tts.py`, `app/providers/llm.py`) so a benchmark swap is a config flag. **This is non-negotiable** — it's c-readiness commitment #5.---2 unmodified lines```user speaks│▼ (audio bytes)voice.transcribe() ── Sarvam Saaras ──► text│▼orchestrator.handle_turn(text, session)│├── if fact-find phase: needs_finder.next_question(profile) → returns next Q│├── if filter/compare intent detected: structured_store.query(filters) → rows│└── if Q&A intent:rag.retrieve(query, top_k=5)─ returns chunks with (policy_id, page, clause, text, score)llm.generate(persona_prompt + chat_history + retrieved_chunks + user_query)─ enforces citation grammar [Source: ...]─ enforces refusal when retrieval is weak─ returns text response│▼voice.synthesize(text) ── Sarvam Bulbul ──► audio bytes│▼ui.play_audio(audio_bytes)ui.append_to_chat(text + citations)log_turn({stt_confidence, retrieved_ids, latency_ms, cost_usd, refused})```---26 unmodified linesfor pdf in corpus:text_chunks = chunk(pdf, target_tokens=800, overlap=120)# chunks indexed in Chroma with metadata: policy_id, page, clause_path# one-shot LLM extraction with the schema as a structured-output targetextracted = llm.extract_structured(full_pdf_text,schema=HealthPolicy,few_shot_examples=[hdfc_ergo_example, niva_bupa_example])# self-critique pass: LLM checks every field's evidence in the sourceconfidence_per_field = llm.self_critique(extracted, full_pdf_text)extracted.extraction_confidence_pct = aggregate(confidence_per_field)# write to DuckDBstructured_store.upsert(extracted)```77 unmodified lines```insurance-sales-bot/├── app/│ ├── __init__.py│ ├── main.py # Streamlit entrypoint│ ├── orchestrator.py # turn handler, persona prompt, intent routing│ ├── needs_finder.py # adaptive fact-find question graph│ ├── ui_chat.py│ ├── ui_filter.py # schema-driven filter UI│ ├── ui_compare.py # side-by-side comparison│ └── providers/│ ├── stt.py # Sarvam Saaras client behind interface│ ├── tts.py # Sarvam Bulbul client behind interface│ ├── llm.py # Sarvam-M client behind interface│ └── embeddings.py├── rag/│ ├── corpus/ # raw PDFs (committed for reproducibility)│ ├── extracted/ # per-policy JSON (committed)│ ├── vectors/ # Chroma persistence (gitignored — rebuilt)│ ├── policies.duckdb # structured store (committed)│ ├── schema.py # Pydantic HealthPolicy model│ ├── ingest.py # download → chunk → embed → extract → store│ ├── retrieve.py # query → top-k chunks│ ├── extract.py # LLM-driven structured extraction│ └── adapters/│ ├── base.py│ ├── star_health.py│ ├── hdfc_ergo.py│ └── ... (10 adapters)├── eval/│ ├── gold_qa.json # 50–100 gold Q&A pairs (10/policy for top policies)│ ├── grader.py # automated grader (LLM judge + regex)│ ├── run.py # batch runner│ └── results.md # last run's accuracy table├── data/│ ├── insurers.json # 10 insurers metadata│ └── corpus_urls.md # output of corpus-discovery sub-agent├── 70-docs/│ ├── 01-requirements.md│ ├── 02-architecture.md # THIS FILE│ ├── 03-eval-plan.md│ ├── 04-failure-modes.md│ ├── 05-needs-analysis-flow.md│ ├── decisions.md│ └── ROADMAP.md├── tests/│ └── test_smoke.py├── streamlit_app.py # Streamlit Cloud entrypoint (thin wrapper)├── requirements.txt├── .env / .env.example├── .gitignore4 unmodified lines## 10. Deployment- **Repo:** `github.com/rohitsar567/insurance-sales-bot` (public)- **Hosting:** Streamlit Community Cloud — `share.streamlit.io` connects to the repo, deploys `streamlit_app.py` on push- **Secrets:** Sarvam API key set via Streamlit Cloud's secrets manager (mirrors `.env`)- **Resources:** ~1 GB ephemeral, persistent disk for `rag/` (corpus + DuckDB committed to repo so deploy is reproducible from `git clone`)- **Vector store rebuild:** on first deploy, app detects empty `rag/vectors/` and rebuilds from `rag/corpus/` (one-time ~5 min cold start; subsequent starts cached)---2 unmodified lines345678910111214 unmodified lines272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889904 unmodified lines95969798991001011021031041051061071081091101111121131141151161171181191202 unmodified lines12312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716826 unmodified lines19519619719819920020120220320420520620720820921021121277 unmodified lines2902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563574 unmodified lines3623633643653663673683693703713723732 unmodified lines| Field | Value || --- | --- || Project | Insurance Sales Portfolio Expert || Document version | 0.2 || Date | 2026-05-15 || Depends on | `problem-statement.md` || Status | Live |---14 unmodified lines│ audio bytes / text / clicks▼┌─────────────────────────────────────────────────────────────────────┐│ NEXT.JS 14 UI (frontend/src/app/page.tsx) ││ ─ chat surface · Live + push-to-talk toggle · profile builder ││ ─ Web Speech (interim) + MediaRecorder (authoritative) hybrid ││ ─ in-DOM <audio> for TTS playback (barge-in compatible) │└─────────────────────────────────────────────────────────────────────┘│ │ ││ audio blob │ user_query (text) │ filter / select▼ ▼ ▼┌──────────────────┐ ┌─────────────────────┐ ┌──────────────────────┐│ VOICE │ │ ORCHESTRATOR │ │ STRUCTURED STORE ││ ─ Sarvam Saarika │ ──────► │ (backend/ │ ◄ │ DuckDB ││ STT │ text │ orchestrator.py) │ │ ─ 1 row per policy ││ ─ Sarvam Bulbul │ ◄────── │ ─ classify_intent │ │ ─ 62-field schema ││ TTS │ audio │ ─ profile RAG │ │ ─ filter / compare │└──────────────────┘ │ ─ sales_brain / │ └──────────────────────┘│ QA brain dispatch │ ▲│ ─ faithfulness gates│ │ extracted└──────────┬──────────┘ │ at ingest time│ │▼ │┌──────────────────────────────────┐ ││ LLM CHAINS (3-tier, ADR-040) │ ││ ┌────────────────────────────┐ │ ││ │ Brain Fast (sales_brain): │ │ ││ │ Gemini 2.0 Flash (Tier 0) │ │ ││ │ → NIM Qwen/Mistral/Llama4 │ │ ││ │ → OR :free fallback │ │ ││ │ → NIM Nemotron 49B (last) │ │ ││ ├────────────────────────────┤ │ ││ │ Brain Main (synthesis): │ │ ││ │ Gemini 2.5 Flash (Tier 0) │ │ ││ │ → NIM Mistral/Maverick/ │ │ ││ │ Qwen │ │ ││ │ → OR Nemotron-3-Super │ │ ││ │ → NIM Nemotron 49B (last) │ │ ││ ├────────────────────────────┤ │ ││ │ Judge (cross-family): │ │ ││ │ NIM Mistral Large 3 675B │ │ ││ │ → NIM Llama-4 Maverick │ │ ││ │ → OR Qwen 80B :free │ │ ││ │ → NIM Nemotron 49B (last) │ │ ││ └────────────────────────────┘ │ ││ Sticky-primary election (KI-080)│ ││ per chain via │ ││ backend/llm_health.py probe loop│ │└──────────────────────────────────┘ │▲ ││ retrieved chunks ││ │┌──────────┴──────────┐ ││ VECTOR STORE │ ┌───────────┴──────────┐│ Chroma │ │ INGEST PIPELINE ││ ─ chunk + BGE-small │ ◄ │ (rag/ingest.py) ││ ─ metadata: policy, │ │ ─ download PDFs ││ page, clause │ │ ─ chunk + embed ││ ─ profile chunks │ │ ─ LLM extract → DB ││ (session-scoped) │ │ ─ per-insurer adapter│└─────────────────────┘ └──────────────────────┘▲│ raw PDFs┌────────────┴─────────┐4 unmodified lines---## 2. Stack picks (current)| Layer | Pick | Why | Decision || --- | --- | --- | --- || STT | **Sarvam Saarika v2.5** | Best-in-class Indian-accent + Hinglish handling. | [ADR-006](../60-decisions/ADR-006-sarvam-first-stack.md) || TTS | **Sarvam Bulbul v2** | First-party Indic prosody; ₹ + lakh shorthand normalised pre-TTS by `voice_format.py`. | [ADR-006](../60-decisions/ADR-006-sarvam-first-stack.md) || LLM — Brain Fast (sales_brain) | **Gemini 2.0 Flash** primary → NIM Qwen 80B / Mistral Large 3 675B / Llama-4 Maverick → OR `:free` (Nemotron-3-Super, Qwen 80B) → NIM Nemotron 49B last resort. Native JSON mode via `response_mime_type=application/json` / `response_format={"type":"json_object"}`. | Frontier free-tier quality on Gemini (1500 req/day) with NIM diversity below it. Sticky-primary election (KI-080) picks one candidate per call. | [ADR-040](../60-decisions/ADR-040-google-gemini-primary.md), [ADR-039](../60-decisions/ADR-039-llm-driven-sales-brain.md) || LLM — Brain Main (QA / comparison / recommendation) | **Gemini 2.5 Flash** primary → NIM Mistral 675B / Maverick / Qwen 80B → OR Nemotron-3-Super → NIM Nemotron 49B last resort. | Higher synthesis quality than 2.0 on long-context recommendation; shares the Google quota with sales_brain. | [ADR-040](../60-decisions/ADR-040-google-gemini-primary.md) || LLM �� Judge (faithfulness Gate 4) | **NIM Mistral Large 3 675B** primary → NIM Llama-4 Maverick → OR Qwen 80B `:free` → NIM Nemotron 49B last resort. | Different family from the Gemini brain — preserves brain ↔ judge family-diversity invariant ([ADR-014](../60-decisions/ADR-014-groq-llama-grader.md) lineage). | [ADR-040](../60-decisions/ADR-040-google-gemini-primary.md) || Indic translation | **Sarvam-M** | Best-in-class Hinglish ↔ English translation. | [ADR-006](../60-decisions/ADR-006-sarvam-first-stack.md) || Embeddings | **BGE-small-en-v1.5 (local CPU, 384-d)** | Free, runs offline, no rate limits. | [ADR-011](../60-decisions/ADR-011-bge-local-embeddings.md) || Vector DB | **Chroma** (local persisted) | Embedded, supports metadata filtering, HNSW bloat guard ([ADR-029](../60-decisions/ADR-029-hnsw-bloat-tripwire.md)) | [ADR-004](../60-decisions/ADR-004-hybrid-structured-vector.md) || Structured DB | **DuckDB** (single file) | One-file, columnar, no server. | [ADR-004](../60-decisions/ADR-004-hybrid-structured-vector.md) || UI | **Next.js 14 (App Router) + Tailwind v4 + shadcn/ui** | Production-pattern, full UI flexibility. | [ADR-005](../60-decisions/ADR-005-nextjs-fastapi-frontend.md), [ADR-013](../60-decisions/ADR-013-tailwind-shadcn-ui.md) || Audio capture | **Web Speech API (interim text) + `MediaRecorder` (authoritative blob), hybrid (KI-168)** | Live UX cadence on the UI + Sarvam-grade STT for the actual transcript. | [ADR-028](../60-decisions/ADR-028-voice-ux-single-default-mode.md) || Deployment | **HF Spaces (Docker) + companion HF Dataset for corpus / vectors** | Free, GitHub-mirrored, snapshot_download for data hydration. | [ADR-012](../60-decisions/ADR-012-render-then-hf-space-deploy.md), [ADR-020](../60-decisions/ADR-020-code-data-split-hf-dataset.md) |**Provider keys:** `GOOGLE_API_KEY` (Google AI Studio, 1500 req/day free), `NVIDIA_NIM_API_KEY` (free, 40 req/min), `OPENROUTER_API_KEY` ($10 unlocks 1000 req/day on `:free` models), `SARVAM_API_KEY` (Sarvam STT + TTS + translation).**Provider abstraction:** every LLM provider lives under `backend/providers/` (`google_gemini_llm.py`, `nvidia_nim_llm.py`, `openrouter_llm.py`) behind a common `LLMProvider` interface. `NimChainLLM` is provider-agnostic — chains may freely mix Google / NIM / OpenRouter candidates by URL. **This is non-negotiable** — it's c-readiness commitment #5.---2 unmodified lines```user speaks││ Web Speech streams interim transcript to chat input (live UX)│ MediaRecorder captures audio blob in parallel│▼ (browser silence-detect → audio blob)POST /api/transcribe ── Sarvam Saarika v2.5 ──► authoritative text│ (fallback to Web Speech transcript if Sarvam errors)│▼ (auto-submit)POST /api/chat → orchestrator.handle_turn(text, session)│├── if intent == fact_find:│ sales_brain.drive_sales_turn(profile, history, user_text)│ ─ ONE LLM call against FAST_BRAIN_CHAIN (Gemini 2.0 Flash primary)│ ─ native JSON mode returns {reply, captures, slot_driving, complete}│ ─ sales_brain_normalizer maps loose captures → canonical fields│ ─ KI-094 None-guard ensures null captures don't wipe filled fields│ ─ KI-171 skips faithfulness judge on fact-find turns│├── if intent == comparison: structured_store.query(filters) → rows│└── if intent ∈ {qa, recommendation}:rag.retrieve(query, top_k=10)─ returns chunks with (policy_id, page, clause, text, score)─ profile_rag chunks filtered to current session_id (KI-102)BRAIN_CHAIN.chat(persona_prompt + history + chunks + user_query)─ Gemini 2.5 Flash primary → NIM Mistral 675B fallback─ enforces citation grammar [Source: ...]─ refusal returned when retrieval is weakfaithfulness gates (skipped on recommendation per KI-171):Gate 1: retrieval floor Gate 2: citation integrityGate 3: regex numeric Gate 4: cross-family judge(NIM Mistral Large 3 675B)│▼voice.synthesize(text) ── Sarvam Bulbul v2 ──► base64 audio│ (voice_format.tts_preprocess strips CoT leaks + expands ₹ shorthand)│▼frontend in-DOM <audio> element plays the response (barge-in compatible)log_turn({intent, brain_used, retrieved_ids, latency_ms, faithfulness, refused})```---26 unmodified linesfor pdf in corpus:text_chunks = chunk(pdf, target_tokens=800, overlap=120)# chunks indexed in Chroma with metadata: policy_id, page, clause_path# one-shot LLM extraction with the schema as a structured-output targetextracted = NimChainLLM(BRAIN_CHAIN).extract_structured(full_pdf_text,schema=HealthPolicy,few_shot_examples=[hdfc_ergo_example, niva_bupa_example])# self-critique pass: judge LLM checks every field's evidence in the sourceconfidence_per_field = NimChainLLM(JUDGE_CHAIN).self_critique(extracted, full_pdf_text)extracted.extraction_confidence_pct = aggregate(confidence_per_field)# write to DuckDBstructured_store.upsert(extracted)```77 unmodified lines```insurance-sales-bot/├── backend/│ ├── main.py # FastAPI app; HTTP routes (/api/chat, /api/transcribe, /api/profile, admin)│ ├── orchestrator.py # turn handler, persona prompt, intent routing│ ├── sales_brain.py # LLM-driven fact-find (one call/turn, native JSON mode)│ ├── sales_brain_normalizer.py # deterministic post-processor over LLM captures│ ├── needs_finder.py # 9-slot fact-find SCHEMA (data only; prompts retired)│ ├── profile_extractor.py # conversational profile-update extractor│ ├── profile_store.py # persistent named-profile JSON store (KI-040)│ ├── profile_rag.py # session-scoped profile chunk in Chroma (KI-102)│ ├── faithfulness.py # 4-gate hallucination guard│ ├── persona.py # consultative-advisor system prompt│ ├── voice_format.py # TTS pre-processing (CoT strip, ₹ shorthand)│ ├── translator.py # Sarvam-M Indic ↔ English translation│ ├── llm_health.py # background probe + sticky-primary election│ ├── admin.py # /api/admin/* (LLM health, performance, profiles)│ └── providers/│ ├── sarvam_stt.py # Sarvam Saarika v2.5 client│ ├── sarvam_tts.py # Sarvam Bulbul v2 client│ ├── google_gemini_llm.py # Google AI Studio (Tier 0 primary)│ ├── nvidia_nim_llm.py # NIM client + NimChainLLM dispatcher│ ├── openrouter_llm.py # OpenRouter client (cross-provider diversity)│ └── local_embeddings.py # BGE-small-en-v1.5 sentence-transformers├── frontend/│ ├── src/app/page.tsx # chat surface + voice toolbar + tab switcher│ ├── src/lib/api.ts # typed API client (openapi-typescript codegen)│ ├── src/lib/useStreamingVoice.ts # hybrid Web Speech + MediaRecorder hook (KI-168)│ └── src/lib/useLiveConversation.ts # Live-mode VAD hook├── rag/│ ├── corpus/ # raw PDFs (hydrated from HF dataset at Docker build)│ ├── extracted/ # per-policy JSON (62-field HealthPolicy)│ ├── vectors/ # Chroma persistence (HF dataset side)│ ├── policies.duckdb # DuckDB rollup│ ├── schema.py # Pydantic HealthPolicy model│ ├── ingest.py # download → chunk → embed → extract → store│ ├── retrieve.py # query → top-k chunks│ └── extract.py # LLM-driven structured extraction├── 40-data/│ ├── policy_facts/ # curated {value, source_quote} JSONs (256 variants)│ ├── premiums/illustrative_premiums.json│ ├── reviews/ # per-insurer IRDAI + aggregator + Reddit data│ ├── profiles/ # persistent named profiles (KI-040)│ ├── llm_health.json # last probe snapshot│ └── llm_usage.jsonl # per-call telemetry├── eval/│ ├── gold_qa.json # 96+ gold Q&A pairs│ ├── run.py # in-process orchestrator runner + regex + judge│ └── results.md / results.json├── 70-docs/│ ├── 00-overview/ # roadmap + problem-statement│ ├── 10-architecture/ # this doc + stack-rationale + safety + scoring│ ├── 20-data-pipeline/ # ingestion-policy + info-source-map│ ├── 30-engineering/ # discovery-script + needs-analysis-flow│ ├── 40-evaluation/ # eval-methodology + known-issues + quality sprints│ └── 60-decisions/ # ADR-001 … ADR-040├── 80-audit/│ ├── ENTERPRISE_AUDIT.md # live defect register│ └── <run_id>/ # 100-persona audit transcripts├── tools/ # operational scripts (corpus / KB / probes / cron)├── tests/│ ├── test_routing_regression.py│ └── test_persona_*.py├── Dockerfile # HF Space image (Python + snapshot_download)├── requirements.txt├── .env / .env.example├── .gitignore4 unmodified lines## 10. Deployment- **Code repo:** `github.com/rohitsar567/insurance-sales-bot` (public; mirrored to HF Space `huggingface.co/spaces/rohitsar567/InsuranceBot`).- **Data repo:** `huggingface.co/datasets/rohitsar567/insurance-bot-data` — 539 files / ~498 MB (corpus PDFs + Chroma vectors + extracted JSONs). See [ADR-020](../60-decisions/ADR-020-code-data-split-hf-dataset.md).- **Hosting:** HF Space Docker image. `Dockerfile` runs `huggingface_hub.snapshot_download` at build time to hydrate `rag/` from the data repo so the Space repo stays code-only (~3 MB).- **Secrets (HF Space repository secrets):** `GOOGLE_API_KEY`, `NVIDIA_NIM_API_KEY`, `OPENROUTER_API_KEY`, `SARVAM_API_KEY`, admin password / IP allowlist. Mirrored locally in `.env` (chmod 600, gitignored).- **Per-deploy verification:** `tests/live_verify.py` runs a small smoke against the live Space URL post-deploy.- **Triple-mirror invariant ([ADR-024](../60-decisions/ADR-024-triple-mirror-code-and-data.md)):** every commit pushed to BOTH GitHub origin AND the HF Space remote; data side mirrors via `tools/upload_*_to_dataset.py`.---
128 unmodified lines129130131132133134135136137138128 unmodified lines## Implementation notesThe questions live in `backend/needs_finder.py::GRAPH`. To add a new question:1. Add a `Question(...)` entry with `id`, `prompt_en` (plain language + WHY), `prompt_hi` (Hindi rendering), `field` (which Profile attribute it sets), `is_core` (boolean — counts toward completeness), optional `condition` callable, optional `parser`.2. Add a row in `70-docs/scorecard-knowledge-graph.md` Part B showing how the new input shifts weights.3. Wire the shift into `_profile_tuned_weights()` in `backend/scorecard.py`.Drift between these three places breaks the transparency promise. Keep them in sync.128 unmodified lines129130131132133134135136137138139140141142128 unmodified lines## Implementation notesThe 9-slot fact-find SCHEMA still lives in `backend/needs_finder.py::GRAPH` — used now as the schema source for the `sales_brain` LLM system prompt rather than as a scripted question list. Each entry's `id`, `field`, `is_core`, and `condition` are consumed by the LLM as a structured contract; the `prompt_en` / `prompt_hi` strings are no longer rendered to the user post-[ADR-039](../60-decisions/ADR-039-llm-driven-sales-brain.md) / KI-167 (the LLM owns voice + cadence end-to-end via its system prompt + the conversation so far).To add a new question:1. Add a `Question(...)` entry with `id`, `field` (which Profile attribute it sets), `is_core` (boolean — counts toward completeness), optional `condition` callable, optional `parser`.2. Surface the new slot in the `sales_brain` system prompt's 9-slot schema (alongside accepted value shapes + examples) so the LLM knows to capture it. See `backend/sales_brain.py::_SYSTEM_PROMPT`.3. Wire any post-capture validation into `backend/sales_brain_normalizer.py` (enum coercion, INR parsing, bounds).4. Add a row in `70-docs/scorecard-knowledge-graph.md` Part B showing how the new input shifts weights.5. Wire the shift into `_profile_tuned_weights()` in `backend/scorecard.py`.Drift between these places breaks the transparency promise. Keep them in sync.
12345678910111213141516171819202122232449 unmodified lines7475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149# 05 — Needs Analysis Flow (Fact-Find)| Field | Value || --- | --- || Project | Insurance Sales Portfolio Expert || Version | 0.1 || Date | 2026-05-13 || Implementation | `backend/needs_finder.py` |## 0. Why an explicit graph (not "let the LLM figure it out")A good Independent Financial Advisor opens with a stable, repeatable set of questions — and conditionally deep-dives based on the buyer's signal. We replicate this with an **explicit question graph**, not an LLM that improvises every session.Why:1. **Auditable behavior.** A reviewer can see the graph, trace any session, and check why a question was (or wasn't) asked.2. **Testable.** Pure functions of `Profile → Question`. Every branch can be unit-tested.3. **Fail-soft.** Even if the LLM brain degrades, the question flow still works.4. **Bilingual by construction.** Each node has English + Hindi prompts side by side.## 1. The graph```┌─────────────────────────────┐49 unmodified lines## 2. Termination criteriaThe graph emits `next_question = None` (i.e., ready to recommend) when all of:1. All 6 core questions answered (age, dependents, income, existing_cover, primary_goal, location)2. All applicable conditional questions answered (parents_age if dependents include parents)3. health_conditions and budget_band answeredOr when the user sets `profile.free_form_session = True` — the orchestrator skips fact-find and answers free questions directly.## 3. Bilingual promptsEvery node has both `prompt_en` and `prompt_hi`. The orchestrator picks based on the user's detected language. Example:| Node | English | Hindi || --- | --- | --- || age | "To start, what's your age?" | "शुरू करते हैं — आपकी उम्र क्या है?" || dependents | "Who else do you want to cover…" | "आपके अलावा किस-किस को cover करना है…" || budget | "What annual premium budget…" | "Premium के लिए सालाना कितना खर्च…" |This is what "Indic-native, not translated" (Doc 01 §5.3) looks like in practice — the question is *authored* in both languages, not machine-translated at runtime.## 4. Parsing user answersEach node has a `parser` callable that normalizes the user's natural-language answer into a typed Profile field:- `age`: `lambda s: int("".join(c for c in s if c.isdigit())[:3] or 0) or None`- `dependents`: free-form string (will be normalized via LLM in v1.1)- `income_band`: bucketed via keyword match ("5 lakh" → "under_5L")When the parser returns `None`, we treat the question as unanswered and re-ask (v1 simply leaves the field as None and moves on — re-ask is v1.1).## 5. How the orchestrator uses this```pythonprofile = Profile.from_session(session_id)q = next_question(profile, language=detected_language)if q is not None:# Still in fact-find phase — ask the next questionreply = q.prompt_hi if language == "indic" else q.prompt_enprofile.asked.append(q.id)else:# Profile complete — proceed to retrieval + recommendationchunks = retrieve(user_query, top_k=5)reply = brain.generate(...)```The orchestrator can also let the user drive the conversation freely — if the user immediately asks a specific question like "compare Star and HDFC ERGO," we set `free_form_session = True` and skip the fact-find.## 6. What the user sees```Bot: "Hi, I'm your AI insurance advisor. To start, what's your age?"User: "I'm 32"Bot: "Got it. Who else do you want to cover — just yourself, spouse, kids, or parents?"User: "self + spouse, kids later"Bot: "Roughly what's your annual income — under 5 lakh, 5-10, 10-25, or 25+ lakh?"User: "around 18 lakhs"... [continues through the core 6] ...Bot: "Here's what I've understood: 32 years old; covering self+spouse; income 10L-25L;no existing cover; goal: first health policy; in a metro; budget 15K-30K.Did I get that right?"User: "yes"Bot: "Based on that, three policies stand out: [...] — let me explain why."```## 7. v2 enhancements| # | Enhancement | Why || --- | --- | --- || 1 | LLM-parser for free-form answers ("I'm in my early 30s with 2 kids") | Handles natural-language replies instead of rigid bucket-matching || 2 | Re-ask on `None` parse | Robust to user confusion || 3 | Skip-confirm flow ("you can skip this — say 'skip'") | Buyer autonomy || 4 | Save profile across sessions | Returning user picks up where they left off || 5 | Tone-match the user's energy (formal vs casual) | Conversation feels human |1234567891011121314151617181920212223242526272829303149 unmodified lines81828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166# 05 — Needs Analysis Flow (LLM-driven sales brain)| Field | Value || --- | --- || Project | Insurance Sales Portfolio Expert || Version | 0.2 || Date | 2026-05-15 || Implementation | `backend/sales_brain.py` (KI-167) — the schema source still lives in `backend/needs_finder.py::GRAPH` |## 0. Why one LLM call per turn (not "scripted question graph + paraphraser")A good Independent Financial Advisor opens with a stable, repeatable set of slots to fill — and adapts which slot to drive next based on what the buyer just said, what they've already told us, and what's still missing. We replicate this with **one LLM call per turn** that owns the entire fact-find surface (voice, cadence, slot-selection, multi-fact capture in a single turn), not a hardcoded state machine with a paraphraser glued on top.The original v0.1 of this doc was an explicit `GRAPH` of canonical questions with `prompt_en` / `prompt_hi` strings. That design shipped with ADR-027 (LLM paraphraser on top of the graph) and ADR-030 (one-call brain with `<FF>` trailer + canonical fallback). Both architectures hit a hard wall: scripted prompts leaked into every fallback turn ("Got that — {slot}.") and produced robotic cadence even when the brain succeeded. KI-167 / [ADR-039](../60-decisions/ADR-039-llm-driven-sales-brain.md) ripped it all out: no canonical_fallback, no scripted prompts, no `<FF>` trailer. Native provider JSON mode (`response_mime_type=application/json` on Gemini, `response_format={"type":"json_object"}` on NIM) provides server-side parseable output.What we kept and what we changed:| Concern | v0.1 (scripted graph) | Current (LLM-driven sales_brain) ||---|---|---|| **Slot schema** | `GRAPH` of 9 `Question(id, prompt_en, prompt_hi, field, is_core, condition, parser)` entries | `GRAPH` data structure retained as the schema source; `prompt_en` / `prompt_hi` are dead strings now || **Question text** | Hardcoded `prompt_en` rendered to user | LLM generates natural prose in the advisor's voice per turn (no template) || **Slot selection** | `next_question(profile)` walked the graph in order | LLM picks `slot_driving` in its JSON response (constrained by the schema to required slots first) || **Multi-fact capture** | One slot per turn (a user saying "I'm 32, just myself, in Mumbai" only filled `age`) | LLM emits a `captures` map per turn — one utterance can fill 2-4 slots || **Auditable behavior** | Graph order was the trace | Per-turn LLM response is logged (intent, brain_used, captures, slot_driving, complete) in `40-data/llm_usage.jsonl` + `logs/turns.jsonl` || **Fail-soft** | Graph survived LLM degradation | Outer 25s `asyncio.wait_for` on the brain call; on total NIM + Google exhaustion the orchestrator returns the [ADR-038](../60-decisions/ADR-038-nim-only-chains.md) graceful error message to the user — no scripted reply || **Bilingual** | Hand-authored `prompt_en` + `prompt_hi` | Sarvam-M translation cascade on the LLM's output (English authoring + Indic translation), same UX, fewer hand-authored strings |## 1. The 9-slot schema (data-only — the LLM consults this through its system prompt)```┌─────────────────────────────┐49 unmodified lines## 2. Termination criteriaThe LLM sets `complete: true` in its JSON response when all required slots are filled. `backend/sales_brain_normalizer.py` double-checks: if `complete == true` while any required slot is empty, the normalizer overrides to `complete = false` — the LLM cannot prematurely declare fact-find done.Or when the user opts out — if the user immediately asks "compare Star and HDFC ERGO" or "show me the top 3 policies for me" (KI-105 closer phrases), the intent classifier forces intent to `comparison` / `recommendation` BEFORE the fact-find branch is even reached, and the orchestrator routes straight to retrieval + Brain Main.## 3. Bilingual handlingThe LLM authors in English; Sarvam-M translates Hinglish ↔ English at the cascade boundary. The "Indic-native, not translated" principle (problem-statement §5.3) is preserved by the LLM's native-quality output rather than by hand-authored Hindi strings — the cascade itself is the bilingual surface.## 4. Parsing user answersThe LLM produces a `captures` map per turn (e.g. `{"age": 34, "dependents": "self", "location_tier": "metro"}`). `backend/sales_brain_normalizer.py` is a pure-function post-processor that:- Resolves field-name aliases (`location` → `location_tier`)- Coerces enums (`Bangalore` → `metro`)- Parses INR amounts (`"32 lakh"` → `3200000`)- Drops null / empty values (KI-094 None-guard — a `None` capture never overwrites a filled field)- Validates types and bounds (rejects `age: 250`)No LLM calls in the normalizer — pure rules. The orchestrator applies the normalized map via `session.update_profile_field()` exactly as before. Profile persistence remains unchanged (`backend/profile_store.save_profile()` + `backend/profile_rag.upsert_profile_chunk()` with session-scoped metadata per KI-102).## 5. How the orchestrator uses this```pythonprofile = Profile.from_session(session_id)if intent == "fact_find":# KI-167: one LLM call per turn against FAST_BRAIN_CHAINoutcome = await sales_brain.drive_sales_turn(profile=profile,history=session.chat_history[-N:],user_text=user_text,)# outcome.reply, outcome.captures, outcome.slot_driving, outcome.completeapply_normalized_captures(session, outcome.captures)if outcome.complete:session.free_form_session = Truereply = outcome.replyelse:# QA / comparison / recommendation → Brain Mainchunks = retrieve(user_query, top_k=10)reply = await BRAIN_CHAIN.chat(persona_prompt + history + chunks + user_text)if intent not in {"fact_find", "recommendation"}:# KI-171: judge skipped on fact-find + recommendation intentsverdict = await faithfulness.check(reply, chunks)if not verdict.supported:reply = SAFE_REFUSAL```## 6. What the user seesA natural conversation, not a script. Example (real session, 2026-05-15):```Bot: "Hi! I'm your insurance advisor. To get you the right shortlist I'll needto learn a bit about you and your situation. What's your name and a roughsense of who we're looking to protect?"User: "Hi, I'm Rohit Sar. I'm 32, just myself, living in Mumbai."Bot: "Nice to meet you, Rohit. Got it — 32, covering yourself, Mumbai-based.Two more quick things and we can look at policies: roughly what's yourannual income, and have you had any health conditions diagnosed —diabetes, BP, anything chronic?"User: "around 18 lakhs, no conditions"Bot: "Perfect. And what's drawing you to insurance right now — first policy,top-up on employer cover, or something specific?"User: "first policy, employer cover feels too thin"Bot: "Makes sense. Last one: comfortable annual premium range — under 15K,15-30K, 30-60K, or higher?"User: "15-30 is fine"Bot: "Great — that's everything I need. Based on your profile, three policiesstand out: [...]"```Note: the LLM captured `{name, age, dependents, location_tier}` in a single turn from the user's opener. Pre-KI-167 each fact required its own turn. The exact turn count varies — some sessions finish in 3-4 turns, others in 6-7 depending on what the user volunteers.## 7. v2 enhancements| # | Enhancement | Why || --- | --- | --- || 1 | Stream the prose token-by-token to the frontend | The JSON tail is parsed server-side after stream completion — would cut perceived latency below the canonical-fallback path || 2 | Promote the same single-call pattern to the QA path | Orchestrator's QA + fact-find branches collapse into one brain call with a richer schema (intent in the JSON block instead of out-of-band classification) || 3 | Skip-confirm flow ("you can skip this — say 'skip'") | Buyer autonomy || 4 | Save profile across sessions ✅ shipped KI-040 | Returning user picks up where they left off || 5 | Tone-match the user's energy (formal vs casual) | The LLM already does this implicitly via the system prompt; could be explicit per-session signal |
31 unmodified lines3233343536373817 unmodified lines56575859606162636411 unmodified lines7677787980818217 unmodified lines10010110210310410531 unmodified lines### Pipeline B — LLM-drafted nuanced questions (curated)For top-priority policies (top 10–20), run an LLM (Sarvam-M, with DeepSeek-V3 fallback) on the policy text with prompt: *"generate 5 buyer-style questions whose answers are explicitly in this document; include the source clause."* Each generated pair is **human spot-checked** before commit.Target: 5 × 20 = 100 questions covering multi-clause and edge-case reasoning that Pipeline A can't generate.17 unmodified linesNumbers, dates, currency, durations, percentages are extracted via regex from both gold and bot reply. Exact match (after normalization) is the strongest signal. Catches "the premium is ₹15,000" hallucinations without an LLM.### Signal 2 — LLM-judge faithfulness (Groq Llama-3.3-70B)Different model family from Sarvam-M (the brain) → **non-circular evaluation**. Judge prompt:> Given GOLD and BOT answers, output strict JSON: `{factual_match: bool, citation_present: bool, score: 0-1, reason: str}`. Be strict on partial matches.11 unmodified lines| Citation accuracy | C3 ≥ 95% | n_correct_citations / n_non_refusal || Refusal precision | C4 ≥ 90% | n_correct_refusals / n_expected_refusals || Hindi parity | C8 within 5pp | factual_acc(hi) vs factual_acc(en) || Brain winners | (router config) | factual_acc grouped by brain_used |## 4. Output artifacts per run17 unmodified lines## 7. Known limitations (transparent)- **Sample bias:** Pipeline A questions are templated, so accuracy on Pipeline A is upper-bound real-world performance. Pipeline B + C provide the harder signal.- **Single judge model:** Groq Llama is one judge. Risk of judge-specific bias. v2: 3-judge consensus.- **No human evaluation:** Cost-prohibitive for 1,100 questions. We rely on the grader; manual spot-check 5%.- **No latency budget enforcement in eval:** Latency is captured per record but doesn't gate the score. Doc 01 C1 (p50 ≤ 4s) is monitored separately.31 unmodified lines3233343536373817 unmodified lines56575859606162636411 unmodified lines7677787980818217 unmodified lines10010110210310410531 unmodified lines### Pipeline B — LLM-drafted nuanced questions (curated)For top-priority policies (top 10–20), run `NimChainLLM(BRAIN_CHAIN)` on the policy text with prompt: *"generate 5 buyer-style questions whose answers are explicitly in this document; include the source clause."* Each generated pair is **human spot-checked** before commit.Target: 5 × 20 = 100 questions covering multi-clause and edge-case reasoning that Pipeline A can't generate.17 unmodified linesNumbers, dates, currency, durations, percentages are extracted via regex from both gold and bot reply. Exact match (after normalization) is the strongest signal. Catches "the premium is ₹15,000" hallucinations without an LLM.### Signal 2 — LLM-judge faithfulness (JUDGE_CHAIN: NIM Mistral Large 3 675B primary)Different model family from the Gemini-led Brain Fast / Brain Main → **non-circular evaluation**. Falls through NIM Llama-4 Maverick → OR Qwen 80B `:free` → NIM Nemotron 49B as last resort. Judge prompt:> Given GOLD and BOT answers, output strict JSON: `{factual_match: bool, citation_present: bool, score: 0-1, reason: str}`. Be strict on partial matches.11 unmodified lines| Citation accuracy | C3 ≥ 95% | n_correct_citations / n_non_refusal || Refusal precision | C4 ≥ 90% | n_correct_refusals / n_expected_refusals || Hindi parity | C8 within 5pp | factual_acc(hi) vs factual_acc(en) || Brain winners | (router config) | factual_acc grouped by `brain_used` — emitted values include `sales_brain::continue`, `sales_brain::complete`, `brain_main::<elected_model>`, `brain_main::graceful_error` |## 4. Output artifacts per run17 unmodified lines## 7. Known limitations (transparent)- **Sample bias:** Pipeline A questions are templated, so accuracy on Pipeline A is upper-bound real-world performance. Pipeline B + C provide the harder signal.- **Single judge model:** NIM Mistral Large 3 675B is the elected judge primary; the fallback ladder includes Llama-4 Maverick + OR Qwen 80B + NIM Nemotron 49B for resilience but every grade run uses a single judge per question. Risk of judge-specific bias. v2: 3-judge consensus.- **No human evaluation:** Cost-prohibitive for 1,100 questions. We rely on the grader; manual spot-check 5%.- **No latency budget enforcement in eval:** Latency is captured per record but doesn't gate the score. Doc 01 C1 (p50 ≤ 4s) is monitored separately.
375 unmodified lines376377378379380381375 unmodified lines**Recommendation:** (A) — once activated, the marketplace tab getsproper SQL filtering that's faster than the current N-JSON-load pattern.### KI-019 — `kb/policies/*.md` not embedded (224 human-readable summaries left out of retrieval)**Severity:** P3375 unmodified lines376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433375 unmodified lines**Recommendation:** (A) — once activated, the marketplace tab getsproper SQL filtering that's faster than the current N-JSON-load pattern.### KI-167 — Scripted `<FF>` trailer + canonical_fallback removed in favour of LLM-driven `sales_brain` — **FIXED** (ADR-039)**Severity:** P0**Source:** `backend/fact_find_brain.py` + `_canonical_fallback` + `_pick_opener` family in `backend/orchestrator.py`**Discovered:** 2026-05-15 — user report *"zero natural LLM chat — it always defaults to the script."*Pre-fix, every fact-find turn ran through ADR-030's one-call brain with a `<FF>...</FF>` trailer convention; on parse failure or contract violation the orchestrator fell to `_canonical_fallback`, which emitted the scripted `Question.prompt_en` of the next unfilled slot prefixed with `"Got that — {slot}."`. Real LLMs (Qwen, Nemotron, Mistral) under load regularly dropped the trailer tags (KI-090 lenient parser bought partial recovery; KI-155 / KI-156 / KI-158 / KI-161 showed it was structural) and silently violated the contract, so the scripted prefix became the dominant user-facing path.**Fix:** Ripped out `backend/fact_find_brain.py` (441 LOC) + `_canonical_fallback` + `_pick_opener` + `_NEUTRAL_OPENERS` + `_FAMILY_OPENERS` + `_contains_self_introduction`. Replaced with `backend/sales_brain.py` — one LLM call per turn against `FAST_BRAIN_CHAIN` using native provider JSON mode (`response_mime_type=application/json` on Gemini, `response_format={"type":"json_object"}` on NIM). New deterministic post-processor `backend/sales_brain_normalizer.py` validates and normalises the captured fields. KI-091 / KI-094 None-guards retained. See [ADR-039](../60-decisions/ADR-039-llm-driven-sales-brain.md).---### KI-168 — Hybrid voice capture (Web Speech + MediaRecorder + Sarvam) — **FIXED****Severity:** P1**Source:** `frontend/src/lib/useStreamingVoice.ts`**Discovered:** 2026-05-15Pre-fix voice UX waited for the full Sarvam STT round-trip before showing the user their transcribed text — felt sluggish on the chat surface. New hybrid: Web Speech API streams interim transcripts into the chat input live, while `MediaRecorder` captures the authoritative audio blob in parallel; on browser silence-detect the blob is POSTed to `/api/transcribe` (Sarvam Saarika STT) for the authoritative transcript. Auto-submit falls back to the Web Speech transcript only if Sarvam errors. KI-173 heartbeat + KI-174 `visibilitychange` / `focus` revival hooks keep the mic alive across tab and app switches.---### KI-171 — Skip faithfulness judge on `fact_find` + `recommendation` intents — **FIXED****Severity:** P1**Source:** `backend/orchestrator.py`**Discovered:** 2026-05-15Faithfulness Gate 4 (LLM judge) was being run on every turn including fact-find and recommendation, where there's no retrieved-chunks context to grade the reply against — burning judge calls and occasionally blocking valid replies. Now gated behind `intent ∈ {qa, comparison}` only. Recommendation replies still go through Gates 1-3 (retrieval floor, citation integrity, regex numeric grounding).---### KI-175 / KI-176 — NIM chain reorder + OpenRouter re-added as cross-provider diversity — **FIXED****Severity:** P2**Source:** Chain definitions in `backend/providers/nvidia_nim_llm.py`**Discovered:** 2026-05-15KI-175 demoted NIM Nemotron 49B from primary to last resort across all three chains — Mistral Large 3 675B and Qwen 80B consistently outperform on the live audit. KI-176 re-added OpenRouter as a cross-provider diversity tier using OR's `models: [...]` array param for server-side fallback within the OR free pool. The NIM-only lock from [ADR-038](../60-decisions/ADR-038-nim-only-chains.md) was relaxed in scope (the `<FF>` trailer convention that motivated it no longer exists post-KI-167); only OR `:free` candidates with verified native JSON mode are included (Nemotron-3-Super 120B, Qwen 80B `:free`).---### KI-178 / KI-179 — Google Gemini Flash added as Tier 0 primary — **FIXED** (ADR-040)**Severity:** P2**Source:** `backend/providers/google_gemini_llm.py` (new); chain definitions in `nvidia_nim_llm.py`**Discovered:** 2026-05-15Operator obtained a Google AI Studio API key. KI-178 audited which OpenRouter free-tier models support `response_format` (only Nemotron-3-Super 120B + Qwen 80B + Gemma-4 31B). KI-179 added a new `LLMProvider` against Google AI Studio's REST API (`gemini-2.0-flash` + `gemini-2.5-flash`, native JSON mode via `response_mime_type=application/json`, 1500 req/day free quota). Promoted to Tier 0 primary on Brain Fast (Gemini 2.0 Flash) + Brain Main (Gemini 2.5 Flash). NIM stays as Tier 1 fallback with Mistral 675B as the strongest non-Gemini candidate; OpenRouter sits as Tier 2 diversity. Judge stays on NIM Mistral 675B (different family from Gemini — preserves brain ↔ judge family-diversity invariant). See [ADR-040](../60-decisions/ADR-040-google-gemini-primary.md).---### KI-019 — `kb/policies/*.md` not embedded (224 human-readable summaries left out of retrieval)**Severity:** P3
84 unmodified lines85868784 unmodified linesEvery commit pushed to BOTH `origin` (HF Space) and `github` per thetriple-mirror contract in [ADR-024](../60-decisions/ADR-024-triple-mirror-code-and-data.md).84 unmodified lines85868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812984 unmodified linesEvery commit pushed to BOTH `origin` (HF Space) and `github` per thetriple-mirror contract in [ADR-024](../60-decisions/ADR-024-triple-mirror-code-and-data.md).---## Follow-on sprint — 2026-05-15 (KI-167 → KI-179)A second-day sprint after live testing flagged that the scripted `<FF>` trailer convention was leaking into every fallback turn ("zero natural LLM chat — it always defaults to the script"). The day produced one ADR (ADR-039), one provider integration (Google AI Studio), and a chain-level rewrite (ADR-040).### Findings & fixes by source| KI | Severity | Issue | Resolution ||---|---|---|---|| KI-167 | P0 | `<FF>` trailer + `_canonical_fallback` dominated user-visible turns when LLM contract violations occurred; bot felt robotic | Ripped out `fact_find_brain.py` + canonical_fallback + scripted prompts; new `backend/sales_brain.py` with one LLM call/turn using native provider JSON mode. ADR-039. || KI-168 | P1 | Voice UX waited for full Sarvam STT round-trip before showing transcript | Hybrid Web Speech (interim) + MediaRecorder (authoritative blob → Sarvam STT on silence-detect). || KI-171 | P1 | Faithfulness judge ran on `fact_find` + `recommendation` turns where there's no retrieval context | Skip Gate 4 on those intents; Gates 1-3 still run. || KI-173 | P2 | Mic died when user switched tabs / minimised the app | Heartbeat keeps mic stream alive. || KI-174 | P2 | Mic state did not recover on `visibilitychange` / `focus` | Revival hooks reattach the mic on tab return. || KI-175 | P2 | NIM Nemotron 49B was a chain primary but consistently underperformed Mistral 675B / Qwen 80B | Demoted Nemotron 49B to last resort across all chains. || KI-176 | P2 | OpenRouter dropped from chains in ADR-038 was no longer needed after ADR-039 retired `<FF>` | Re-added OR `:free` candidates with verified JSON mode as cross-provider diversity. || KI-178 | P2 | Audit of which OR `:free` models support `response_format` | Llama 3.3 70B / Hermes 3 405B excluded (no native JSON mode); Nemotron-3-Super 120B + Qwen 80B `:free` + Gemma-4 31B included. || KI-179 | P2 | Google AI Studio key obtained; need to wire it into chains | New `backend/providers/google_gemini_llm.py`; Gemini 2.0 Flash → Brain Fast primary, Gemini 2.5 Flash → Brain Main primary. ADR-040. |### What changed in the architecture- **Brain Fast (sales_brain):** Gemini 2.0 Flash → NIM Qwen 80B → NIM Mistral Large 3 675B → NIM Llama-4 Maverick → OR Nemotron-3-Super 120B → OR Qwen 80B `:free` → NIM Nemotron 49B (last resort).- **Brain Main:** Gemini 2.5 Flash → NIM Mistral Large 3 675B → NIM Llama-4 Maverick → NIM Qwen 80B → OR Nemotron-3-Super → NIM Nemotron 49B (last resort).- **Judge:** NIM Mistral Large 3 675B → NIM Llama-4 Maverick → OR Qwen 80B `:free` → NIM Nemotron 49B (last resort).### What was deleted- `backend/fact_find_brain.py` (441 LOC).- `_canonical_fallback`, `_normalize_for_slot`, `_pick_opener`, `_NEUTRAL_OPENERS`, `_FAMILY_OPENERS`, `_contains_self_introduction` in `backend/orchestrator.py`.- The `<FF>{...}</FF>` trailer convention + lenient parser ladder + `:no_trailer` / `:empty_reply` / `:llm_error` telemetry variants from `TurnResult.brain_used`.- Dead `prompt_en` / `prompt_hi` strings in `backend/needs_finder.py::GRAPH` are no longer rendered (data structure retained for the LLM's system-prompt schema).### What stayed- KI-080 sticky-primary election machinery (now scores Google / NIM / OpenRouter candidates uniformly).- KI-084 per-phase httpx timeouts.- KI-085 proactive credit gating (extended to Google quota).- KI-091 / KI-094 None-guards on the profile extractor (still relevant for QA-mode turns).- KI-102 / KI-107 session-isolated profile RAG.- KI-106 graceful `TimeoutError` + `Exception` handling on `/api/chat`.
12345678# ADR-014: Groq Llama-3.3-70B as eval grader**Status:** Superseded by [ADR-019](ADR-019-nim-single-provider-consolidation.md)**Date:** 2026-05-13## ContextThe eval harness needed a grading LLM that was NOT the same family as the brain LLM (to avoid circular evaluation). Available options:123456789101112# ADR-014: Groq Llama-3.3-70B as eval grader**Status:** Superseded by [ADR-040](ADR-040-google-gemini-primary.md) (2026-05-15) — Groq is no longer in any chain. The judge primary is NIM Mistral Large 3 675B (different family from the Gemini brain — preserves the non-circular cross-family principle this ADR introduced). Originally superseded by [ADR-019](ADR-019-nim-single-provider-consolidation.md).**Date:** 2026-05-13## Why supersession (current)Groq was removed from all chains in [ADR-038](ADR-038-nim-only-chains.md) (KI-160) after KI-155 demonstrated Groq Llama-3.3-70B silently ignores structured-output contracts. The brain ↔ judge family-diversity principle this ADR introduced is now expressed differently — the brain is Gemini (Google family), the judge is Mistral (Mistral family) — but the architectural intent (judge does not mark its own homework) is unchanged.## ContextThe eval harness needed a grading LLM that was NOT the same family as the brain LLM (to avoid circular evaluation). Available options:
12345678# ADR-016: Hybrid brain router (Sarvam primary + Llama / DeepSeek fallback)**Status:** Superseded by [ADR-019](ADR-019-nim-single-provider-consolidation.md)**Date:** 2026-05-13## ContextA single brain LLM was insufficient: Sarvam-M's 2048 output cap + `<think>` tokens caused mid-JSON truncation in extraction and mid-answer truncation in advisory. But Sarvam-first is non-negotiable narrative for the assignment.123456789101112# ADR-016: Hybrid brain router (Sarvam primary + Llama / DeepSeek fallback)**Status:** Superseded by [ADR-040](ADR-040-google-gemini-primary.md) (2026-05-15) — the cross-provider router intent survives, but the candidate pool now leads with Google AI Studio (Gemini 2.0 / 2.5 Flash) on Brain Fast / Brain Main with NIM Mistral / Maverick / Qwen and OpenRouter `:free` as cross-provider diversity. Originally superseded by [ADR-019](ADR-019-nim-single-provider-consolidation.md).**Date:** 2026-05-13## Why supersededThe original Sarvam-primary + Llama/DeepSeek-fallback router was retired in two steps. ADR-019 first collapsed cross-provider sprawl onto a single NIM key. ADR-040 then re-opened the cross-provider surface — but on a different basis: native JSON-mode contract validation (`response_mime_type=application/json` / `response_format={"type":"json_object"}`) replaces empirical query-class routing as the candidate-selection rule. The current chain is Google → NIM → OpenRouter, scored by KI-080 probe-driven election rather than a static "Indic → Sarvam, comparison → DeepSeek" heuristic.## ContextA single brain LLM was insufficient: Sarvam-M's 2048 output cap + `<think>` tokens caused mid-JSON truncation in extraction and mid-answer truncation in advisory. But Sarvam-first is non-negotiable narrative for the assignment.
123456# ADR-019: NVIDIA NIM as the single non-Sarvam provider**Status:** Locked**Date:** 2026-05-14**Partial supersession (D-022, 2026-05-14):** NIM's DeepSeek V4-Pro / V4-Flash and Llama-4 Maverick inference pools degraded with hours-long timeouts during a production incident. The chains were re-ordered to put **Qwen 3-Next 80B** (brain primary), **Nemotron Nano 30B** (fast brain primary), and **Mistral Large 3 675B** (judge primary) at the head, with DeepSeek + Maverick retained as fallback chain entries that re-enter rotation when those pools recover. The single-provider consolidation decision in this ADR still stands (NIM remains the primary inference provider); only the *specific model picks* were swapped. See `backend/providers/nvidia_nim_llm.py` for the current chain definitions.123456# ADR-019: NVIDIA NIM as the single non-Sarvam provider**Status:** Superseded by [ADR-040](ADR-040-google-gemini-primary.md) (2026-05-15) — the single-provider stance is retired. Google AI Studio (Gemini 2.0 / 2.5 Flash, 1500 req/day free, native JSON mode) is now Tier 0 primary on Brain Fast + Brain Main; NIM stays as Tier 1 fallback (Mistral Large 3 675B + Llama-4 Maverick + Qwen 80B) and is still the judge primary (cross-family from Gemini). OpenRouter `:free` is Tier 2 diversity. ADR-019's "cross-family judge" + "single-key per provider" + "$0 free-tier" principles are preserved across the multi-provider stack.**Date:** 2026-05-14**Partial supersession (D-022, 2026-05-14):** NIM's DeepSeek V4-Pro / V4-Flash and Llama-4 Maverick inference pools degraded with hours-long timeouts during a production incident. The chains were re-ordered to put **Qwen 3-Next 80B** (brain primary), **Nemotron Nano 30B** (fast brain primary), and **Mistral Large 3 675B** (judge primary) at the head, with DeepSeek + Maverick retained as fallback chain entries that re-enter rotation when those pools recover. The single-provider consolidation decision in this ADR still stands (NIM remains the primary inference provider); only the *specific model picks* were swapped. See `backend/providers/nvidia_nim_llm.py` for the current chain definitions.
12345678# ADR-026 — Brain provider load-balancing (NIM ↔ Groq, 50/50)**Status:** Accepted — 2026-05-14**Owner:** Rohit Saraf**Supersedes:** Partial override of [ADR-019](ADR-019-nim-single-provider-consolidation.md)'s single-provider stance## Context123456789# ADR-026 — Brain provider load-balancing (NIM ↔ Groq, 50/50)**Status:** Superseded by [ADR-040](ADR-040-google-gemini-primary.md) (2026-05-15) — the 50/50 random-coin load balance was first deprecated by [ADR-031](ADR-031-sticky-primary-election.md)'s probe-driven sticky-primary election (KI-080) and is now fully retired. The current chain shape (Google AI Studio Tier 0 primary → NIM Tier 1 fallback → OpenRouter `:free` Tier 2 diversity) is decided by per-call election against probe scores rather than a static probability split.**Date:** 2026-05-14**Owner:** Rohit Saraf**Originally supersedes:** Partial override of [ADR-019](ADR-019-nim-single-provider-consolidation.md)'s single-provider stance## Context
123456789# ADR-030 — LLM-driven fact-find (single brain call per turn)**Status:** Accepted — 2026-05-15**Owner:** Rohit Saraf**Supersedes:** [ADR-027](ADR-027-fact-find-llm-paraphraser.md) (the LLM paraphraser was a band-aid on the hardcoded-graph stitching; this is the full replacement.)**Related:** [ADR-022](ADR-022-conversational-profile-updates.md) (free-form profile updates — the answer-side LLM that this ADR generalizes into the whole loop)## Context1234567891011121314# ADR-030 — LLM-driven fact-find (single brain call per turn)**Status:** Superseded by [ADR-039](ADR-039-llm-driven-sales-brain.md) (2026-05-15, KI-167) — partially superseded by [ADR-040](ADR-040-google-gemini-primary.md) (chain candidates). The "schema-aware single LLM call per turn" intuition is preserved in `backend/sales_brain.py`; the `<FF>...</FF>` trailer convention, the `_canonical_fallback` greedy slot-walker, and the scripted `Question.prompt_en` prefix are all retired in favour of native provider JSON mode (`response_mime_type=application/json` / `response_format={"type":"json_object"}`).**Date:** 2026-05-15**Owner:** Rohit Saraf**Originally supersedes:** [ADR-027](ADR-027-fact-find-llm-paraphraser.md) (the LLM paraphraser was a band-aid on the hardcoded-graph stitching; this was the full replacement.)**Related:** [ADR-022](ADR-022-conversational-profile-updates.md) (free-form profile updates — the answer-side LLM that this ADR generalized into the whole loop)## Why supersededThe `<FF>{...}</FF>` trailer convention proved structurally fragile under load — see KI-155 / KI-156 / KI-158 / KI-161. Even with the KI-090 lenient parser ladder, real LLMs (Qwen, Nemotron, Mistral) regularly returned grammatically fine prose with no parseable trailer, causing `_canonical_fallback` to fire and the user to see the scripted `Question.prompt_en` of the next unfilled slot. The scripted prefix became the dominant user-facing path even when the LLM call had "succeeded." ADR-039 retires the trailer convention entirely in favour of native provider JSON mode; ADR-040 expanded the candidate pool to Google AI Studio + NIM + OpenRouter, all of which natively support server-enforced JSON mode.## Context
123456# ADR-031 — Sticky primary election for LLM chains**Status:** Superseded by [ADR-038](ADR-038-nim-only-chains.md) — 2026-05-15 (KI-160). Cross-provider election candidates (Groq, OpenRouter) removed from all three chains after KI-155 demonstrated Groq Llama-3.3 silently ignores the `<FF>` trailer contract. Sticky-primary election mechanics still apply, but only within the NIM candidate pool. Body retained below for history.**Status (original):** Accepted — 2026-05-15**Owner:** Rohit Saraf12345678910# ADR-031 — Sticky primary election for LLM chains**Status:** Superseded by [ADR-040](ADR-040-google-gemini-primary.md) — 2026-05-15 (KI-179) on the candidate-pool scope. The sticky-primary election machinery (per-chain probe + scored election + provider-diverse BACKUP) is preserved and now scores Google AI Studio / NIM / OpenRouter candidates uniformly. Previously superseded by [ADR-038](ADR-038-nim-only-chains.md) (KI-160) on the same scope. Body retained below for history.## Why supersededADR-038 had locked the candidate pool to NIM-only after KI-155 showed cross-provider candidates silently violated the `<FF>` trailer contract. ADR-039 / KI-167 retired the `<FF>` trailer entirely in favour of native provider JSON mode, which removes the structural reason for the lock. ADR-040 then added Google AI Studio (Gemini 2.0 / 2.5 Flash) as Tier 0 primary on Brain Fast / Brain Main with NIM as Tier 1 fallback and OpenRouter `:free` as Tier 2 diversity. The election scoring (latency × success_rate) and the provider-diverse BACKUP rule are unchanged.**Status (original):** Accepted — 2026-05-15**Owner:** Rohit Saraf
123456789101112# ADR-032 — LLM Chain Architecture Reference**Status:** Superseded by [ADR-038](ADR-038-nim-only-chains.md) — 2026-05-15 (KI-160). All three chains locked to NIM candidates only after KI-155. Current candidate lists:- **BRAIN:** `nvidia/llama-3.3-nemotron-super-49b-v1.5` (primary), `qwen/qwen3-next-80b-a3b-instruct` (backup), `mistralai/mistral-large-3-675b-instruct-2512` (3rd)- **FAST_BRAIN:** `qwen/qwen3-next-80b-a3b-instruct` (primary), `nvidia/llama-3.3-nemotron-super-49b-v1.5` (backup)- **JUDGE:** `meta/llama-4-maverick-17b-128e-instruct` (primary), `mistralai/mistral-large-3-675b-instruct-2512` (backup)Body below retained as architectural reference for probe / election / timeout machinery — all still in effect within the NIM-only scope.**Status (original):** Accepted — 2026-05-15**Type:** Architecture reference (not a decision ADR)123456789101112# ADR-032 — LLM Chain Architecture Reference**Status:** Superseded by [ADR-040](ADR-040-google-gemini-primary.md) — 2026-05-15 (KI-179) on the candidate-pool scope. The NIM-only lock from ADR-038 was relaxed once ADR-039 / KI-167 retired the `<FF>` trailer convention. Current candidate lists per ADR-040:- **BRAIN (Fast — sales_brain):** Gemini 2.0 Flash (Google AI Studio Tier 0 primary), then NIM `qwen/qwen3-next-80b-a3b-instruct` → NIM `mistralai/mistral-large-3-675b-instruct-2512` → NIM `meta/llama-4-maverick-17b-128e-instruct` → OpenRouter `nvidia/nemotron-3-super-120b-a12b:free` → OpenRouter `qwen/qwen3-next-80b-a3b-instruct:free` → NIM `nvidia/llama-3.3-nemotron-super-49b-v1.5` (last resort).- **BRAIN (Main — synthesis / QA / comparison / recommendation):** Gemini 2.5 Flash (Tier 0 primary), then NIM Mistral 675B → NIM Maverick → NIM Qwen 80B → OpenRouter Nemotron-3-Super → NIM Nemotron 49B (last resort).- **JUDGE:** NIM `mistralai/mistral-large-3-675b-instruct-2512` (primary), NIM Maverick (backup), OpenRouter Qwen 80B `:free`, NIM Nemotron 49B (last resort).Body below retained as architectural reference for probe / election / timeout / credit-gating machinery — all still in effect across the multi-provider pool. Section 4 "Election algorithm" treats Google / NIM / OpenRouter candidates uniformly via `provider_of()` for the cross-provider BACKUP rule.**Status (original):** Accepted — 2026-05-15**Type:** Architecture reference (not a decision ADR)
123456# ADR-038 — NIM-only chains (KI-160)**Status:** Accepted — 2026-05-15**Owner:** Rohit Saraf**Supersedes:** [ADR-031](ADR-031-sticky-primary-election.md) (cross-provider election scope), [ADR-032](ADR-032-llm-chain-architecture.md) (candidate-pool scope)**Related KIs:** KI-155 (Groq `<FF>` contract violation, root cause), KI-160 (this lock-down), KI-080 / KI-081 / KI-084 / KI-085 / KI-087 (probe + election mechanics, retained within NIM scope)12345678# ADR-038 — NIM-only chains (KI-160)**Status:** Superseded by [ADR-040](ADR-040-google-gemini-primary.md) (2026-05-15). The NIM-only lock was relaxed once KI-167 ([ADR-039](ADR-039-llm-driven-sales-brain.md))'s sales_brain eliminated the `<FF>` trailer convention that originally motivated the lock. Native provider JSON mode (`response_format={"type":"json_object"}` on NIM, `response_mime_type=application/json` on Gemini) is now the structured-output contract, so cross-provider candidates that natively support JSON mode are safe to re-add to the election pool. The "fail-loud > fail-silent-with-garbage" principle and brain ↔ judge family-diversity invariant from this ADR are preserved in ADR-040.**Original status:** Accepted — 2026-05-15**Owner:** Rohit Saraf**Supersedes:** [ADR-031](ADR-031-sticky-primary-election.md) (cross-provider election scope), [ADR-032](ADR-032-llm-chain-architecture.md) (candidate-pool scope)**Related KIs:** KI-155 (Groq `<FF>` contract violation, root cause), KI-160 (this lock-down), KI-080 / KI-081 / KI-084 / KI-085 / KI-087 (probe + election mechanics, retained within NIM scope)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990# ADR-040 — Google Gemini Flash as primary LLM tier (KI-179)
**Status:** Accepted — 2026-05-15**Owner:** Rohit Saraf**Supersedes:** [ADR-038](ADR-038-nim-only-chains.md) (NIM-only chain lock) — partially. The "fail-loud > fail-silent-with-garbage" principle and the brain ↔ judge family-diversity invariant are preserved; the strict NIM-only candidate-pool scope is relaxed now that the `<FF>` trailer convention that motivated the lock no longer exists post-[ADR-039](ADR-039-llm-driven-sales-brain.md) / KI-167.**Related KIs:** KI-167 (sales_brain rip-out), KI-171 (judge skip on fact_find + recommendation), KI-175 (NIM chain reorder — nemotron demoted to last), KI-176 (OpenRouter `models: [...]` server-side fallback), KI-178 (live audit of OR free-tier JSON-mode support), KI-179 (this decision — Google AI Studio added as Tier 0).
## Context
After KI-167 ([ADR-039](ADR-039-llm-driven-sales-brain.md)) eliminated the `<FF>...</FF>` trailer convention in favour of native provider JSON mode (`response_format={"type":"json_object"}` on NIM, `response_mime_type=application/json` on Gemini), the structural reason for the NIM-only lock dissolved. KI-176 added OpenRouter back as a cross-provider fallback using OR's `models: [...]` array param for server-side fallback within the OR free pool.
KI-178 then audited which OpenRouter free-tier models actually support `response_format`:
- **No Gemini variants exist on OR's free tier.**- **Llama 3.3 70B and Hermes 3 405B on OR free do not expose `response_format`** — JSON would have to be prompt-engineered, which carries a non-trivial parse-failure rate (the very class of silent failure KI-160 / ADR-038 was instituted to prevent).- **The only OR free-tier models with native JSON mode** are `nvidia/nemotron-3-super-120b-a12b:free`, `qwen/qwen3-next-80b-a3b-instruct:free`, and `google/gemma-4-31b:free`.
In parallel, the operator obtained a Google AI Studio API key. Google's documented free tier on Gemini 2.0 / 2.5 Flash is **1,500 requests/day, 15 requests/minute, native JSON mode via `response_mime_type=application/json`**, with conversational quality that is genuinely better than any model in the existing NIM pool for the sales-brain free-form QA + recommendation surfaces. The free quota is adequate for the demo + early-production workload (a typical fact-find conversation is ~10 turns; 1,500 req/day supports ~150 conversations/day before falling to fallbacks).
The chain shape needs to reflect this: a frontier-quality free tier exists, and routing past it would be deliberately ignoring a strictly-better primary.
## Decision
**Add Google AI Studio as Tier 0 (primary) on the Brain Fast and Brain Main chains.** NIM stays as Tier 1 fallback with its 675B Mistral Large 3 as the strongest non-Gemini candidate. OpenRouter ($10 stays parked) sits as Tier 2 diversity pool before the nemotron-49b last resort. The judge stays NIM-primary on Mistral Large 3 675B — different family from Gemini, preserving the brain ↔ judge family-diversity invariant.
Concretely, the three chains become:
### Brain Fast (fact-find conversation, `backend/sales_brain.py`)
1. **PRIMARY — Google AI Studio:** `gemini-2.0-flash` (1500 req/day free, native JSON mode)2. Fallback 1 — NIM: `qwen3-next-80b-a3b-instruct`3. Fallback 2 — NIM: `mistralai/mistral-large-3-675b-instruct-2512` (675B dense)4. Fallback 3 — NIM: `meta/llama-4-maverick-17b-128e-instruct` (128B MoE)5. Fallback 4 — OpenRouter: `nvidia/nemotron-3-super-120b-a12b:free`6. Fallback 5 — OpenRouter: `qwen/qwen3-next-80b-a3b-instruct:free`7. Last resort — NIM: `nvidia/llama-3.3-nemotron-super-49b-v1.5`
### Brain Main (orchestrator free-form QA + recommendation synthesis)
1. **PRIMARY — Google AI Studio:** `gemini-2.5-flash` (same 1500 req/day quota, higher synthesis quality than 2.0 Flash on long-context recommendation generation)2. Fallback 1 — NIM: `mistralai/mistral-large-3-675b-instruct-2512`3. Fallback 2 — NIM: `meta/llama-4-maverick-17b-128e-instruct`4. Fallback 3 — NIM: `qwen/qwen3-next-80b-a3b-instruct`5. Fallback 4 — OpenRouter: `nvidia/nemotron-3-super-120b-a12b:free`6. Last resort — NIM: `nvidia/llama-3.3-nemotron-super-49b-v1.5`
### Judge (faithfulness Gate 4 — KI-171 skips this on `fact_find` + `recommendation` queries)
1. **PRIMARY — NIM:** `mistralai/mistral-large-3-675b-instruct-2512` (different family from the Gemini brain; preserves cross-family invariant)2. Fallback 1 — NIM: `meta/llama-4-maverick-17b-128e-instruct`3. Fallback 2 — OpenRouter: `qwen/qwen3-next-80b-a3b-instruct:free`4. Last resort — NIM: `nvidia/llama-3.3-nemotron-super-49b-v1.5`
A new `backend/providers/google_gemini_llm.py` wrapper (KI-179) implements the `LLMProvider` interface against Google AI Studio's REST API, matching the same `chat()` signature as `NvidiaNimLLM` and `OpenRouterLLM`. `NimChainLLM` is provider-agnostic — chains may now mix Google / NIM / OpenRouter candidates by URL.
## Consequences
### Positive
- **Frontier-tier conversational quality on the free path.** Gemini 2.0 Flash + 2.5 Flash are genuinely best-in-class for the sales-brain surface (one-shot JSON-mode replies with tight schemas + natural prose) and the recommendation-synthesis surface (multi-policy comparison + ranked shortlist).- **Native JSON mode preserved.** `response_mime_type=application/json` is Google's server-enforced equivalent of NIM's `response_format={"type":"json_object"}` — the [ADR-039](ADR-039-llm-driven-sales-brain.md) structured-output guarantee survives the provider swap.- **NIM's massive Mistral Large 3 (675B dense) stays accessible as Fallback 1** on both Brain chains. The judge chain still leads with Mistral 675B, so the rescue-by-judge path remains identical.- **OpenRouter $10 diversity pool stays valuable.** The two OR `:free` candidates with verified JSON mode (nemotron-3-super-120b, qwen3-next-80b) cover a third-provider tier under both Google and NIM, so a simultaneous Google + NIM degradation has at least one diverse candidate to elect.- **Family diversity preserved at the judge boundary.** Brain primaries are Gemini (Google family); judge primary is Mistral Large 3 675B (Mistral family) — the brain ↔ judge family diversity that [ADR-014](ADR-014-groq-llama-grader.md) / [ADR-032](ADR-032-llm-chain-architecture.md) require is intact.
### Negative
- **One additional dependency** — Google AI Studio key (`GOOGLE_API_KEY`). The provider list grows from {NIM, OpenRouter, Sarvam} to {Google, NIM, OpenRouter, Sarvam}.- **Free-tier quota cap of 1500 req/day on Gemini Flash.** Adequate for demo + early production but not unbounded. A sustained 100+ concurrent-conversation load would exhaust the quota and force fallback to NIM Mistral 675B.
### Mitigations
- **6-level fallback chain on Brain Fast, 5-level on Brain Main.** A Google AI Studio outage / quota exhaustion / 429 simply falls to NIM Mistral 675B — the same provider family that has been production-validated since KI-160.- **Quota visibility.** Daily request counter is visible at [aistudio.google.com](https://aistudio.google.com); admin telemetry (KI-086 `/api/admin/llm-health`) surfaces per-candidate health + degraded-until timestamps, so quota-exhaustion is observable in the existing admin panel.- **Key rotation procedure exists.** Google AI Studio keys can be rotated in-console; the `GOOGLE_API_KEY` env in HF Space secrets is one-flip to swap.- **Probe loop (KI-080 + KI-088 NIM semaphore) extends naturally** to the Google provider — `backend/llm_health.py` scores every candidate uniformly on `(1 / max(50, latency_ms)) * success_rate`; the elector treats provider-of-origin as opaque.
## Alternatives considered
- **Ship Llama 3.3 70B / Hermes 3 405B from OpenRouter free tier as the new primary.** Rejected. KI-178 confirmed neither model exposes `response_format` on OR free — JSON would have to be prompt-engineered out of prose, reintroducing the class of silent failure that KI-160 / [ADR-038](ADR-038-nim-only-chains.md) was instituted to prevent. The point of native JSON mode is server-side enforcement; a model without it is structurally worse for our use case regardless of its parameter count.
- **Stay NIM-only (KI-175 state — nemotron demoted to last, Mistral 675B as new NIM primary).** Rejected. Live testing showed Gemini Flash conversational quality is genuinely better on the sales-brain surface (more natural opener variety, less repetition, fewer "Got that —" style filler patterns), and the 1500 req/day Google free tier is plentiful for the workload. Routing past a strictly-better free primary would be deliberately ignoring it.
- **Buy paid Gemini via OpenRouter's $10 balance.** Rejected. OR's paid Gemini is ~1000–2000 conversations before the $10 refill is needed; direct Google AI Studio is genuinely free at the same quality level. The OR $10 is better spent on the diversity-pool free models (nemotron-3-super-120b, qwen3-next-80b) that round out the fallback chain.
- **Make Gemini the judge too (same family across all roles).** Rejected. Brain ↔ judge family diversity ([ADR-014](ADR-014-groq-llama-grader.md) / [ADR-032](ADR-032-llm-chain-architecture.md)) is the structural defence against circular grading — the judge would mark its own homework. Keeping the judge on Mistral Large 3 675B (Mistral family) preserves the non-circular grading invariant when the brain is Gemini.
## Reversal trigger
Re-open this ADR if (a) Google AI Studio imposes a paid-tier requirement or removes `response_mime_type` support, (b) the 1500 req/day quota is consistently exhausted before noon UTC over a 7-day window (signalling we need either a paid tier or a different primary), (c) live audit shows Gemini Flash silently violating the JSON-mode contract on any sales-brain or recommendation turn (the failure class KI-160 originally locked NIM against), or (d) the brain ↔ judge family-diversity invariant breaks (e.g. Google ships a judge-grade reasoning model and we're tempted to consolidate). Reversal would shift the Brain primaries back to NIM Mistral 675B with OpenRouter as Tier 1 — i.e. the KI-176 state — not the strict NIM-only lock of KI-160 (the `<FF>` trailer convention that motivated that lock is permanently retired).123456711 unmodified lines1920212223242526309 unmodified lines336337338339# Enterprise-Grade Readiness Audit**Target deployment:** top-tier Indian insurance companies (HDFC ERGO, ICICI Lombard, Bajaj Allianz, Star Health, Tata AIG, etc.)**Audit date:** 2026-05-14**Audit window:** active — this is a living document. Background audits (100-persona simulation + full gold-QA eval) running concurrently; results merge here as they land.---11 unmodified lines| Language-handling fairness | ⚠️ Hinglish concern was a 20-persona sampling artifact. Real outliers: tax_planner archetype (4.6 refusals) + stream style (4.3) — open. | P1 — India-market regulatory risk || Code hygiene | ✅ Loose tmp files removed; `fact_find_normalizer` + `profile_extractor` migrated to chain pattern (KI-033) | — || Test coverage | 🟡 15 unit tests pinning KI-018 / KI-023 / KI-080 routing + primary-election invariants. Broader coverage still open. | P1 || Voice UX | ✅ Live default-on + clickable toggle + labeled push-to-talk + barge-in working (ADR-028) | — || Fact-find robotic tone | ✅ LLM paraphraser w/ verifier (ADR-027) | — || Secrets handling | ✅ Verified clean (.env never committed) | — |Legend: ✅ fixed / ⚠️ partial / 🟡 improving / 🔴 open309 unmodified lines---*This file regenerates as new evidence lands. Last updated: 2026-05-15 (KI-101..KI-107 landed).*123456711 unmodified lines192021222324252627309 unmodified lines337338339340341342343344345346347348349350351352353354355356357# Enterprise-Grade Readiness Audit**Target deployment:** top-tier Indian insurance companies (HDFC ERGO, ICICI Lombard, Bajaj Allianz, Star Health, Tata AIG, etc.)**Audit date:** 2026-05-14 (initial) · 2026-05-15 (follow-on sprint KI-167 → KI-179 landed)**Audit window:** active — this is a living document. Background audits (100-persona simulation + full gold-QA eval) running concurrently; results merge here as they land.---11 unmodified lines| Language-handling fairness | ⚠️ Hinglish concern was a 20-persona sampling artifact. Real outliers: tax_planner archetype (4.6 refusals) + stream style (4.3) — open. | P1 — India-market regulatory risk || Code hygiene | ✅ Loose tmp files removed; `fact_find_normalizer` + `profile_extractor` migrated to chain pattern (KI-033) | — || Test coverage | 🟡 15 unit tests pinning KI-018 / KI-023 / KI-080 routing + primary-election invariants. Broader coverage still open. | P1 || Voice UX | ✅ Live default-on + clickable toggle + labeled push-to-talk + barge-in working (ADR-028) + hybrid Web Speech + MediaRecorder capture (KI-168) + tab-switch revival (KI-173 / KI-174) | — || Fact-find robotic tone | ✅ Replaced with `sales_brain` LLM-driven loop ([ADR-039](../70-docs/60-decisions/ADR-039-llm-driven-sales-brain.md), KI-167) — no scripted prompts, no `<FF>` trailer, native provider JSON mode | — || LLM stack | ✅ 3-tier chain Google → NIM → OpenRouter per [ADR-040](../70-docs/60-decisions/ADR-040-google-gemini-primary.md). Gemini 2.0/2.5 Flash primary; NIM Mistral 675B fallback; OR `:free` diversity. Judge stays NIM Mistral 675B (cross-family from Gemini). | — || Secrets handling | ✅ Verified clean (.env never committed) | — |Legend: ✅ fixed / ⚠️ partial / 🟡 improving / 🔴 open309 unmodified lines---## Sprint 2026-05-15 (KI-167 → KI-179) — chain rewrite + sales_brain rip-outSecond-day follow-on sprint after live user testing flagged that the scripted `<FF>` trailer convention was leaking into every fallback turn. Full timeline in [`70-docs/40-evaluation/quality-sprint-2026-05-14.md`](../70-docs/40-evaluation/quality-sprint-2026-05-14.md) (Follow-on sprint section). Highlights against the register:| KI | Impact on register | Note ||---|---|---|| **KI-167** ([ADR-039](../70-docs/60-decisions/ADR-039-llm-driven-sales-brain.md)) | Closes the "scripted fact-find leakage" defect at root — `backend/fact_find_brain.py` + `_canonical_fallback` + the `<FF>` trailer convention all deleted. Replaced with `backend/sales_brain.py` (one LLM call per turn, native provider JSON mode). KI-090 lenient parser, KI-103 no_trailer loop-breaker, and the entire `fact_find_brain::fallback:*` telemetry vocabulary are retired. | Net negative LOC. || **KI-168 / KI-173 / KI-174** | Voice UX hardening — hybrid Web Speech (live UX) + MediaRecorder (authoritative blob → Sarvam STT) + tab-switch revival hooks. | Frontend-only. || **KI-171** | Skip faithfulness Gate 4 on `fact_find` + `recommendation` intents (no retrieval context to grade against). | Tightens D-006 fairness risk surface. || **KI-175 / KI-176** | NIM chain reorder — Nemotron 49B demoted from primary to last resort; OpenRouter re-added as cross-provider diversity (using OR's `models: [...]` server-side fallback). | Mitigates D-004 latency long-tail. || **KI-178** | Live audit of OR `:free` `response_format` support — Llama 3.3 70B / Hermes 3 405B excluded; only Nemotron-3-Super 120B + Qwen 80B `:free` + Gemma-4 31B included. | Closes a silent-failure class proactively. || **KI-179** ([ADR-040](../70-docs/60-decisions/ADR-040-google-gemini-primary.md)) | New `backend/providers/google_gemini_llm.py`; Gemini 2.0 Flash → Brain Fast primary, Gemini 2.5 Flash → Brain Main primary. NIM Tier 1 fallback, OR `:free` Tier 2 diversity. Judge stays on NIM Mistral 675B (different family from Gemini — preserves brain ↔ judge family-diversity invariant). | Tier 0 free-tier conversational quality lift. |The 2026-05-14 scoreboard rows for "Voice UX", "Fact-find robotic tone", and the new "LLM stack" row are now fully green. D-003 (factual accuracy) and D-004 (latency) remain partially open pending a fresh full-eval re-run on the new chain shape.---*This file regenerates as new evidence lands. Last updated: 2026-05-15 (sprint KI-167 → KI-179 landed; ADR-039 + ADR-040 ship).*
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950Insurance Sales Portfolio Expert: Architecture & DesignThis document details the technical architecture, operational workflows, and future roadmap for the Insurance Sales AI Agent.---## System ArchitectureThe application is built using a modular approach to ensure simplicity, explainability and high performance.### 1. Frontend & Orchestration- **Technology**:- **Role**: Serves as the user interface and central controller. It manages:- **Session State**: Tracks chat history, processed audio IDs, and indexed document status.- **Resource Caching**: Uses `@st.cache_resource` to ensure heavy models (Whisper, RAG, LLM) are loaded only once.- **Component Coordination**: Pipes data from the microphone to Whisper, then to the RAG engine, then to the LLM, and finally to the TTS engine.### 2. Retrieval-Augmented Generation- **Technology**:- **Embeddings**:- **Workflow**:- **Ingestion**:- **Metadata Tagging**: Documents are tagged as either `Product` (policies) or `Regulatory` (annual reports).- **Vector Storage**:- **Retrieval**:### 3. Language Processing- **Technology**:- **Role**: The "reasoning" engine.- **System Prompting**: Enforces a persona of a "Professional Insurance Advisor." It is explicitly instructed to:- Compare multiple policies.- Use specific citation tags (e.g., `[Source: ...]`).- Be concise for voice-based interactions.### 4. Voice Pipeline- **STT (Speech-to-Text)**:- **TTS (Text-to-Speech)**:---## How It Works (Step-by-Step)1. **Document Indexing**: User uploads a PDF.2. **Voice Input**: Captures raw audio.3. **Transcription**: Converts the audio bytes into text.4. **Contextual Retrieval**: The text query is embedded and matched against the DB. The engine returns the most relevant snippets along with their source.5. **Response Generation**: The LLM receives the user's question and the retrieved snippets. It synthesises a natural language answer.6. **Voice Synthesis**: The answer is converted to voice7. **Playback**: Audio component plays the response automatically1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495# Insurance Sales Portfolio Expert — Architecture & DesignA condensed, current architecture map of the Insurance Sales AI Agent. Forauthoritative system-level detail see [`70-docs/10-architecture/system-overview.md`](70-docs/10-architecture/system-overview.md);for routing + chain mechanics see[`70-docs/60-decisions/ADR-040-google-gemini-primary.md`](70-docs/60-decisions/ADR-040-google-gemini-primary.md).---## System architecture### 1. Frontend- **Technology:** Next.js 14 (App Router) + Tailwind v4 + shadcn/ui — deployedto the HF Space static surface.- **Voice capture (post-KI-168 hybrid):** Web Speech API streams interimtranscripts into the chat input for live UX feel, while `MediaRecorder` runsin parallel and captures the authoritative audio blob. On browsersilence-detect the blob is POSTed to `/api/transcribe` (Sarvam Saarika STT,the authoritative transcript); auto-submit then falls back to the Web Speechtranscript only if Sarvam errors. KI-173 heartbeat + KI-174`visibilitychange` / `focus` revival keep the mic alive across tab and appswitches.### 2. Backend (FastAPI orchestrator)- **Technology:** FastAPI + Pydantic. Single per-turn entry `POST /api/chat`fans out through `backend/orchestrator.py`.- **Sales brain (`backend/sales_brain.py`, KI-167):** one LLM call perfact-find turn against `FAST_BRAIN_CHAIN`. Uses native provider JSON mode(`response_mime_type=application/json` on Gemini,`response_format={"type":"json_object"}` on NIM / OpenRouter) — no `<FF>`trailer convention, no scripted canonical fallback. See[ADR-039](70-docs/60-decisions/ADR-039-llm-driven-sales-brain.md).- **Faithfulness:** 4-gate guard in `backend/faithfulness.py` (retrieval floor→ citation integrity → regex numeric grounding → cross-family judge).Skipped on `fact_find` + `recommendation` intents per KI-171.### 3. LLM chains (3-tier, post-ADR-040)| Role | Tier 0 (primary) | Tier 1 (NIM fallback) | Tier 2 (OR diversity) | Last resort ||---|---|---|---|---|| Brain Fast (sales_brain) | Gemini 2.0 Flash | Qwen 3-Next 80B → Mistral Large 3 675B → Llama-4 Maverick | OR Nemotron-3-Super 120B → OR Qwen 80B `:free` | NIM Nemotron 49B || Brain Main (synthesis) | Gemini 2.5 Flash | Mistral Large 3 675B → Llama-4 Maverick → Qwen 80B | OR Nemotron-3-Super 120B | NIM Nemotron 49B || Judge (faithfulness Gate 4) | NIM Mistral Large 3 675B | Llama-4 Maverick | OR Qwen 80B `:free` | NIM Nemotron 49B |Provider keys: `GOOGLE_API_KEY` (1500 req/day free), `NVIDIA_NIM_API_KEY`(free, 40 req/min), `OPENROUTER_API_KEY` ($10 unlocks 1000 req/day on `:free`models). Brain ↔ judge family-diversity invariant is preserved — Gemini-braincalls are graded by Mistral.### 4. Retrieval & data- **Vector store:** Chroma persistent client at `rag/vectors/` (BGE-small-en-v1.5local 384-d embeddings — see [ADR-011](70-docs/60-decisions/ADR-011-bge-local-embeddings.md)).- **Structured store:** DuckDB rollup of 62-field `HealthPolicy` extractions(`rag/policies.duckdb`); the source-of-truth JSONs live in`rag/extracted/<policy_id>.json` and curated facts in `40-data/policy_facts/`.- **Profile RAG:** session profile is embedded as a Chroma chunk with`session_id` metadata; KI-102 enforces strict session isolation on lookup.### 5. Voice pipeline- **STT:** Sarvam Saarika v2.5 (`/api/transcribe`).- **TTS:** Sarvam Bulbul v2 — bot replies normalised by`backend/voice_format.py::tts_preprocess` (markdown stripped, CoT leakagekilled per KI-104, money shorthand expanded per KI-066).---## How a single turn flows1. **Voice input** — browser captures audio with `MediaRecorder` while WebSpeech provides interim text for the UI.2. **Transcription** — silence-detect POSTs the blob to `/api/transcribe`(Sarvam Saarika STT); Web Speech transcript is the fallback.3. **Chat call** — `POST /api/chat` runs `classify_intent`,profile-RAG injection, and dispatches to `sales_brain` (fact-find) or toretrieval + Brain Main (QA / comparison / recommendation).4. **Brain call** — sticky-primary election (KI-080) picks one candidate fromthe relevant chain; native JSON mode guarantees parseable output.5. **Faithfulness gates** — retrieval floor + citation integrity + regexnumeric grounding + (cross-family) judge LLM. Blocked replies land in`logs/hallucinations.jsonl`.6. **TTS synthesis** — Sarvam Bulbul returns base64 audio in the same JSONresponse; frontend plays it through the in-DOM `<audio>` element sobarge-in's `querySelectorAll("audio").pause()` actually finds it.7. **Telemetry** — every turn writes a JSONL record (intent, brain_used,latency, faithfulness verdict, cost estimate) for replay + audit.---## Where to read next- [`70-docs/10-architecture/system-overview.md`](70-docs/10-architecture/system-overview.md) — full system map with the canonical data flow.- [`70-docs/10-architecture/stack-rationale.md`](70-docs/10-architecture/stack-rationale.md) — every technology pick with alternatives + reasoning.- [`70-docs/60-decisions/ADR-040-google-gemini-primary.md`](70-docs/60-decisions/ADR-040-google-gemini-primary.md) — the current chain shape.- [`70-docs/60-decisions/ADR-039-llm-driven-sales-brain.md`](70-docs/60-decisions/ADR-039-llm-driven-sales-brain.md) — fact-find LLM-driven sales brain.- [`backend/README.md`](backend/README.md) — per-module entry points.- [`80-audit/ENTERPRISE_AUDIT.md`](80-audit/ENTERPRISE_AUDIT.md) — live defect register + production-readiness scorecard.
17 unmodified lines1819202122232425262728293031323334353610 unmodified lines47484950515253545556575859606162636468 unmodified lines13313413513613713813914017 unmodified lines- **Hands-free was removed entirely** in KI-027. Anything in the codebase still referring to it is stale.- **Bot TTS plays via the in-DOM `<audio>` element** inside `Message` (autoplay-on-mount via ref'd `useEffect`). Never use `new Audio(url).play()` — those detached instances are invisible to `document.querySelectorAll("audio").pause()` in the barge-in handler.## LLM stack (ADR-019 + ADR-026 → ADR-031 + ADR-032 → ADR-038) — KI-080 → KI-087, KI-160Every LLM role is a `NimChainLLM` candidate pool, NOT a hardcoded single model. End-to-end spec: [ADR-032](70-docs/60-decisions/ADR-032-llm-chain-architecture.md). All three chains are **locked to NIM candidates only** as of KI-160 / [ADR-038](70-docs/60-decisions/ADR-038-nim-only-chains.md) — Groq + OpenRouter were removed as election candidates after KI-155 proved Groq Llama-3.3 silently ignores the `<FF>` structured-output trailer contract. Chains still preserve brain ↔ judge family diversity (Qwen / Nemotron brain ↔ Mistral / Llama-4 judge) so failovers can't produce circular grading.- **NIM-only election (KI-160, [ADR-038](70-docs/60-decisions/ADR-038-nim-only-chains.md)).** Candidate pools per role: BRAIN — `nvidia/llama-3.3-nemotron-super-49b-v1.5` (primary), `qwen/qwen3-next-80b-a3b-instruct` (backup), `mistralai/mistral-large-3-675b-instruct-2512` (3rd). FAST_BRAIN — `qwen/qwen3-next-80b-a3b-instruct` (primary), `nvidia/llama-3.3-nemotron-super-49b-v1.5` (backup). JUDGE — `meta/llama-4-maverick-17b-128e-instruct` (primary), `mistralai/mistral-large-3-675b-instruct-2512` (backup). If all NIM candidates fail in a turn, orchestrator returns a graceful error message instead of cascading to Groq / OpenRouter — **fail-loud > fail-silent-with-garbage**.- **Probe-driven sticky primary election (KI-080, [ADR-031](70-docs/60-decisions/ADR-031-sticky-primary-election.md), superseded by ADR-038 for candidate-pool scope).** All three chains elect a sticky PRIMARY + BACKUP from a background probe within the NIM pool. `backend/llm_health.py` scores every candidate on `(1 / max(50, latency_ms)) * success_rate` and writes the current election to process state. `NimChainLLM.chat()` calls PRIMARY once; on real-time failure it falls to BACKUP and triggers an immediate probe refresh. **Per-turn LLM call count: 1 (most cases) or 2 (PRIMARY fails real-time → BACKUP).**- **Probe cadence + per-phase timeouts (KI-084, `119e0fd`).** Probe loop ticks at `PROBE_INTERVAL_SEC = 300s`. Probe `max_tokens` cut `5 → 1`. Every chat call uses explicit `httpx.Timeout(connect=2, read=12, write=2, pool=2)` so a stuck NIM pool releases its TCP socket independently of the outer `asyncio.wait_for`. Rate-limit failures (HTTP 429 / `RateLimit` body) get a **1h sin-bin** (`DEGRADE_DURATION_LONG_S = 3600s`).- **Proactive credit gating (KI-085, `8fc7979`), now NIM-only scope.** Election is gated by `is_alive AND has_credits` so quota-exhausted NIM models are excluded BEFORE the user hits a 429. Signal source within the NIM pool: per-model local 60-second rate-meter (gate at 35-of-40 req/min, headroom 5). Per-model rate-metering applies within the locked NIM pool.- **HF Space secrets (KI-081).** `GROQ_API_KEY` + `OPENROUTER_API_KEY` remain in HF Space repository secrets for future re-enable, but the chain config no longer references them after KI-160 — they are dormant, not active election candidates. `NVIDIA_NIM_API_KEY` is the only key the chain config consults.- **Admin telemetry (KI-086, `d90f8c0`).** `GET /api/admin/llm-health` returns `{chains, candidates, recent_turns, snapshot_ts}` with per-chain elected primary/backup, per-candidate health + credits + degraded-until, and last 20 turn outcomes. Admin "LLM Chain" tab auto-refreshes every 30s and renders whatever the chain config exposes (NIM-only post-KI-160).- **KI-025's 50/50 NIM ↔ Groq rotation ([ADR-026](70-docs/60-decisions/ADR-026-provider-load-balancing.md)) is deprecated** — `_balanced_brain_chain` retained behind a feature flag for one-release rollback; the probe-driven NIM-only election picks the actually-faster candidate dynamically.- **Cold-start fallback.** Before the first probe completes (process restart, HF Space rebuild), `chain[0]` is the initial primary and `chain[1]` is the initial backup, both NIM.- **Brain / fast-brain / judge primaries in steady state** are **NIM Nemotron-Super 49B** (brain), **NIM Qwen 3-Next 80B** (fast brain), and **NIM Llama-4 Maverick 17B/128E** (judge), per the KI-160 candidate lists. Not hardcoded — elected primary follows live `latency × success_rate × credits_available` within the NIM pool.- **KI-079 escalation as last bite (`87ee522`) — modified by KI-167.** If both PRIMARY and BACKUP fail in a single fact-find turn, orchestrator retries once on `BRAIN_CHAIN` (heavy brain, `_TIMEOUT_S_ESCALATION = 15s`, 35s chain budget). Post-KI-167 ([ADR-039](70-docs/60-decisions/ADR-039-llm-driven-sales-brain.md)) the `_canonical_fallback` terminal step is gone — on heavy-brain exhaustion the orchestrator returns the [ADR-038](70-docs/60-decisions/ADR-038-nim-only-chains.md) graceful error message instead. Worst-case wall-clock before graceful error: 25s FAST + 15s heavy = 40s.- **NIM concurrency semaphore + serial probe (KI-088, `14ee008`).** Module-level `asyncio.Semaphore(2)` wraps every NIM HTTP call so our process never has >2 NIM requests in flight simultaneously, regardless of source (probe loop + admin polls + per-user turns all serialise through the same semaphore). Probe loop changed parallel→serial so the 6-NIM probe burst becomes a 1-slot trickle over ~12s. Inner 4-attempt exponential-backoff retry deleted from `NvidiaNimLLM.chat()` — KI-080 election + KI-079 escalation now handle failover. Result: latency-based failures (41s timeouts under self-saturation) dropped to zero; replaced by a parser-side bottleneck (KI-090).- **Lenient FF-block parser (KI-090, `11cf4b3`) — RETIRED by KI-167 ([ADR-039](70-docs/60-decisions/ADR-039-llm-driven-sales-brain.md)).** Was needed because the `<FF>...</FF>` trailer convention was fragile under load. Post-KI-167 the sales brain uses NIM `response_format={"type":"json_object"}` for guaranteed structured output, so the whole `_parse_ff_block` strict → fenced → bare-JSON ladder is gone.10 unmodified lines- **Chroma collection re-ingested + profile-write hardening (KI-112).** KI-111 wrapped `.query()` so the bot survived the corruption, but every embedding query was raising `InternalError: Error executing plan: Internal error: Error finding id` and silently returning empty retrieval — the bot was answering 206 policies' worth of Qs without access to any policy chunk. Root cause: a pre-KI-102 deploy wrote a `profile_anonymous` chunk with NO `session_id` metadata; that legacy row poisoned every later `coll.query(where={"doc_type": {"$ne": "profile"}})` and the damage spread across HNSW segments (full collection extraction surfaced 1580 / 7356 chunks across 148 policies as `Error getting embedding`). Fix: full re-ingest from `rag/corpus/` PDFs → clean `rag/vectors/` + two new write-time guards in `backend/profile_rag.py::upsert_profile_chunk` — (a) reject `session_id` that isn't a non-empty `str`, (b) reject any embedding whose length ≠ `embedder.dimension` or that contains `None`. Both guards log a `WARNING` and return without writing, so a future model-drift or bad-input event can't re-poison HNSW. 4 new regression tests in `tests/test_profile_rag_isolation.py::TestUpsertRejectsBadInputs`. Repaired vectors uploaded to HF dataset `rohitsar567/insurance-bot-data` via `tools/upload_vectors_to_dataset.py` so the Space rebuild picks up the clean index. Old corrupted Chroma archived at `rag/_hf_dataset_backup/rag/vectors.corrupted.<ts>/`.- **Chain budgets:** brain 20s × 35s total, fast-brain 12s × 22s total, judge 30s × 75s total. With KI-080 only PRIMARY + BACKUP consume budget in the common case — leaves headroom for KI-079 escalation. KI-084 per-phase httpx timeouts are nested inside these budgets.- **STT/TTS/Translator** = Sarvam (Saarika v2.5 / Bulbul v2 / Sarvam-M). **Embeddings** = local BGE-small-en-v1.5.- **Provider keys.** `NVIDIA_NIM_API_KEY` + `GROQ_API_KEY` + `OPENROUTER_API_KEY` required in `.env` (local) and HF Space environment (production — KI-081).## Fact-find loop (ADR-039, supersedes ADR-030 / ADR-027) — KI-167**One LLM call per turn, structured-output JSON, no scripted prompts, no fallback prose.** KI-167 ripped out `backend/fact_find_brain.py` (the `<FF>{...}</FF>` trailer convention + `_canonical_fallback` greedy slot-walker + scripted `Question.prompt_en` prefixed with `"Got that — {slot}."`) and replaced it with `backend/sales_brain.py` — a single LLM-driven sales agent. The pre-KI-167 architecture had accreted eight patches (KI-090 / KI-091 / KI-094 / KI-103 / KI-150 / KI-155 / KI-156 / KI-158 / KI-161) working around the fragility of pattern-matching structure out of prose; KI-155 and follow-ups showed the canonical fallback was the *dominant* path, not the safety net. User-visible symptom: "zero natural LLM chat — it always defaults to the script."- **Single NIM call per turn** via `NimChainLLM(FAST_BRAIN_CHAIN)` against the [ADR-038](70-docs/60-decisions/ADR-038-nim-only-chains.md) NIM-only pool, using NVIDIA NIM's **`response_format={"type": "json_object"}`** for structured output — the same JSON-mode contract already validated in `backend/translation_check.py`, `backend/faithfulness.py`, and `backend/security.py`. Response shape: `{"reply": "<prose for user>", "captures": {<slot_id>: <raw>}, "slot_driving": "<slot_id|null>", "complete": <bool>}`.- **System prompt** carries the 9-slot schema + current profile state. The LLM is free to ask in any order, in any voice, multi-fact in one turn or one slot at a time. No scripted opener, no acknowledger prefix, no `prompt_en` template.- **Deterministic post-processor** (`backend/sales_brain_normalizer.py`) takes the LLM's loose `captures` dict and emits a `{canonical_field: validated_value}` map: alias resolution (`location` → `location_tier`), enum normalization (`Bangalore` → `metro`), INR-amount parsing, null/empty drop, type/bounds validation. No LLM calls — pure rules. Override: if LLM sets `complete: true` while any required slot is empty, force `complete: false`.- **Profile persistence unchanged.** Captures flow through `session.update_profile_field()` → `backend/profile_store.save_profile()` (disk durability) → `backend/profile_rag.upsert_profile_chunk()` (retrieval-side visibility). KI-102 / KI-107 / KI-112 session-isolation guards remain in force.- **No scripted prompts, no canonical_fallback, no trailer convention.** `backend/needs_finder.py::GRAPH` slot-id data stays as a schema source for the system prompt, but `Question.prompt_en` is dead text — never consulted by the fact-find branch. `_canonical_fallback`, `_normalize_for_slot`, `_pick_opener`, `_NEUTRAL_OPENERS`, `_FAMILY_OPENERS`, `_contains_self_introduction`, the lenient `<FF>` parser ladder, and the `"Got that — {slot}."` prefix logic are deleted.- **Outer 25s `asyncio.wait_for` ceiling retained.** On total NIM exhaustion the orchestrator returns the [ADR-038](70-docs/60-decisions/ADR-038-nim-only-chains.md) graceful error to the user (fail-loud) rather than cascading to a scripted reply. There is no scripted safety net — that is intentional.- **DELETED in KI-167:** `backend/fact_find_brain.py` (441 LOC); `_canonical_fallback` + `_pick_opener` branches in `backend/orchestrator.py`; `_ff_failed_attempts` / `_ff_skipped_slots` session fields; every `fact_find_brain::fallback:*` telemetry variant; the lenient `<FF>` / fenced-`json` / bare-JSON-tail parser ladder.- **Persona-audit fixtures rewritten** to assert on final captured state (which slots are filled with what) rather than per-turn slot order — the LLM may capture in different turn order than the pre-KI-167 rules engine did. See WS4.- **Natural-conversation escape (KI-045):** intent_change phrases / off-topic questions still exit fact-find by routing through `should_route_to_fact_find` upstream of the brain.68 unmodified lines- **The `indusind-general` slug did not exist anywhere in the codebase before 2026-05-15.** Reliance General Insurance was rebranded to IndusInd General; **KI-144** migrated insurer slug + policy IDs + Chroma metadata + marketplace alias mapping. Any code referencing `reliance-general` should either be retained as a legacy alias (one card remains under `reliance-general` for back-compat) or migrated to `indusind-general`. Do not silently merge the two — they're tracked as separate slugs.- **Voice mode now defaults OFF (KI-131 / KI-134 / KI-139 / KI-148).** The Live pill renders red by default; the user must opt in. AudioContext.resume() is required to unlock TTS autoplay. VAD thresholds: `rmsThreshold=18`, `voiceBandMinProp=0.20`, `noiseFloor * 1.8`. TTS preprocess now expands `k → thousand`. Anything in the codebase still assuming default-ON Live mode is stale.- **Marketplace dedup is one card per IRDAI-filed product (KI-133 / KI-141 / KI-142 / KI-145).** Aliases handle marketing renames (e.g. Reliance → IndusInd); sub-variants stay separate only when material terms differ. Card count is 166 across 19 real insurers — anything counting 138 or 188 or 206 against the marketplace is stale.- **`sales_brain.py` is the fact-find handler (KI-167, [ADR-039](70-docs/60-decisions/ADR-039-llm-driven-sales-brain.md)).** `backend/fact_find_brain.py` is deleted along with the `<FF>` trailer convention, `_canonical_fallback`, scripted `Question.prompt_en`, and the `"Got that — {slot}."` prefix. Never re-introduce a fallback to scripted prompts on the fact-find branch — on total NIM exhaustion the orchestrator returns the [ADR-038](70-docs/60-decisions/ADR-038-nim-only-chains.md) graceful error message (fail-loud > fail-silent-with-script). The KI-150 historical note (`fact_find_brain` `max_tokens` 420 → 700) is moot post-KI-167 since the prose+trailer prompt shape that needed the larger budget no longer exists.---*Last reviewed 2026-05-15 — KI-101..KI-112 landed (orchestrator stability + profile-RAG session isolation + recommendation closer + graceful chat error handling + Chroma re-ingest + profile-write hardening). Same day: KI-125..KI-150 landed (full corpus rebuild → 7,317 chunks; marketplace dedup → 166 cards; voice default OFF + VAD retune; IndusInd General slug migration from Reliance General). Same day: KI-160 / [ADR-038](70-docs/60-decisions/ADR-038-nim-only-chains.md) locked chains to NIM-only after KI-155's `<FF>` trailer contract violation. Same day: KI-167 / [ADR-039](70-docs/60-decisions/ADR-039-llm-driven-sales-brain.md) replaced `fact_find_brain.py` (scripted slot-walker + `<FF>` trailer + `_canonical_fallback` + scripted `Question.prompt_en`) with `backend/sales_brain.py` (single LLM call per turn, NIM `response_format=json_object`, deterministic post-processor).*17 unmodified lines181920212223242526272829303132333435363738394010 unmodified lines51525354555657585960616263646566676868 unmodified lines13713813914014114214314414517 unmodified lines- **Hands-free was removed entirely** in KI-027. Anything in the codebase still referring to it is stale.- **Bot TTS plays via the in-DOM `<audio>` element** inside `Message` (autoplay-on-mount via ref'd `useEffect`). Never use `new Audio(url).play()` — those detached instances are invisible to `document.querySelectorAll("audio").pause()` in the barge-in handler.## LLM stack (ADR-019 + ADR-026 → ADR-031 + ADR-032 → ADR-038 → ADR-040) — KI-080 → KI-087, KI-160, KI-167 → KI-179Every LLM role is a `NimChainLLM` candidate pool, NOT a hardcoded single model. End-to-end spec: [ADR-032](70-docs/60-decisions/ADR-032-llm-chain-architecture.md). Chains now mix **Google AI Studio (Gemini Flash) as Tier 0 primary, NIM as Tier 1 fallback, OpenRouter free as Tier 2 diversity pool** ([ADR-040](70-docs/60-decisions/ADR-040-google-gemini-primary.md) — supersedes ADR-038's NIM-only lock once KI-167 retired the `<FF>` trailer convention that motivated the lock). Native provider JSON mode (`response_format={"type":"json_object"}` on NIM, `response_mime_type=application/json` on Gemini) is the structured-output contract; cross-provider fallback is safe again as long as every candidate supports JSON mode natively. Chains preserve brain ↔ judge family diversity (Gemini brain ↔ Mistral / Llama-4 judge) so failovers can't produce circular grading.- **Three-tier election ([ADR-040](70-docs/60-decisions/ADR-040-google-gemini-primary.md)).** Candidate pools per role:- **Brain Fast** (sales-brain fact-find per KI-167, fast QA): Google `gemini-2.0-flash` (PRIMARY) → NIM `qwen3-next-80b-a3b-instruct` → NIM `mistralai/mistral-large-3-675b-instruct-2512` (675B dense) → NIM `meta/llama-4-maverick-17b-128e-instruct` (128B MoE) → OpenRouter `nvidia/nemotron-3-super-120b-a12b:free` → OpenRouter `qwen/qwen3-next-80b-a3b-instruct:free` → NIM `nvidia/llama-3.3-nemotron-super-49b-v1.5` (last resort).- **Brain Main** (free-form QA + recommendation synthesis): Google `gemini-2.5-flash` (PRIMARY) → NIM `mistralai/mistral-large-3-675b-instruct-2512` → NIM `meta/llama-4-maverick-17b-128e-instruct` → NIM `qwen/qwen3-next-80b-a3b-instruct` → OpenRouter `nvidia/nemotron-3-super-120b-a12b:free` → NIM `nvidia/llama-3.3-nemotron-super-49b-v1.5` (last resort).- **Judge** (faithfulness Gate 4, KI-171 skips on `fact_find` + `recommendation` queries): NIM `mistralai/mistral-large-3-675b-instruct-2512` (PRIMARY — different family from Gemini brain) → NIM `meta/llama-4-maverick-17b-128e-instruct` → OpenRouter `qwen/qwen3-next-80b-a3b-instruct:free` → NIM `nvidia/llama-3.3-nemotron-super-49b-v1.5`.Google AI Studio free tier: 1500 req/day, 15 req/min on Gemini 2.0/2.5 Flash. On total chain exhaustion, orchestrator returns a graceful error message to the user — **fail-loud > fail-silent-with-garbage** still holds at the chain-tail level.- **Probe-driven sticky primary election (KI-080, [ADR-031](70-docs/60-decisions/ADR-031-sticky-primary-election.md), superseded by ADR-038 for candidate-pool scope).** All three chains elect a sticky PRIMARY + BACKUP from a background probe within the NIM pool. `backend/llm_health.py` scores every candidate on `(1 / max(50, latency_ms)) * success_rate` and writes the current election to process state. `NimChainLLM.chat()` calls PRIMARY once; on real-time failure it falls to BACKUP and triggers an immediate probe refresh. **Per-turn LLM call count: 1 (most cases) or 2 (PRIMARY fails real-time → BACKUP).**- **Probe cadence + per-phase timeouts (KI-084, `119e0fd`).** Probe loop ticks at `PROBE_INTERVAL_SEC = 300s`. Probe `max_tokens` cut `5 → 1`. Every chat call uses explicit `httpx.Timeout(connect=2, read=12, write=2, pool=2)` so a stuck NIM pool releases its TCP socket independently of the outer `asyncio.wait_for`. Rate-limit failures (HTTP 429 / `RateLimit` body) get a **1h sin-bin** (`DEGRADE_DURATION_LONG_S = 3600s`).- **Proactive credit gating (KI-085, `8fc7979`), now NIM-only scope.** Election is gated by `is_alive AND has_credits` so quota-exhausted NIM models are excluded BEFORE the user hits a 429. Signal source within the NIM pool: per-model local 60-second rate-meter (gate at 35-of-40 req/min, headroom 5). Per-model rate-metering applies within the locked NIM pool.- **HF Space secrets (KI-081, updated KI-179).** The chain config now consults **`GOOGLE_API_KEY`** (Tier 0, Brain Fast + Brain Main primary), `NVIDIA_NIM_API_KEY` (Tier 1 fallback + Judge primary), and `OPENROUTER_API_KEY` (Tier 2 diversity pool — KI-176 server-side `models: [...]` fallback within the OR free pool). `GROQ_API_KEY` remains in HF Space secrets but is dormant — Groq is no longer in any chain (KI-155 `<FF>` violation root cause remains a guard even though the `<FF>` convention itself is gone).- **Admin telemetry (KI-086, `d90f8c0`).** `GET /api/admin/llm-health` returns `{chains, candidates, recent_turns, snapshot_ts}` with per-chain elected primary/backup, per-candidate health + credits + degraded-until, and last 20 turn outcomes. Admin "LLM Chain" tab auto-refreshes every 30s and renders whatever the chain config exposes (NIM-only post-KI-160).- **KI-025's 50/50 NIM ↔ Groq rotation ([ADR-026](70-docs/60-decisions/ADR-026-provider-load-balancing.md)) is deprecated** — `_balanced_brain_chain` retained behind a feature flag for one-release rollback; the probe-driven NIM-only election picks the actually-faster candidate dynamically.- **Cold-start fallback.** Before the first probe completes (process restart, HF Space rebuild), `chain[0]` is the initial primary and `chain[1]` is the initial backup, both NIM.- **Brain / fast-brain / judge primaries in steady state** are **Google `gemini-2.5-flash`** (Brain Main), **Google `gemini-2.0-flash`** (Brain Fast / sales-brain fact-find), and **NIM Mistral Large 3 675B** (Judge), per the ADR-040 chain. Not hardcoded — elected primary follows live `latency × success_rate × credits_available` across the full three-tier pool; on Google quota exhaustion or 429, election falls naturally to NIM Mistral 675B (the Tier 1 fallback) without operator intervention.- **KI-079 escalation as last bite (`87ee522`) — modified by KI-167.** If both PRIMARY and BACKUP fail in a single fact-find turn, orchestrator retries once on `BRAIN_CHAIN` (heavy brain, `_TIMEOUT_S_ESCALATION = 15s`, 35s chain budget). Post-KI-167 ([ADR-039](70-docs/60-decisions/ADR-039-llm-driven-sales-brain.md)) the `_canonical_fallback` terminal step is gone — on heavy-brain exhaustion the orchestrator returns the [ADR-038](70-docs/60-decisions/ADR-038-nim-only-chains.md) graceful error message instead. Worst-case wall-clock before graceful error: 25s FAST + 15s heavy = 40s.- **NIM concurrency semaphore + serial probe (KI-088, `14ee008`).** Module-level `asyncio.Semaphore(2)` wraps every NIM HTTP call so our process never has >2 NIM requests in flight simultaneously, regardless of source (probe loop + admin polls + per-user turns all serialise through the same semaphore). Probe loop changed parallel→serial so the 6-NIM probe burst becomes a 1-slot trickle over ~12s. Inner 4-attempt exponential-backoff retry deleted from `NvidiaNimLLM.chat()` — KI-080 election + KI-079 escalation now handle failover. Result: latency-based failures (41s timeouts under self-saturation) dropped to zero; replaced by a parser-side bottleneck (KI-090).- **Lenient FF-block parser (KI-090, `11cf4b3`) — RETIRED by KI-167 ([ADR-039](70-docs/60-decisions/ADR-039-llm-driven-sales-brain.md)).** Was needed because the `<FF>...</FF>` trailer convention was fragile under load. Post-KI-167 the sales brain uses NIM `response_format={"type":"json_object"}` for guaranteed structured output, so the whole `_parse_ff_block` strict → fenced → bare-JSON ladder is gone.10 unmodified lines- **Chroma collection re-ingested + profile-write hardening (KI-112).** KI-111 wrapped `.query()` so the bot survived the corruption, but every embedding query was raising `InternalError: Error executing plan: Internal error: Error finding id` and silently returning empty retrieval — the bot was answering 206 policies' worth of Qs without access to any policy chunk. Root cause: a pre-KI-102 deploy wrote a `profile_anonymous` chunk with NO `session_id` metadata; that legacy row poisoned every later `coll.query(where={"doc_type": {"$ne": "profile"}})` and the damage spread across HNSW segments (full collection extraction surfaced 1580 / 7356 chunks across 148 policies as `Error getting embedding`). Fix: full re-ingest from `rag/corpus/` PDFs → clean `rag/vectors/` + two new write-time guards in `backend/profile_rag.py::upsert_profile_chunk` — (a) reject `session_id` that isn't a non-empty `str`, (b) reject any embedding whose length ≠ `embedder.dimension` or that contains `None`. Both guards log a `WARNING` and return without writing, so a future model-drift or bad-input event can't re-poison HNSW. 4 new regression tests in `tests/test_profile_rag_isolation.py::TestUpsertRejectsBadInputs`. Repaired vectors uploaded to HF dataset `rohitsar567/insurance-bot-data` via `tools/upload_vectors_to_dataset.py` so the Space rebuild picks up the clean index. Old corrupted Chroma archived at `rag/_hf_dataset_backup/rag/vectors.corrupted.<ts>/`.- **Chain budgets:** brain 20s × 35s total, fast-brain 12s × 22s total, judge 30s × 75s total. With KI-080 only PRIMARY + BACKUP consume budget in the common case — leaves headroom for KI-079 escalation. KI-084 per-phase httpx timeouts are nested inside these budgets.- **STT/TTS/Translator** = Sarvam (Saarika v2.5 / Bulbul v2 / Sarvam-M). **Embeddings** = local BGE-small-en-v1.5.- **Provider keys (post-KI-179).** `GOOGLE_API_KEY` (Tier 0 — Gemini Flash primary), `NVIDIA_NIM_API_KEY` (Tier 1 fallback + Judge primary), `OPENROUTER_API_KEY` (Tier 2 diversity pool) required in `.env` (local) and HF Space environment (production). `GROQ_API_KEY` retained as dormant secret for one-flip re-enable, but no chain references it.## Fact-find loop (ADR-039 + ADR-040, supersedes ADR-030 / ADR-027) — KI-167 / KI-179**One LLM call per turn, structured-output JSON, no scripted prompts, no fallback prose.** KI-167 ripped out `backend/fact_find_brain.py` (the `<FF>{...}</FF>` trailer convention + `_canonical_fallback` greedy slot-walker + scripted `Question.prompt_en` prefixed with `"Got that — {slot}."`) and replaced it with `backend/sales_brain.py` — a single LLM-driven sales agent. KI-179 then moved the primary candidate from NIM Qwen to Google `gemini-2.0-flash` ([ADR-040](70-docs/60-decisions/ADR-040-google-gemini-primary.md)) for best-in-class conversational quality on the free path. The pre-KI-167 architecture had accreted eight patches (KI-090 / KI-091 / KI-094 / KI-103 / KI-150 / KI-155 / KI-156 / KI-158 / KI-161) working around the fragility of pattern-matching structure out of prose; KI-155 and follow-ups showed the canonical fallback was the *dominant* path, not the safety net. User-visible symptom: "zero natural LLM chat — it always defaults to the script."- **Single LLM call per turn** via `NimChainLLM(FAST_BRAIN_CHAIN)` against the [ADR-040](70-docs/60-decisions/ADR-040-google-gemini-primary.md) three-tier pool (Google Tier 0 → NIM Tier 1 → OpenRouter Tier 2). Google uses **`response_mime_type=application/json`**; NIM uses **`response_format={"type":"json_object"}`**; OpenRouter free-tier candidates (`nvidia/nemotron-3-super-120b-a12b:free`, `qwen/qwen3-next-80b-a3b-instruct:free`) also support `response_format` natively (KI-178 audit). Every candidate enforces structured output server-side — same contract already validated in `backend/translation_check.py`, `backend/faithfulness.py`, and `backend/security.py`. Response shape: `{"reply": "<prose for user>", "captures": {<slot_id>: <raw>}, "slot_driving": "<slot_id|null>", "complete": <bool>}`.- **System prompt** carries the 9-slot schema + current profile state. The LLM is free to ask in any order, in any voice, multi-fact in one turn or one slot at a time. No scripted opener, no acknowledger prefix, no `prompt_en` template.- **Deterministic post-processor** (`backend/sales_brain_normalizer.py`) takes the LLM's loose `captures` dict and emits a `{canonical_field: validated_value}` map: alias resolution (`location` → `location_tier`), enum normalization (`Bangalore` → `metro`), INR-amount parsing, null/empty drop, type/bounds validation. No LLM calls — pure rules. Override: if LLM sets `complete: true` while any required slot is empty, force `complete: false`.- **Profile persistence unchanged.** Captures flow through `session.update_profile_field()` → `backend/profile_store.save_profile()` (disk durability) → `backend/profile_rag.upsert_profile_chunk()` (retrieval-side visibility). KI-102 / KI-107 / KI-112 session-isolation guards remain in force.- **No scripted prompts, no canonical_fallback, no trailer convention.** `backend/needs_finder.py::GRAPH` slot-id data stays as a schema source for the system prompt, but `Question.prompt_en` is dead text — never consulted by the fact-find branch. `_canonical_fallback`, `_normalize_for_slot`, `_pick_opener`, `_NEUTRAL_OPENERS`, `_FAMILY_OPENERS`, `_contains_self_introduction`, the lenient `<FF>` parser ladder, and the `"Got that — {slot}."` prefix logic are deleted.- **Outer 25s `asyncio.wait_for` ceiling retained.** On total chain exhaustion (all of Google → NIM → OpenRouter fail in a single turn) the orchestrator returns the graceful error to the user (fail-loud) rather than cascading to a scripted reply. There is no scripted safety net — that is intentional.- **DELETED in KI-167:** `backend/fact_find_brain.py` (441 LOC); `_canonical_fallback` + `_pick_opener` branches in `backend/orchestrator.py`; `_ff_failed_attempts` / `_ff_skipped_slots` session fields; every `fact_find_brain::fallback:*` telemetry variant; the lenient `<FF>` / fenced-`json` / bare-JSON-tail parser ladder.- **Persona-audit fixtures rewritten** to assert on final captured state (which slots are filled with what) rather than per-turn slot order — the LLM may capture in different turn order than the pre-KI-167 rules engine did. See WS4.- **Natural-conversation escape (KI-045):** intent_change phrases / off-topic questions still exit fact-find by routing through `should_route_to_fact_find` upstream of the brain.68 unmodified lines- **The `indusind-general` slug did not exist anywhere in the codebase before 2026-05-15.** Reliance General Insurance was rebranded to IndusInd General; **KI-144** migrated insurer slug + policy IDs + Chroma metadata + marketplace alias mapping. Any code referencing `reliance-general` should either be retained as a legacy alias (one card remains under `reliance-general` for back-compat) or migrated to `indusind-general`. Do not silently merge the two — they're tracked as separate slugs.- **Voice mode now defaults OFF (KI-131 / KI-134 / KI-139 / KI-148).** The Live pill renders red by default; the user must opt in. AudioContext.resume() is required to unlock TTS autoplay. VAD thresholds: `rmsThreshold=18`, `voiceBandMinProp=0.20`, `noiseFloor * 1.8`. TTS preprocess now expands `k → thousand`. Anything in the codebase still assuming default-ON Live mode is stale.- **Marketplace dedup is one card per IRDAI-filed product (KI-133 / KI-141 / KI-142 / KI-145).** Aliases handle marketing renames (e.g. Reliance → IndusInd); sub-variants stay separate only when material terms differ. Card count is 166 across 19 real insurers — anything counting 138 or 188 or 206 against the marketplace is stale.- **`sales_brain.py` is the fact-find handler (KI-167, [ADR-039](70-docs/60-decisions/ADR-039-llm-driven-sales-brain.md); primary candidate is Google Gemini 2.0 Flash post-KI-179 / [ADR-040](70-docs/60-decisions/ADR-040-google-gemini-primary.md)).** `backend/fact_find_brain.py` is deleted along with the `<FF>` trailer convention, `_canonical_fallback`, scripted `Question.prompt_en`, and the `"Got that — {slot}."` prefix. Never re-introduce a fallback to scripted prompts on the fact-find branch — on total three-tier chain exhaustion the orchestrator returns a graceful error message (fail-loud > fail-silent-with-script). The KI-150 historical note (`fact_find_brain` `max_tokens` 420 → 700) is moot post-KI-167 since the prose+trailer prompt shape that needed the larger budget no longer exists.- **Never hardcode `NvidiaNimLLM(model=...)` post-KI-179** — chains now mix Google (`backend/providers/google_gemini_llm.py`), NIM (`backend/providers/nvidia_nim_llm.py`), and OpenRouter (`backend/providers/openrouter_llm.py`) candidates. Always go through `NimChainLLM(chain=...)` so the call surfs the full three-tier failover; bypassing the chain reintroduces the single-provider single-point-of-failure that KI-080 / KI-160 / KI-179 collectively eliminated.---*Last reviewed 2026-05-15 — KI-101..KI-112 landed (orchestrator stability + profile-RAG session isolation + recommendation closer + graceful chat error handling + Chroma re-ingest + profile-write hardening). Same day: KI-125..KI-150 landed (full corpus rebuild → 7,317 chunks; marketplace dedup → 166 cards; voice default OFF + VAD retune; IndusInd General slug migration from Reliance General). Same day: KI-160 / [ADR-038](70-docs/60-decisions/ADR-038-nim-only-chains.md) locked chains to NIM-only after KI-155's `<FF>` trailer contract violation. Same day: KI-167 / [ADR-039](70-docs/60-decisions/ADR-039-llm-driven-sales-brain.md) replaced `fact_find_brain.py` with `backend/sales_brain.py` (single LLM call per turn, native JSON mode, deterministic post-processor). Same day: KI-171 (judge skip on fact_find + recommendation), KI-175 (NIM chain reorder — nemotron demoted to last), KI-176 (OpenRouter `models: [...]` server-side fallback), KI-178 (live audit of OR free-tier JSON-mode support), KI-179 / [ADR-040](70-docs/60-decisions/ADR-040-google-gemini-primary.md) added Google AI Studio (Gemini 2.0 / 2.5 Flash) as the Tier 0 primary on Brain Fast + Brain Main, with NIM as Tier 1 fallback and OpenRouter as Tier 2 diversity pool. ADR-038 is now superseded — the NIM-only lock was relaxed once the `<FF>` trailer convention that motivated it was retired.*
63 unmodified lines6465666768697021 unmodified lines929394959697989910010110210310410510694 unmodified lines20120220320420520620720845 unmodified lines254255256257258259260261262113 unmodified lines37637737837938038138238338438538628 unmodified lines41541641741841942042142242311 unmodified lines43543643743843944044179 unmodified lines52152252352452552652752852953053153253353438 unmodified lines573574575576577578579580581582583584585586587588217 unmodified lines80680780880981081181281381463 unmodified lines- **KI-149** — budget + income parser captures bare numerals like `"30000"`.- **KI-150** — `fact_find_brain` `max_tokens` 420 → 700 (one of eight band-aids on the prose+`<FF>`-trailer prompt shape; superseded by KI-167).- **KI-160** — chains locked to NIM-only ([ADR-038](70-docs/60-decisions/ADR-038-nim-only-chains.md)) after KI-155 demonstrated Groq Llama-3.3 silently ignores the `<FF>` structured-output trailer contract.- **KI-167** — `backend/fact_find_brain.py` ripped out and replaced by `backend/sales_brain.py` ([ADR-039](70-docs/60-decisions/ADR-039-llm-driven-sales-brain.md)). Single LLM call per turn using NIM `response_format={"type":"json_object"}`; no scripted `Question.prompt_en`, no `<FF>` trailer, no `_canonical_fallback`, no `"Got that — {slot}."` prefix. Deterministic post-processor (`backend/sales_brain_normalizer.py`) normalizes captures; profile persists via `profile_store` + `profile_rag` as before.Per-insurer card counts (166 total across 19 real insurers): HDFC ERGO 15 · National Insurance 14 · Niva Bupa 14 · Bajaj Allianz 13 · ICICI Lombard 13 · Star Health 11 · Care Health 10 · New India Assurance 9 · Tata AIG 9 · Acko 7 · Aditya Birla 7 · Royal Sundaram 7 · Cholamandalam MS 6 · Go Digit 6 · IFFCO Tokio 6 · ManipalCigna 6 · SBI General 6 · IndusInd General 3 · Oriental Insurance 3 · Reliance General 1.21 unmodified lines2. **Hallucination defense and refusal as product features.** BFSI deployments get fined for mis-selling; the bot is biased toward refusal over confident wrong answers. The 4 faithfulness gates + cross-check retry + 3 Indic drift checks + audit log are the BFSI-compliance-grade version of "we shipped a chatbot." When the eval shows a headline accuracy below 100% because the gates are aggressive, the right response is to soften the gates carefully — not to ship a higher number by relaxing the verifier.3. **Honest model picks — Sarvam where Sarvam is uniquely strong, open-weights frontier for reasoning.** Voice and Indic are non-substitutable: **Sarvam Saarika v2.5** for speech-to-text, **Sarvam Bulbul v2** (speaker `anushka`) for text-to-speech, and **Sarvam-M** for Hindi/Hinglish/vernacular translation — no closed-source frontier matches Sarvam on Indian accents or code-mixed Hinglish. Reasoning is a different problem and runs on open-weights frontier models behind a NIM-only candidate pool per role (KI-160 / [ADR-038](70-docs/60-decisions/ADR-038-nim-only-chains.md)), not a single hardcoded brain. Each role is a `NimChainLLM` (`backend/providers/nvidia_nim_llm.py`) whose candidates are all NIM-hosted — KI-155 demonstrated that Groq Llama-3.3 silently ignores the `<FF>` structured-output trailer contract, so cross-provider fallback was removed as a silent-failure trap:- **`BRAIN_CHAIN`** (comparison, recommendation, synthesis) — primary **NVIDIA Nemotron-Super 49B v1.5** (`nvidia/llama-3.3-nemotron-super-49b-v1.5`), backup **Qwen 3-Next 80B** (`qwen/qwen3-next-80b-a3b-instruct`, 80B / 3B-active MoE), 3rd candidate **Mistral Large 3 675B** (`mistralai/mistral-large-3-675b-instruct-2512`).- **`FAST_BRAIN_CHAIN`** (sales-brain fact-find turns per KI-167, QA, normalize, extract — every latency-sensitive role) — primary **Qwen 3-Next 80B** (`qwen/qwen3-next-80b-a3b-instruct`), backup **NVIDIA Nemotron-Super 49B v1.5** (`nvidia/llama-3.3-nemotron-super-49b-v1.5`).- **`JUDGE_CHAIN`** (faithfulness Gate 4, Hinglish drift LLM-judge, eval grader) — primary **Meta Llama-4 Maverick 17B/128E** (`meta/llama-4-maverick-17b-128e-instruct`), backup **Mistral Large 3 675B** (`mistralai/mistral-large-3-675b-instruct-2512`). Deliberately different model families from the brain pool so the judge does not mark its own homework.**NIM-only election, no cross-provider cascade (KI-160, [ADR-038](70-docs/60-decisions/ADR-038-nim-only-chains.md)).** If every NIM candidate in a chain fails, orchestrator returns a graceful error message rather than falling to Groq or OpenRouter — fail-loud is preferred over fail-silent-with-garbage for structured-output contracts. The 50/50 NIM ↔ Groq rotation of KI-025 ([ADR-026](70-docs/60-decisions/ADR-026-provider-load-balancing.md)) and the cross-provider-fallback variant of KI-080 ([ADR-031](70-docs/60-decisions/ADR-031-sticky-primary-election.md)) are both superseded. KI-085's proactive credit gating still applies within the NIM pool via a per-model 60-second rate-meter (gate at 35-of-40 req/min, headroom 5). `GROQ_API_KEY` + `OPENROUTER_API_KEY` remain in HF Space secrets for future re-enable but the chain config no longer references them.The result: a Sarvam customer deploying this stack gets a product that *uses Sarvam exactly where Sarvam beats the world* and uses MIT-licensed open-weights frontier models for everything else — $0 inference, two independent free-tier providers, single-key-per-provider for the entire non-voice stack.The rest is craftsmanship. The 8-section KB ([`kb/`](kb/)) is regeneratable from primary sources in <40 minutes for <$2 cold. Every numeric value in every reviewer-facing artifact traces to a source PDF + page + clause. Every architectural decision is in [`70-docs/60-decisions/`](70-docs/60-decisions/) with alternatives and revisit-at-scale notes. Every production-readiness defect is in [`80-audit/ENTERPRISE_AUDIT.md`](80-audit/ENTERPRISE_AUDIT.md). The repo is structured so a new engineer joining on Monday could ship v1.1 by Friday.94 unmodified lines- `detect_language(user_text)` → `english / indic`- Indic cascade: if indic, Sarvam-M translates → English for reasoning, response translated back**Tech 4 — Fact-find branch (KI-167 / [ADR-039](70-docs/60-decisions/ADR-039-llm-driven-sales-brain.md))**- If profile empty AND intent ∈ {fact_find, recommendation, comparison}: hand the turn to `backend/sales_brain.py::drive_sales_brain()` — one NIM call with `response_format={"type":"json_object"}`, system prompt carries the 9-slot schema + current profile state. Response: `{reply, captures, slot_driving, complete}`. `backend/sales_brain_normalizer.py` normalizes captures → `session.update_profile_field()` → `profile_store.save_profile()` + `profile_rag.upsert_profile_chunk()`. Emit `reply` to the user.- Else: continue to retrieval</td></tr>45 unmodified lines</td><td>**Tech 7 — Brain selection, `pick_brain(intent, language)`**- `intent ∈ {comparison, recommendation}` → BRAIN_CHAIN with probe-elected primary within the [ADR-038](70-docs/60-decisions/ADR-038-nim-only-chains.md) NIM-only pool (KI-080 / KI-160)- `intent ∈ {qa, fact_find}` → FAST_BRAIN_CHAIN with probe-elected primary in the NIM-only pool (typically Qwen 3-Next 80B in steady state); `fact_find` turns go through `backend/sales_brain.py` with `response_format={"type":"json_object"}` (KI-167 / [ADR-039](70-docs/60-decisions/ADR-039-llm-driven-sales-brain.md))- KI-080 election: 1 LLM call per turn (most cases) or 2 (primary fails real-time → NIM-pool backup). Per-chain primary refreshed every 300s by background probe. On total NIM exhaustion: graceful error to user (fail-loud, [ADR-038](70-docs/60-decisions/ADR-038-nim-only-chains.md)).**Tech 8 — System prompt construction, `build_messages()`**- `[System: ADVISOR_PROMPT + USER PROFILE block + USER IS LOOKING AT (view_context) block]`113 unmodified lines│▼┌──────────────────────────────────────────────────────────────────────────┐│ TECH 4. Fact-find OR free-form branch (KI-167 / ADR-039) ││ ------- ││ · If intent ∈ {fact_find, recommendation, comparison} AND profile ││ incomplete: ││ drive_sales_brain() — one NIM call, response_format=json_object ││ → {reply, captures, slot_driving, complete} ││ normalize captures → session.update_profile_field() ││ → profile_store.save_profile() + profile_rag.upsert_profile_chunk() │28 unmodified lines┌──────────────────────────────────────────────────────────────────────────┐│ TECH 7. Brain selection — pick_brain(intent, language) ││ ------- ││ · intent ∈ {comparison, recommendation} → BRAIN_CHAIN with probe-elected primary in NIM-only pool (heavy, KI-080 / KI-160 / ADR-038)││ · intent ∈ {qa, fact_find} → FAST_BRAIN_CHAIN; fact_find turns dispatched to sales_brain.py (KI-167 / ADR-039, JSON mode) ││ · NIM Qwen 80B + Nemotron-Super 49B as fast-brain election candidates (NIM-only post-KI-160) │└──────────────────────────────────────────────────────────────────────────┘│▼11 unmodified lines┌──────────────────────────────────────────────────────────────────────────┐│ TECH 9. Brain LLM call → reply text ││ ------- ││ · NIM streaming chat call (V4-Pro or V4-Flash) ││ · strip_think_tags() removes <think>…</think> chain-of-thought ││ · Capture brain_model_actual for non-circular judge selection │└──────────────────────────────────────────────────────────────────────────┘79 unmodified lines│ ┌───────────────────────┼──────────────────────────┐ ││ ▼ ▼ ▼ ││ ┌──────────────┐ ┌──────────────────┐ ┌──────────────────────┐ ││ │ STRUCTURED │ │ VECTOR STORE │ │ NIM BRAIN ROUTER │ ││ │ DuckDB │ │ Chroma 0.5.20 │ │ V4-Pro (heavy) │ ││ │ 62 fields │ │ BGE-small (384d) │ │ V4-Flash (fast) │ ││ │ per policy │ │ 800/120 chunk │ │ Mistral Large 3 675B │ ││ └──────────────┘ │ +profile chunk │ │ (judge + xcheck │ ││ │ per session │ │ + Indic gates) │ ││ └──────────────────┘ │ single NIM key │ ││ │ 40 req/min · $0 │ ││ └──────────────────────┘ │└─────────────────────────────────────────────────────────────────────────┘│38 unmodified lines### 4.3 Model stackEvery LLM role is served by a **candidate pool** of models elected over by a probe-driven sticky-primary scheme ([ADR-031](70-docs/60-decisions/ADR-031-sticky-primary-election.md), end-to-end spec in [ADR-032](70-docs/60-decisions/ADR-032-llm-chain-architecture.md)), never a hardcoded single model. Chains were curated to preserve brain ↔ judge family diversity (Qwen brain ↔ Mistral judge) so any failover still produces non-circular grading. Cross-provider entries (OpenRouter, Groq) sit inside every chain so the whole reasoning stack survives a full NIM regional outage.| Role | Primary | Fallback chain (in order) | Provider(s) | Why this primary ||---|---|---|---|---|| **Heavy brain** (comparison, recommendation, synthesis) | Probe-elected primary (KI-080) — typically Qwen 3-Next 80B or Groq Llama-3.3-70B in steady state | Qwen 3.5 122B → GPT-OSS 120B → Mistral Large 3 675B → Nemotron-Super 49B → Llama-3.3-70B → DeepSeek V4-Pro → OpenRouter GPT-OSS 120B → Groq Llama-3.3-70B (all as election candidates; probe scores them every 60s) | NIM + Groq + OpenRouter | Probe-driven election picks the actually-faster candidate dynamically (latency × success-rate score), with provider-diverse BACKUP. Pre-KI-080 static 50/50 ([ADR-026](70-docs/60-decisions/ADR-026-provider-load-balancing.md)) was deprecated in favour of [ADR-031](70-docs/60-decisions/ADR-031-sticky-primary-election.md). || **Fast brain** (voice turns, sales-brain fact-find KI-167, QA, normalize, extract) | Probe-elected primary within the [ADR-038](70-docs/60-decisions/ADR-038-nim-only-chains.md) NIM-only pool — typically Qwen 3-Next 80B in steady state | Qwen 3-Next 80B → NVIDIA Nemotron-Super 49B v1.5 (NIM-only election candidates) | NIM | Bottleneck on these short jobs is TTFT, not capability. Sales brain (KI-167) calls this chain with `response_format={"type":"json_object"}` for guaranteed structured output. Election adapts within the NIM pool when one candidate degrades. || **Judge** (faithfulness Gate 4, Hinglish drift, eval grader) | Mistral Large 3 675B | GPT-OSS 120B → Kimi K2 → MiniMax M2.5 → Llama-4 Maverick 17B/128E → OpenRouter GPT-OSS 120B → Groq Llama-3.3-70B | NIM + OpenRouter + Groq | Different family from the Qwen brain (Mistral, not Qwen / DeepSeek / Llama family) so the judge sees the brain's output from a genuinely different decision surface. 675B dense, MIT, ~4.3s on NIM. || **Profile extractor** (free-form profile updates → 9-slot schema, ADR-022) | Fast brain chain (Nemotron Nano 30B primary) | inherits FAST_BRAIN_CHAIN | NIM + Groq | Short prompt, structured JSON out — Nemotron Nano is fast and reliable enough; same chain as fact-find. || **Fact-find normalizer** (user answer → typed slot value) | Fast brain chain (Nemotron Nano 30B primary) | inherits FAST_BRAIN_CHAIN | NIM + Groq | Same shape as profile extractor — narrow input, narrow JSON output. || **Sales brain** (fact-find conversation driver — KI-167 / [ADR-039](70-docs/60-decisions/ADR-039-llm-driven-sales-brain.md)) | Fast brain chain (Qwen 3-Next 80B primary in NIM-only pool) | inherits FAST_BRAIN_CHAIN | NIM | One NIM call per turn using `response_format={"type":"json_object"}`. System prompt carries the 9-slot schema + current profile state; LLM owns voice + flow + slot order, returns `{reply, captures, slot_driving, complete}`. Replaces the scripted-`prompt_en` + paraphraser + opener-rotation + `<FF>` trailer + `_canonical_fallback` machinery (ADR-027 / ADR-030 retired). || **Indic translation** (English ↔ Hindi / Hinglish / vernacular) | Sarvam-M | — (no fallback; Indic is non-substitutable) | Sarvam | Best-in-class on Hinglish and code-mixed Indian languages; no open-weights frontier model is competitive here. || **STT** (speech-to-text) | Sarvam Saarika v2.5 (`saarika:v2.5`) | — | Sarvam | Best-in-class on Indian-accented English and Hinglish; WebM transcoded to 16kHz mono WAV at the gateway (`backend/providers/sarvam_stt.py`). || **TTS** (text-to-speech) | Sarvam Bulbul v2 (`bulbul:v2`, speaker `anushka`) | — | Sarvam | Best-in-class on Hinglish prosody; 22.05kHz output, base64 WAV from Sarvam endpoint. |217 unmodified lines```bashcp .env.example .env# Edit .env and fill in the 8 keys (see 70-docs/60-decisions/ADR-010-secret-handling.md):# SARVAM_API_KEY, VOYAGE_API_KEY, NVIDIA_NIM_API_KEY, HF_TOKEN,# ADMIN_PASSWORD, ADMIN_IP_ALLOWLIST, GROQ_API_KEY, OPENROUTER_API_KEYchmod 600 .env```63 unmodified lines646566676869707172737421 unmodified lines9697989910010110210310410510610710810911094 unmodified lines20520620720820921021121245 unmodified lines258259260261262263264265266113 unmodified lines38038138238338438538638738838939039139228 unmodified lines42142242342442542642742842943043143243343411 unmodified lines44644744844945045145279 unmodified lines53253353453553653753853954054154254354454554654754854938 unmodified lines588589590591592593594595596597598599600601602603217 unmodified lines82182282382482582682782882983083183283383483563 unmodified lines- **KI-149** — budget + income parser captures bare numerals like `"30000"`.- **KI-150** — `fact_find_brain` `max_tokens` 420 → 700 (one of eight band-aids on the prose+`<FF>`-trailer prompt shape; superseded by KI-167).- **KI-160** — chains locked to NIM-only ([ADR-038](70-docs/60-decisions/ADR-038-nim-only-chains.md)) after KI-155 demonstrated Groq Llama-3.3 silently ignores the `<FF>` structured-output trailer contract.- **KI-167** — `backend/fact_find_brain.py` ripped out and replaced by `backend/sales_brain.py` ([ADR-039](70-docs/60-decisions/ADR-039-llm-driven-sales-brain.md)). Single LLM call per turn using native JSON mode; no scripted `Question.prompt_en`, no `<FF>` trailer, no `_canonical_fallback`, no `"Got that — {slot}."` prefix. Deterministic post-processor (`backend/sales_brain_normalizer.py`) normalizes captures; profile persists via `profile_store` + `profile_rag` as before.- **KI-171** — orchestrator skips the Judge chain on `fact_find` + `recommendation` queries (faithfulness scoring is meaningless on profile-capture turns and on multi-policy ranked shortlists where the rubric is structural, not factual grounding).- **KI-175** — NIM chain reorder: Mistral Large 3 675B promoted to primary, nemotron-49b demoted to last resort across all three chains. The old "nemotron primary" ordering predated the 675B model's availability.- **KI-176** — OpenRouter re-added to the chain pool with `models: [...]` server-side fallback within the OR free pool. KI-178 live-audit then confirmed which OR free-tier models actually support `response_format` (nemotron-3-super-120b, qwen3-next-80b, gemma-4 — not Llama 3.3 70B or Hermes 3 405B).- **KI-179** — Google AI Studio added as Tier 0 primary on Brain Fast + Brain Main ([ADR-040](70-docs/60-decisions/ADR-040-google-gemini-primary.md)). `backend/providers/google_gemini_llm.py` wrapper matches the `LLMProvider` interface; chains now span {Google → NIM → OpenRouter}. ADR-038 (NIM-only lock) is superseded — the lock was relaxed once KI-167 retired the `<FF>` trailer convention that originally motivated it. Brain Fast primary is `gemini-2.0-flash`; Brain Main primary is `gemini-2.5-flash`; Judge stays NIM Mistral Large 3 675B (different family from Gemini, preserving the brain ↔ judge non-circular grading invariant). Google's free tier: 1500 req/day, 15 req/min, native JSON via `response_mime_type=application/json`.Per-insurer card counts (166 total across 19 real insurers): HDFC ERGO 15 · National Insurance 14 · Niva Bupa 14 · Bajaj Allianz 13 · ICICI Lombard 13 · Star Health 11 · Care Health 10 · New India Assurance 9 · Tata AIG 9 · Acko 7 · Aditya Birla 7 · Royal Sundaram 7 · Cholamandalam MS 6 · Go Digit 6 · IFFCO Tokio 6 · ManipalCigna 6 · SBI General 6 · IndusInd General 3 · Oriental Insurance 3 · Reliance General 1.21 unmodified lines2. **Hallucination defense and refusal as product features.** BFSI deployments get fined for mis-selling; the bot is biased toward refusal over confident wrong answers. The 4 faithfulness gates + cross-check retry + 3 Indic drift checks + audit log are the BFSI-compliance-grade version of "we shipped a chatbot." When the eval shows a headline accuracy below 100% because the gates are aggressive, the right response is to soften the gates carefully — not to ship a higher number by relaxing the verifier.3. **Honest model picks — Sarvam where Sarvam is uniquely strong, frontier-tier free brains for reasoning.** Voice and Indic are non-substitutable: **Sarvam Saarika v2.5** for speech-to-text, **Sarvam Bulbul v2** (speaker `anushka`) for text-to-speech, and **Sarvam-M** for Hindi/Hinglish/vernacular translation — no closed-source frontier matches Sarvam on Indian accents or code-mixed Hinglish. Reasoning runs on a three-tier candidate pool per role (KI-179 / [ADR-040](70-docs/60-decisions/ADR-040-google-gemini-primary.md)), not a single hardcoded brain. Every candidate supports native JSON mode server-side — Google's `response_mime_type=application/json`, NIM's `response_format={"type":"json_object"}`, OpenRouter's `response_format` pass-through on the audited free-tier models (KI-178). Cross-provider fallback is safe again now that the `<FF>` trailer convention that triggered KI-160 / ADR-038's NIM-only lock has been retired by KI-167 / [ADR-039](70-docs/60-decisions/ADR-039-llm-driven-sales-brain.md):- **Brain Main** (comparison, recommendation, synthesis) — primary **Google `gemini-2.5-flash`** via Google AI Studio (1500 req/day free, native JSON mode), Tier 1 fallback **NIM Mistral Large 3 675B** (`mistralai/mistral-large-3-675b-instruct-2512`), then **NIM Llama-4 Maverick 17B/128E**, then **NIM Qwen 3-Next 80B**, then **OpenRouter `nvidia/nemotron-3-super-120b-a12b:free`**, last resort **NIM Nemotron-Super 49B v1.5**.- **Brain Fast** (sales-brain fact-find turns per KI-167, fast QA) — primary **Google `gemini-2.0-flash`**, Tier 1 fallback **NIM Qwen 3-Next 80B**, then **NIM Mistral Large 3 675B**, then **NIM Llama-4 Maverick 17B/128E**, then **OpenRouter `nvidia/nemotron-3-super-120b-a12b:free`** + `qwen/qwen3-next-80b-a3b-instruct:free`, last resort **NIM Nemotron-Super 49B v1.5**.- **Judge** (faithfulness Gate 4, Hinglish drift LLM-judge, eval grader; KI-171 skips this on `fact_find` + `recommendation` queries) — primary **NIM Mistral Large 3 675B** (different family from the Gemini brain — preserves cross-family non-circular grading), Tier 1 fallback **NIM Llama-4 Maverick 17B/128E**, then **OpenRouter `qwen/qwen3-next-80b-a3b-instruct:free`**, last resort **NIM Nemotron-Super 49B v1.5**.**Three-tier election (KI-179, [ADR-040](70-docs/60-decisions/ADR-040-google-gemini-primary.md)).** Google → NIM → OpenRouter, with the chain falling through naturally when an upper tier 429s, exhausts quota, or fails real-time. On total chain exhaustion the orchestrator returns a graceful error message — fail-loud > fail-silent-with-garbage is preserved. The 50/50 NIM ↔ Groq rotation of KI-025 ([ADR-026](70-docs/60-decisions/ADR-026-provider-load-balancing.md)) and the NIM-only lock of KI-160 ([ADR-038](70-docs/60-decisions/ADR-038-nim-only-chains.md)) are both superseded. KI-085's proactive credit gating applies per-candidate (60-second rate-meter, gate at 35-of-40 req/min). `GROQ_API_KEY` remains in HF Space secrets but is dormant — no chain references it.The result: a Sarvam customer deploying this stack gets a product that *uses Sarvam exactly where Sarvam beats the world*, uses **Google Gemini Flash on the free path for frontier-tier conversational quality**, and uses MIT-licensed open-weights frontier models (Mistral Large 3 675B, Llama-4 Maverick, Qwen 3-Next 80B, Nemotron-Super 49B) for everything else — $0 inference, three independent free-tier providers, single-key-per-provider for the entire non-voice stack.The rest is craftsmanship. The 8-section KB ([`kb/`](kb/)) is regeneratable from primary sources in <40 minutes for <$2 cold. Every numeric value in every reviewer-facing artifact traces to a source PDF + page + clause. Every architectural decision is in [`70-docs/60-decisions/`](70-docs/60-decisions/) with alternatives and revisit-at-scale notes. Every production-readiness defect is in [`80-audit/ENTERPRISE_AUDIT.md`](80-audit/ENTERPRISE_AUDIT.md). The repo is structured so a new engineer joining on Monday could ship v1.1 by Friday.94 unmodified lines- `detect_language(user_text)` → `english / indic`- Indic cascade: if indic, Sarvam-M translates → English for reasoning, response translated back**Tech 4 — Fact-find branch (KI-167 / [ADR-039](70-docs/60-decisions/ADR-039-llm-driven-sales-brain.md); primary candidate is Google Gemini 2.0 Flash post-KI-179 / [ADR-040](70-docs/60-decisions/ADR-040-google-gemini-primary.md))**- If profile empty AND intent ∈ {fact_find, recommendation, comparison}: hand the turn to `backend/sales_brain.py::drive_sales_brain()` — one LLM call against the Brain Fast chain (Google `gemini-2.0-flash` primary → NIM Qwen / Mistral 675B / Llama-4 Maverick → OpenRouter free → NIM Nemotron-49b last resort) using native JSON mode (`response_mime_type=application/json` on Gemini, `response_format={"type":"json_object"}` on NIM / OR). System prompt carries the 9-slot schema + current profile state. Response: `{reply, captures, slot_driving, complete}`. `backend/sales_brain_normalizer.py` normalizes captures → `session.update_profile_field()` → `profile_store.save_profile()` + `profile_rag.upsert_profile_chunk()`. Emit `reply` to the user.- Else: continue to retrieval</td></tr>45 unmodified lines</td><td>**Tech 7 — Brain selection, `pick_brain(intent, language)`**- `intent ∈ {comparison, recommendation}` → Brain Main chain with probe-elected primary across the three-tier pool ([ADR-040](70-docs/60-decisions/ADR-040-google-gemini-primary.md)): Google `gemini-2.5-flash` → NIM Mistral Large 3 675B → NIM Llama-4 Maverick → NIM Qwen 3-Next 80B → OpenRouter `nemotron-3-super-120b:free` → NIM Nemotron-49b- `intent ∈ {qa, fact_find}` → Brain Fast chain: Google `gemini-2.0-flash` → NIM Qwen → NIM Mistral 675B → NIM Llama-4 Maverick → OpenRouter free pool → NIM Nemotron-49b. `fact_find` turns go through `backend/sales_brain.py` with native JSON mode (KI-167 / [ADR-039](70-docs/60-decisions/ADR-039-llm-driven-sales-brain.md))- KI-080 election: 1 LLM call per turn (most cases) or 2 (primary fails real-time → next tier). Per-chain primary refreshed every 300s by background probe. On total three-tier exhaustion: graceful error to user (fail-loud — KI-179 preserves the [ADR-038](70-docs/60-decisions/ADR-038-nim-only-chains.md) principle even though the NIM-only candidate-pool scope is superseded).**Tech 8 — System prompt construction, `build_messages()`**- `[System: ADVISOR_PROMPT + USER PROFILE block + USER IS LOOKING AT (view_context) block]`113 unmodified lines│▼┌──────────────────────────────────────────────────────────────────────────┐│ TECH 4. Fact-find OR free-form branch (KI-167 / ADR-039 / ADR-040) ││ ------- ││ · If intent ∈ {fact_find, recommendation, comparison} AND profile ││ incomplete: ││ drive_sales_brain() — one LLM call against Brain Fast chain ││ (Gemini 2.0 Flash → NIM Qwen / Mistral 675B → OR free) ││ using native JSON mode (response_mime_type / response_format) ││ → {reply, captures, slot_driving, complete} ││ normalize captures → session.update_profile_field() ││ → profile_store.save_profile() + profile_rag.upsert_profile_chunk() │28 unmodified lines┌──────────────────────────────────────────────────────────────────────────┐│ TECH 7. Brain selection — pick_brain(intent, language) ││ ------- ││ · intent ∈ {comparison, recommendation} → Brain Main chain ││ Gemini 2.5 Flash → NIM Mistral 675B → NIM Llama-4 Maverick → ││ NIM Qwen 80B → OR nemotron-3-super-120b:free → NIM Nemotron-49b ││ · intent ∈ {qa, fact_find} → Brain Fast chain ││ Gemini 2.0 Flash → NIM Qwen 80B → NIM Mistral 675B → NIM Llama-4 → ││ OR free pool → NIM Nemotron-49b last resort ││ · fact_find turns dispatched to sales_brain.py (KI-167 / ADR-039) ││ · Three-tier election: Google → NIM → OpenRouter (KI-179 / ADR-040) │└──────────────────────────────────────────────────────────────────────────┘│▼11 unmodified lines┌──────────────────────────────────────────────────────────────────────────┐│ TECH 9. Brain LLM call → reply text ││ ------- ││ · Provider-agnostic chat call via NimChainLLM (Google / NIM / OR) ││ · strip_think_tags() removes <think>…</think> chain-of-thought ││ · Capture brain_model_actual for non-circular judge selection │└──────────────────────────────────────────────────────────────────────────┘79 unmodified lines│ ┌───────────────────────┼──────────────────────────┐ ││ ▼ ▼ ▼ ││ ┌──────────────┐ ┌──────────────────┐ ┌──────────────────────┐ ││ │ STRUCTURED │ │ VECTOR STORE │ │ 3-TIER BRAIN ROUTER │ ││ │ DuckDB │ │ Chroma 0.5.20 │ │ Tier 0: Google AI │ ││ │ 62 fields │ │ BGE-small (384d) │ │ Studio (Gemini │ ││ │ per policy │ │ 800/120 chunk │ │ 2.0 / 2.5 Flash) │ ││ └──────────────┘ │ +profile chunk │ │ Tier 1: NIM (Mistral │ ││ │ per session │ │ 675B, Llama-4, │ ││ └──────────────────┘ │ Qwen 80B, Nemo-49) │ ││ │ Tier 2: OR free pool │ ││ │ (nemotron-120b, │ ││ │ qwen-80b:free) │ ││ │ KI-179 / ADR-040 │ ││ │ $0 inference path │ ││ └──────────────────────┘ │└─────────────────────────────────────────────────────────────────────────┘│38 unmodified lines### 4.3 Model stackEvery LLM role is served by a **three-tier candidate pool** elected over by a probe-driven sticky-primary scheme ([ADR-031](70-docs/60-decisions/ADR-031-sticky-primary-election.md), end-to-end spec in [ADR-032](70-docs/60-decisions/ADR-032-llm-chain-architecture.md), current candidate-pool shape in [ADR-040](70-docs/60-decisions/ADR-040-google-gemini-primary.md)), never a hardcoded single model. Chains preserve brain ↔ judge family diversity (Gemini brain ↔ Mistral judge) so any failover still produces non-circular grading. Tier 0 (Google AI Studio) is the steady-state primary; Tier 1 (NIM) is the fallback; Tier 2 (OpenRouter free pool) is the diversity tail before the last-resort NIM Nemotron-49b. Every candidate enforces native JSON mode server-side — `response_mime_type=application/json` on Google, `response_format={"type":"json_object"}` on NIM and on the audited OR free-tier models (KI-178).| Role | Primary | Fallback chain (in order) | Provider(s) | Why this primary ||---|---|---|---|---|| **Brain Main** (comparison, recommendation, synthesis) | **Google `gemini-2.5-flash`** (1500 req/day free, native JSON mode) | NIM Mistral Large 3 675B → NIM Llama-4 Maverick 17B/128E → NIM Qwen 3-Next 80B → OpenRouter `nvidia/nemotron-3-super-120b-a12b:free` → NIM Nemotron-Super 49B v1.5 (last resort) | Google + NIM + OpenRouter | Best-in-class conversational + synthesis quality on the free path; 1500 req/day adequate for demo + early production. NIM Mistral 675B Tier 1 fallback preserves dense 675B reasoning when Google quota / 429 trips. KI-179 / [ADR-040](70-docs/60-decisions/ADR-040-google-gemini-primary.md). || **Brain Fast** (voice turns, sales-brain fact-find KI-167, QA) | **Google `gemini-2.0-flash`** (same 1500 req/day quota, lower-latency tier for fast turns) | NIM Qwen 3-Next 80B → NIM Mistral Large 3 675B → NIM Llama-4 Maverick → OpenRouter `nemotron-3-super-120b:free` + `qwen3-next-80b:free` → NIM Nemotron-Super 49B v1.5 (last resort) | Google + NIM + OpenRouter | Bottleneck on these short jobs is TTFT — Gemini 2.0 Flash optimised for low-latency JSON. Sales brain (KI-167) calls this chain with native JSON mode for guaranteed structured output. KI-179 / [ADR-040](70-docs/60-decisions/ADR-040-google-gemini-primary.md). || **Judge** (faithfulness Gate 4, Hinglish drift, eval grader; KI-171 skips on `fact_find` + `recommendation`) | **NIM Mistral Large 3 675B** (`mistralai/mistral-large-3-675b-instruct-2512`) | NIM Llama-4 Maverick 17B/128E → OpenRouter `qwen/qwen3-next-80b-a3b-instruct:free` → NIM Nemotron-Super 49B v1.5 | NIM + OpenRouter | Different family from the Gemini brain (Mistral, not Google / Llama / Qwen) so the judge sees the brain's output from a genuinely different decision surface. 675B dense, MIT, ~4.3s on NIM. Brain ↔ judge family diversity is the structural defence against circular grading. || **Profile extractor** (free-form profile updates → 9-slot schema, ADR-022) | Brain Fast chain (Gemini 2.0 Flash primary) | inherits Brain Fast chain | Google + NIM + OpenRouter | Short prompt, structured JSON out — same chain as sales brain. || **Fact-find normalizer** (user answer → typed slot value) | Brain Fast chain (Gemini 2.0 Flash primary) | inherits Brain Fast chain | Google + NIM + OpenRouter | Same shape as profile extractor — narrow input, narrow JSON output. || **Sales brain** (fact-find conversation driver — KI-167 / [ADR-039](70-docs/60-decisions/ADR-039-llm-driven-sales-brain.md), KI-179 / [ADR-040](70-docs/60-decisions/ADR-040-google-gemini-primary.md)) | Brain Fast chain (Gemini 2.0 Flash primary) | inherits Brain Fast chain | Google + NIM + OpenRouter | One LLM call per turn using native JSON mode. System prompt carries the 9-slot schema + current profile state; LLM owns voice + flow + slot order, returns `{reply, captures, slot_driving, complete}`. Replaces the scripted-`prompt_en` + paraphraser + opener-rotation + `<FF>` trailer + `_canonical_fallback` machinery (ADR-027 / ADR-030 retired). || **Indic translation** (English ↔ Hindi / Hinglish / vernacular) | Sarvam-M | — (no fallback; Indic is non-substitutable) | Sarvam | Best-in-class on Hinglish and code-mixed Indian languages; no open-weights frontier model is competitive here. || **STT** (speech-to-text) | Sarvam Saarika v2.5 (`saarika:v2.5`) | — | Sarvam | Best-in-class on Indian-accented English and Hinglish; WebM transcoded to 16kHz mono WAV at the gateway (`backend/providers/sarvam_stt.py`). || **TTS** (text-to-speech) | Sarvam Bulbul v2 (`bulbul:v2`, speaker `anushka`) | — | Sarvam | Best-in-class on Hinglish prosody; 22.05kHz output, base64 WAV from Sarvam endpoint. |217 unmodified lines```bashcp .env.example .env# Edit .env and fill in the keys (see 70-docs/60-decisions/ADR-010-secret-handling.md):# GOOGLE_API_KEY — Tier 0 brain (Gemini 2.0/2.5 Flash, KI-179 / ADR-040)# NVIDIA_NIM_API_KEY — Tier 1 brain fallback + Judge primary# OPENROUTER_API_KEY — Tier 2 diversity pool (free-tier OR models)# SARVAM_API_KEY — STT / TTS / Indic translation (non-substitutable)# VOYAGE_API_KEY — offline ingest embeddings only (BGE on hot path)# HF_TOKEN — data-dataset pull at boot# ADMIN_PASSWORD — /api/admin/* gating (post-KI-097, password-only)# GROQ_API_KEY — DORMANT (no chain references it post-KI-160)chmod 600 .env```
13 unmodified lines14151617181920212212 unmodified lines3536373839404113 unmodified lines| File | Role | Related ADR || --- | --- | --- || `needs_finder.py` | 9-slot fact-find schema (`GRAPH`) + canonical question prompts. Post-KI-070 used as **safeguard fallback only** — primary path is `fact_find_brain.py::drive_fact_find` (single LLM call per turn). | [ADR-030](../70-docs/60-decisions/ADR-030-llm-driven-fact-find.md) || `fact_find_brain.py` | KI-070 single-LLM-call fact-find driver. One brain call per turn produces natural prose + `<FF>{...}</FF>` JSON tail (captured slots + next slot + complete flag). KI-090 made the tail parser lenient (strict / fenced / bare-JSON-tail). | [ADR-030](../70-docs/60-decisions/ADR-030-llm-driven-fact-find.md), [ADR-032](../70-docs/60-decisions/ADR-032-llm-chain-architecture.md) || ~~`question_paraphraser.py`~~ *(deleted in KI-070)* | Was an LLM rewrite of canonical slot questions (ADR-027). Superseded by `fact_find_brain.py`'s single-call architecture. | superseded by [ADR-030](../70-docs/60-decisions/ADR-030-llm-driven-fact-find.md) || `fact_find_normalizer.py` | LLM-driven free-text → slot-value coercion (e.g. "32 lakh" → `3200000`). Goes through `NimChainLLM`, not a single client (KI-033). | — || `profile_extractor.py` | LLM extractor that pulls profile updates out of conversational asides ("by the way, my dad has diabetes"). Chain-pattern, never a hardcoded model. | [ADR-022](../70-docs/60-decisions/ADR-022-conversational-profile-updates.md) || `profile_store.py` | **NEW (KI-040).** Persistent named-profile JSON store under `40-data/profiles/`. O(1) name-keyed lookup; mirrors into `profile_rag` on every save. | — |12 unmodified lines## Subdirectory`providers/` — concrete STT / TTS / LLM / embeddings client implementations. All LLM access goes through `NimChainLLM(chain=...)` from `providers/nvidia_nim_llm.py` — never instantiate a single-provider client directly. See `backend/providers/README.md`.## Where to read for what13 unmodified lines141516171819202122232412 unmodified lines37383940414243444546474849505113 unmodified lines| File | Role | Related ADR || --- | --- | --- || `needs_finder.py` | 9-slot fact-find SCHEMA (`GRAPH`). Post-KI-167 the `prompt_en` / `prompt_hi` strings are dead text — the LLM owns voice + cadence end-to-end via its system prompt. The data structure is retained as the schema source for `sales_brain.py`. | [ADR-039](../70-docs/60-decisions/ADR-039-llm-driven-sales-brain.md), [ADR-040](../70-docs/60-decisions/ADR-040-google-gemini-primary.md) || `sales_brain.py` | **KI-167 LLM-driven fact-find driver.** One brain call per turn against `FAST_BRAIN_CHAIN` (Gemini 2.0 Flash primary) using native provider JSON mode (`response_mime_type=application/json` on Gemini, `response_format={"type":"json_object"}` on NIM / OpenRouter). Returns `{reply, captures, slot_driving, complete}`. No `<FF>` trailer, no scripted fallback. | [ADR-039](../70-docs/60-decisions/ADR-039-llm-driven-sales-brain.md), [ADR-040](../70-docs/60-decisions/ADR-040-google-gemini-primary.md) || `sales_brain_normalizer.py` | **KI-167 deterministic post-processor.** Pure-rule mapping of the LLM's loose `captures` dict to canonical `{field: validated_value}`: alias resolution (`location` → `location_tier`), enum coercion (`Bangalore` → `metro`), INR parsing, type / bounds validation, KI-094 null-drop. No LLM calls. | [ADR-039](../70-docs/60-decisions/ADR-039-llm-driven-sales-brain.md) || ~~`fact_find_brain.py`~~ *(deleted in KI-167)* | Was the ADR-030 one-call brain with `<FF>...</FF>` trailer convention + `_canonical_fallback`. Removed entirely. | superseded by [ADR-039](../70-docs/60-decisions/ADR-039-llm-driven-sales-brain.md) || ~~`question_paraphraser.py`~~ *(deleted in KI-070)* | Was an LLM rewrite of canonical slot questions (ADR-027). Superseded first by `fact_find_brain.py`, now by `sales_brain.py`. | superseded by [ADR-039](../70-docs/60-decisions/ADR-039-llm-driven-sales-brain.md) || `fact_find_normalizer.py` | LLM-driven free-text → slot-value coercion (e.g. "32 lakh" → `3200000`). Goes through `NimChainLLM`, not a single client (KI-033). | — || `profile_extractor.py` | LLM extractor that pulls profile updates out of conversational asides ("by the way, my dad has diabetes"). Chain-pattern, never a hardcoded model. | [ADR-022](../70-docs/60-decisions/ADR-022-conversational-profile-updates.md) || `profile_store.py` | **NEW (KI-040).** Persistent named-profile JSON store under `40-data/profiles/`. O(1) name-keyed lookup; mirrors into `profile_rag` on every save. | — |12 unmodified lines## Subdirectory`providers/` — concrete STT / TTS / LLM / embeddings client implementations:- `sarvam_stt.py` / `sarvam_tts.py` — Sarvam Saarika v2.5 + Bulbul v2.- `google_gemini_llm.py` — Google AI Studio (`gemini-2.0-flash`, `gemini-2.5-flash`); Tier 0 primary on Brain Fast + Brain Main ([ADR-040](../70-docs/60-decisions/ADR-040-google-gemini-primary.md)).- `nvidia_nim_llm.py` — NIM client + `NimChainLLM` dispatcher (the elector + cross-provider BACKUP machinery from KI-080). Tier 1 fallback across all chains; judge primary stays on NIM Mistral Large 3 675B.- `openrouter_llm.py` — OpenRouter client; Tier 2 cross-provider diversity using OR's `models: [...]` server-side fallback (KI-176).- `local_embeddings.py` — BGE-small-en-v1.5 sentence-transformers.All LLM access goes through `NimChainLLM(chain=...)` — never instantiate a single-provider client directly. See `backend/providers/README.md`.## Where to read for what
27 unmodified lines282930313233263 unmodified lines2972982993003013023033043053063073082 unmodified lines31131231331431531631731827 unmodified linesget_brain_llm,get_fast_brain_llm,)from rag.retrieve import RetrievedChunk, format_for_llm_context, retrieve263 unmodified linesdef pick_brain(intent: str, language: str) -> BrainPick:"""Route to the reasoning brain per D-019 (2026-05-14, tiered routing).All routes go through NVIDIA NIM (single provider, $0 cost). Tier pickedby intent classification:- 'comparison' / 'recommendation' → DeepSeek-V4-Pro (1.6T/49B MoE)Heavy synthesis, multi-policy reasoning. Quality > latency.- 'fact_find' / 'qa' → DeepSeek-V4-Flash (284B/13B MoE)Single-turn voice responses. Latency > quality, still frontier-tier.Indic queries get a Sarvam-M translation pass in `handle_turn` beforeretrieval, then another after reasoning to convert the English reply back2 unmodified lines"""HEAVY_INTENTS = {"comparison", "recommendation"}if intent in HEAVY_INTENTS:return BrainPick(get_brain_llm(), f"v4-pro::{intent}")return BrainPick(get_fast_brain_llm(), f"v4-flash::{intent}")# ---------- welcome-back greeting helpers ----------27 unmodified lines28293031323334263 unmodified lines2982993003013023033043053063073083093103113122 unmodified lines31531631731831932032132227 unmodified linesget_brain_llm,get_fast_brain_llm,)from backend.providers.tiered_brain_llm import get_tiered_brain_llmfrom rag.retrieve import RetrievedChunk, format_for_llm_context, retrieve263 unmodified linesdef pick_brain(intent: str, language: str) -> BrainPick:"""Route to the reasoning brain per D-019 (2026-05-14, tiered routing).KI-179 (2026-05-15) — every route now goes through a 3-tier wrapper(TieredBrainLLM) that prefers Google Gemini Flash, falls back to NIM,then OpenRouter free-tier. The intent-based heavy vs fast split ispreserved at the wrapper level — heavy intents get `gemini-2.5-flash`+ BRAIN_CHAIN, light intents get `gemini-2.0-flash` + FAST_BRAIN_CHAIN.Original D-019 design (kept for context):- 'comparison' / 'recommendation' → heavy brain (quality > latency)- 'fact_find' / 'qa' → fast brain (latency > quality)Indic queries get a Sarvam-M translation pass in `handle_turn` beforeretrieval, then another after reasoning to convert the English reply back2 unmodified lines"""HEAVY_INTENTS = {"comparison", "recommendation"}if intent in HEAVY_INTENTS:return BrainPick(get_tiered_brain_llm(role="brain"), f"v4-pro::{intent}")return BrainPick(get_tiered_brain_llm(role="fast_brain"), f"v4-flash::{intent}")# ---------- welcome-back greeting helpers ----------
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233"""Google Gemini — primary LLM tier for sales_brain + orchestrator brain (KI-179).
Google AI Studio's free tier on `gemini-2.0-flash` and `gemini-2.5-flash` gives1500 req/day with native JSON mode (`responseMimeType: "application/json"`).This is best-in-class free quality for conversation and beats every model inNIM or OpenRouter free tiers.
Wire-shape: REST API direct via httpx (no SDK dependency — matches the patternof nvidia_nim_llm.py and openrouter_llm.py).
Endpoint: POST https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={api_key}
Request body: { "contents": [ {"role": "user", "parts": [{"text": "..."}]}, {"role": "model", "parts": [{"text": "..."}]} ], "systemInstruction": {"parts": [{"text": "..."}]}, "generationConfig": { "temperature": 0.6, "maxOutputTokens": 700, "responseMimeType": "application/json" } }
Role mapping: OpenAI shape → Gemini shape role="system" → systemInstruction (separate top-level field) role="user" → contents[i].role = "user" role="assistant" → contents[i].role = "model"
JSON mode: response_format == {"type": "json_object"} → generationConfig.responseMimeType = "application/json"
The provider matches the existing `LLMProvider` interface so it slotsstraight into both sales_brain.py (Tier 0) and the orchestrator brain mainpath (Tier 0, via TieredBrainLLM wrapper)."""
from __future__ import annotations
import asyncioimport osfrom typing import Optional
import httpx
from backend.providers.base import ChatMessage, LLMProvider, LLMResult
GEMINI_BASE_URL = "https://generativelanguage.googleapis.com/v1beta/models"DEFAULT_MODEL = "gemini-2.5-flash-lite" # KI-183 — gemini-2.0-flash retired for new accounts
def _to_gemini_contents(messages: list[ChatMessage]) -> tuple[Optional[str], list[dict]]: """Split an OpenAI-style message list into (systemInstruction, contents).
Gemini's API expects: - `systemInstruction` as a separate top-level field (one block, the concatenation of every system message in order) - `contents` as a list of `{role: "user" | "model", parts: [{text: ...}]}` entries (no "system" role allowed inside contents)
OpenAI's role names map cleanly: - "system" → folded into systemInstruction - "user" → contents[i].role = "user" - "assistant" → contents[i].role = "model"
Empty / non-string content is coerced to a safe empty string so a stray None never breaks the wire payload. """ system_chunks: list[str] = [] contents: list[dict] = [] for m in messages: text = m.content if isinstance(m.content, str) else str(m.content or "") if m.role == "system": if text: system_chunks.append(text) continue if m.role == "user": contents.append({"role": "user", "parts": [{"text": text}]}) elif m.role == "assistant": contents.append({"role": "model", "parts": [{"text": text}]}) else: # Unknown role — treat as user input rather than dropping it. contents.append({"role": "user", "parts": [{"text": text}]}) system_instruction = "\n\n".join(system_chunks) if system_chunks else None return system_instruction, contents
class GoogleGeminiLLM(LLMProvider): """Google Gemini Flash via the AI Studio REST API.
`api_key` is read from the `GOOGLE_API_KEY` env var at *chat-time* — NOT at module import time — so missing-key errors only surface when this provider is actually called. That keeps cold imports cheap and lets the Tier 0 layer cleanly fall through to Tier 1 (NIM) when the key is unavailable (e.g., on the eval harness machine). """
name = "gemini"
def __init__( self, model: str = DEFAULT_MODEL, api_key: Optional[str] = None, timeout: float = 25.0, ): # Defer the key-presence check to chat() — see class docstring. self.api_key = api_key or os.environ.get("GOOGLE_API_KEY", "") self.model = model self.timeout = timeout self.name = f"gemini::{model}"
async def chat( self, messages: list[ChatMessage], temperature: float = 0.6, max_tokens: int = 700, response_format: Optional[dict] = None, **kwargs, # absorb OR-specific kwargs like `models=[...]` — ignored here ) -> LLMResult: if not self.api_key: raise RuntimeError( "GOOGLE_API_KEY not set. Get a key at " "https://aistudio.google.com/app/apikey and add " "GOOGLE_API_KEY=... to .env" )
system_instruction, contents = _to_gemini_contents(messages)
generation_config: dict = { "temperature": temperature, "maxOutputTokens": max_tokens, } # JSON mode — Gemini's native equivalent of OpenAI response_format. if response_format and response_format.get("type") == "json_object": generation_config["responseMimeType"] = "application/json"
body: dict = { "contents": contents, "generationConfig": generation_config, } if system_instruction: body["systemInstruction"] = {"parts": [{"text": system_instruction}]}
# API key goes in the URL query param — the Google AI Studio default. # The header form (`x-goog-api-key`) also works but is undocumented for # the v1beta generativelanguage endpoint. url = f"{GEMINI_BASE_URL}/{self.model}:generateContent?key={self.api_key}" headers = {"Content-Type": "application/json"}
# Per-phase timeouts mirroring the NIM/OpenRouter pattern: a stuck # connection releases its slot on its own deadline rather than holding # past the outer wait_for cancellation. client_timeout = httpx.Timeout( connect=2.0, read=self.timeout, write=2.0, pool=2.0, )
async with httpx.AsyncClient(timeout=client_timeout) as client: resp = await client.post(url, headers=headers, json=body) if resp.status_code >= 400: # Surface the Google error body so the caller's log makes the # root cause visible (typical failure: 429 quota exceeded or # 400 prompt-block). detail = "" try: detail = resp.text[:500] except Exception: pass raise httpx.HTTPStatusError( f"Gemini API {resp.status_code}: {detail}", request=resp.request, response=resp, ) payload = resp.json()
# Response shape: # {"candidates": [{"content": {"parts": [{"text": "..."}], "role": "model"}, # "finishReason": "STOP"}], # "usageMetadata": {"promptTokenCount": N, "candidatesTokenCount": M, ...}} text = "" try: candidates = payload.get("candidates") or [] if candidates: parts = (candidates[0].get("content") or {}).get("parts") or [] # Concatenate every text part — Gemini sometimes returns # multiple chunks per candidate when streaming-shape leaks # into a non-streaming response. text = "".join( p.get("text", "") for p in parts if isinstance(p, dict) ) except Exception: text = ""
usage = payload.get("usageMetadata") or {} return LLMResult( text=text, model=self.model, prompt_tokens=usage.get("promptTokenCount"), completion_tokens=usage.get("candidatesTokenCount"), raw=payload, )
# ----------------------------------------------------------------------------# Factory# ----------------------------------------------------------------------------
def get_gemini_llm( model: str = DEFAULT_MODEL, timeout: float = 25.0,) -> GoogleGeminiLLM: """Return a fresh GoogleGeminiLLM client.
25s timeout matches the KI-179 brief — Gemini Flash typically responds in 1-3s so 25s is a generous outer bound that still bails fast on a quota / network stall.
Common models: - "gemini-2.0-flash" → fast, conversational, sales_brain Tier 0 - "gemini-2.5-flash" → slightly heavier reasoning, brain main Tier 0 """ return GoogleGeminiLLM(model=model, timeout=timeout)
__all__ = ["GoogleGeminiLLM", "get_gemini_llm", "DEFAULT_MODEL"]67 unmodified lines6869707172737475767778798057 unmodified lines13813914067 unmodified linestemperature: float = 0.2,max_tokens: int = 1024,response_format: Optional[dict] = None,) -> LLMResult:body: dict = {"model": self.model,"messages": [{"role": m.role, "content": m.content} for m in messages],"temperature": temperature,"max_tokens": max_tokens,}if response_format:body["response_format"] = response_format57 unmodified linescompletion_tokens=usage.get("completion_tokens"),raw=payload,)67 unmodified lines686970717273747576777879808182838485868788899091929357 unmodified lines15115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120267 unmodified linestemperature: float = 0.2,max_tokens: int = 1024,response_format: Optional[dict] = None,models: Optional[list[str]] = None,) -> LLMResult:"""Send a chat completion to OpenRouter.KI-176 — `models` (optional list of model ids) activates OpenRouter'snative server-side fallback: the server tries each id in order andreturns the first that succeeds. When provided, `models[0]` is alsoset as the primary `model` field (OpenRouter requires both forrouting; if `models` is omitted the lone `model` field is used).Reference: https://openrouter.ai/docs/features/model-routing"""primary_model = models[0] if models else self.modelbody: dict = {"model": primary_model,"messages": [{"role": m.role, "content": m.content} for m in messages],"temperature": temperature,"max_tokens": max_tokens,}if models:body["models"] = list(models)if response_format:body["response_format"] = response_format57 unmodified linescompletion_tokens=usage.get("completion_tokens"),raw=payload,)# ----------------------------------------------------------------------------# KI-176 — Factory for the OpenRouter free-tier frontier pool.## User loaded $10 on OpenRouter; that unlocks 1000 req/day across all `:free`# suffix models. This factory returns an OpenRouterLLM whose `model` field is# a sane single-model default; callers that want server-side fallback should# pass `models=[...]` to `chat()`.## Model IDs verified against the LIVE OpenRouter catalog# (GET /api/v1/models, 2026-05-15). The model IDs from the KI-176 brief# (gemini-2.0-flash-exp:free, llama-3.3-70b-instruct:free,# hermes-3-llama-3.1-405b:free) were checked:# - gemini-2.0-flash-exp:free — NOT in catalog# - llama-3.3-70b-instruct:free — PRESENT but no response_format# - hermes-3-llama-3.1-405b:free — PRESENT but no response_format# So those would silently lose JSON mode. The IDs below are the actual# free-tier set that declare `response_format` (and most also# `structured_outputs`) in their `supported_parameters`:# - nvidia/nemotron-3-super-120b-a12b:free (120B, structured_outputs)# - qwen/qwen3-next-80b-a3b-instruct:free (80B, structured_outputs)# - google/gemma-4-31b-it:free (31B, response_format)# - minimax/minimax-m2.5:free (?, response_format)# - google/gemma-4-26b-a4b-it:free (26B, response_format)# ----------------------------------------------------------------------------# Default JSON-mode-capable free-tier model. Callers usually override this by# passing `models=[...]` to chat() — this is just the lone-model fallback.DEFAULT_FREE_BRAIN_MODEL = "nvidia/nemotron-3-super-120b-a12b:free"def get_openrouter_llm(chain_name: str = "sales_brain",model: str = DEFAULT_FREE_BRAIN_MODEL,timeout: float = 60.0,) -> "OpenRouterLLM":"""Return a fresh OpenRouterLLM ready for sales_brain.The returned client is single-use-shaped (one chat() call per turn) andintended to be passed `models=[primary, fallback1, fallback2]` so theOpenRouter server handles in-pool failover before the caller falls backto the NIM chain."""return OpenRouterLLM(model=model,timeout=timeout,chain_name=chain_name,)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229"""TieredBrainLLM — 3-tier wrapper for the orchestrator's brain main path (KI-179).
Architecture:
Tier 0 — Google Gemini Flash (best free quality, 1500 req/day) Tier 1 — NIM brain chain (NimChainLLM, multi-candidate election) Tier 2 — OpenRouter free pool (cross-provider safety net)
Why a wrapper class instead of inlining the tiers in orchestrator.py?
The orchestrator's brain main path is one of the busiest call-sites in thesystem — faithfulness gates, cross-check retry, drift recovery, eval loggingall hang off it. Inlining a 3-tier try/except cascade there would explodethe cyclomatic complexity of an already-long function. Wrapping the3-tier dance behind the SAME `LLMProvider.chat()` signature as `NimChainLLM`lets us swap in the wrapper at the construction site with zero downstreamchanges — the existing `await pick.provider.chat(...)` call shape ispreserved.
Match the existing `LLMProvider` interface so this drops into the sameslot the orchestrator currently fills with `get_brain_llm()` /`get_fast_brain_llm()`. `self.model` and `self.name` are updated after asuccessful call to reflect which tier actually served — preserves theKI-080 audit trail."""
from __future__ import annotations
import asyncioimport loggingfrom typing import Optional
from backend.providers.base import ChatMessage, LLMProvider, LLMResultfrom backend.providers.google_gemini_llm import get_gemini_llmfrom backend.providers.nvidia_nim_llm import ( get_brain_llm, get_fast_brain_llm,)from backend.providers.openrouter_llm import get_openrouter_llm
# Mirrors sales_brain.py's free-tier pool: every model declares# response_format in its supported_parameters so the OR server's native# fallback walks an JSON-mode-aware list._OR_MODELS: list[str] = [ "nvidia/nemotron-3-super-120b-a12b:free", "qwen/qwen3-next-80b-a3b-instruct:free", "google/gemma-4-31b-it:free",]
class TieredBrainLLM(LLMProvider): """3-tier brain wrapper: Gemini → NIM → OpenRouter.
`role` is one of "brain" | "fast_brain" — controls which NIM chain factory is used for Tier 1: - "brain" → get_brain_llm() (BRAIN_CHAIN, 20s per-link) - "fast_brain" → get_fast_brain_llm() (FAST_BRAIN_CHAIN, 6s per-link)
`gemini_model` defaults to "gemini-2.5-flash" for the heavy brain (slightly higher quality on complex synthesis) and can be overridden to "gemini-2.0-flash" for the fast brain (lower latency).
`per_tier_timeout` is the outer asyncio.wait_for cap applied to EACH tier individually. Mirrors the 30s budget the orchestrator's existing brain call uses (see orchestrator.py KI-098). """
name = "tiered-brain"
def __init__( self, role: str = "brain", gemini_model: str = "gemini-2.5-flash", per_tier_timeout: float = 30.0, ): if role not in ("brain", "fast_brain"): raise ValueError(f"role must be 'brain' or 'fast_brain', got {role!r}") self.role = role self.gemini_model = gemini_model self.per_tier_timeout = per_tier_timeout # Start with the Tier 0 model as the "current" model — `chat()` # rewrites this to whichever tier actually served the request. self.model = gemini_model self.name = f"tiered-brain::{role}::gemini:{gemini_model}"
async def chat( self, messages: list[ChatMessage], temperature: float = 0.2, max_tokens: int = 1024, response_format: Optional[dict] = None, **kwargs, # absorb provider-specific kwargs (e.g. OR's `models=[...]`) ) -> LLMResult: gemini_exc: Optional[BaseException] = None nim_exc: Optional[BaseException] = None or_exc: Optional[BaseException] = None
# ---- Tier 0 — Google Gemini ---- try: gemini_llm = get_gemini_llm(model=self.gemini_model, timeout=25.0) result = await asyncio.wait_for( gemini_llm.chat( messages=messages, temperature=temperature, max_tokens=max_tokens, response_format=response_format, ), timeout=self.per_tier_timeout, ) text = (result.text or "").strip() if text: # Stamp the actually-served model so faithfulness can exclude it # from the judge chain (cross-family-grading invariant). self.model = result.model or self.gemini_model self.name = f"tiered-brain::{self.role}::gemini:{self.model}" return result # Empty text from Gemini → treat as failure, fall through. logging.info( "TieredBrainLLM[%s]: Gemini returned empty text, falling to NIM", self.role, ) except (asyncio.CancelledError, KeyboardInterrupt, SystemExit): raise except asyncio.TimeoutError as e: gemini_exc = e logging.info( "TieredBrainLLM[%s]: Gemini timed out, falling to NIM", self.role, ) except Exception as e: # noqa: BLE001 — fall through on ANY provider error gemini_exc = e logging.info( "TieredBrainLLM[%s]: Gemini raised %s, falling to NIM: %s", self.role, type(e).__name__, str(e)[:200], )
# ---- Tier 1 — NIM chain ---- try: nim_llm = ( get_brain_llm() if self.role == "brain" else get_fast_brain_llm() ) result = await asyncio.wait_for( nim_llm.chat( messages=messages, temperature=temperature, max_tokens=max_tokens, response_format=response_format, ), timeout=self.per_tier_timeout, ) text = (result.text or "").strip() if text: self.model = result.model or getattr(nim_llm, "model", "nim") self.name = f"tiered-brain::{self.role}::nim:{self.model}" return result logging.info( "TieredBrainLLM[%s]: NIM returned empty text, falling to OpenRouter", self.role, ) except (asyncio.CancelledError, KeyboardInterrupt, SystemExit): raise except asyncio.TimeoutError as e: nim_exc = e logging.info( "TieredBrainLLM[%s]: NIM timed out, falling to OpenRouter", self.role, ) except Exception as e: # noqa: BLE001 nim_exc = e logging.info( "TieredBrainLLM[%s]: NIM raised %s, falling to OpenRouter: %s", self.role, type(e).__name__, str(e)[:200], )
# ---- Tier 2 — OpenRouter free pool ---- try: or_llm = get_openrouter_llm(chain_name=f"orchestrator_{self.role}") result = await asyncio.wait_for( or_llm.chat( messages=messages, temperature=temperature, max_tokens=max_tokens, response_format=response_format, models=_OR_MODELS, ), timeout=self.per_tier_timeout, ) self.model = result.model or "openrouter" self.name = f"tiered-brain::{self.role}::or:{self.model}" return result except (asyncio.CancelledError, KeyboardInterrupt, SystemExit): raise except Exception as e: # noqa: BLE001 or_exc = e
# All three tiers failed — raise a single combined RuntimeError so # the orchestrator's existing outer-error handling treats it as a # standard brain failure (it already handles `pick.provider.chat` # raising — see the wait_for cap at orchestrator.py KI-098). raise RuntimeError( f"TieredBrainLLM[{self.role}] all tiers failed: " f"gemini={type(gemini_exc).__name__ if gemini_exc else 'n/a'}, " f"nim={type(nim_exc).__name__ if nim_exc else 'n/a'}, " f"or={type(or_exc).__name__ if or_exc else 'n/a'}" ) from or_exc
def get_tiered_brain_llm( role: str = "brain", gemini_model: Optional[str] = None,) -> TieredBrainLLM: """Factory for the orchestrator's brain main path.
Defaults: role="brain" → gemini-2.5-flash + BRAIN_CHAIN (heavy synthesis) role="fast_brain" → gemini-2.5-flash-lite + FAST_BRAIN_CHAIN (voice latency)
KI-183 (2026-05-15) — gemini-2.0-flash retired for new accounts; gemini-2.5-flash-lite is the replacement (faster, cleaner JSON). """ if gemini_model is None: gemini_model = ( "gemini-2.5-flash" if role == "brain" else "gemini-2.5-flash-lite" ) return TieredBrainLLM(role=role, gemini_model=gemini_model)
__all__ = ["TieredBrainLLM", "get_tiered_brain_llm"]55 unmodified lines56575859606162636465310 unmodified lines37637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841990 unmodified lines51051151251351451551616 unmodified lines53353453553653753853955 unmodified linesfrom backend.needs_finder import Profilefrom backend.providers.base import ChatMessagefrom backend.providers.nvidia_nim_llm import get_fast_brain_llmfrom backend.sales_brain_normalizer import normalize_captures# ----------------------------------------------------------------------------# Public result dataclass — the contract WS2 will consume.# ----------------------------------------------------------------------------310 unmodified linesmessages.append(ChatMessage(role=role, content=str(content)))messages.append(ChatMessage(role="user", content=user_text or ""))# Call the fast-brain NIM chain with response_format=json_object# (singleton-via-factory — see KI-080; the factory builds a fresh# NimChainLLM each call but the underlying election state is shared# via backend.llm_health module-level dicts).llm = get_fast_brain_llm()try:result = await asyncio.wait_for(llm.chat(messages=messages,temperature=_TEMPERATURE,max_tokens=_MAX_TOKENS,response_format={"type": "json_object"},),timeout=_TIMEOUT_S,)except asyncio.TimeoutError:elapsed = time.time() - t0logging.warning("sales_brain timeout (session=%s, %.1fs)", session_id, elapsed,)return SalesBrainResult(reply_text="",captured_updates={},ready_for_recommendations=False,brain_used="sales_brain::error:timeout",error_reason=f"timeout_after_{elapsed:.1f}s",)except Exception as e: # noqa: BLE001 — broad catch is intentional herelogging.warning("sales_brain LLM call failed (session=%s): %s: %s",session_id, type(e).__name__, str(e)[:200],)return SalesBrainResult(reply_text="",captured_updates={},ready_for_recommendations=False,brain_used=f"sales_brain::error:llm_error_{type(e).__name__}",error_reason=f"{type(e).__name__}: {str(e)[:200]}",)# Parse the JSON object from the LLM response.90 unmodified linesreply_text=retry_reply,captured_updates=captured_updates,ready_for_recommendations=ready_for_recommendations,brain_used=f"sales_brain::nim:{retry_model}::retry",raw_json=retry_parsed,error_reason=None,)16 unmodified linesreply_text=reply_text,captured_updates=captured_updates,ready_for_recommendations=ready_for_recommendations,brain_used=f"sales_brain::nim:{served_model}",raw_json=parsed,error_reason=None,)55 unmodified lines56575859606162636465666768697071727374757677787980818283310 unmodified lines39439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254390 unmodified lines63463563663763863964016 unmodified lines65765865966066166266355 unmodified linesfrom backend.needs_finder import Profilefrom backend.providers.base import ChatMessagefrom backend.providers.google_gemini_llm import get_gemini_llmfrom backend.providers.nvidia_nim_llm import get_fast_brain_llmfrom backend.providers.openrouter_llm import get_openrouter_llmfrom backend.sales_brain_normalizer import normalize_captures# ----------------------------------------------------------------------------# KI-176 — OpenRouter free-tier frontier pool (PRIMARY tier).## User loaded $10 on OpenRouter which unlocks 1000 req/day on `:free` models.# These IDs were verified against the LIVE OpenRouter catalog and ALL declare# `response_format` in their supported_parameters (the first two also declare# `structured_outputs`). The list is passed to OpenRouter's native `models`# array for server-side in-pool fallback BEFORE we fall through to NIM.# ----------------------------------------------------------------------------_OR_MODELS: list[str] = ["nvidia/nemotron-3-super-120b-a12b:free", # 120B, structured_outputs"qwen/qwen3-next-80b-a3b-instruct:free", # 80B, structured_outputs"google/gemma-4-31b-it:free", # 31B, response_format]# ----------------------------------------------------------------------------# Public result dataclass — the contract WS2 will consume.# ----------------------------------------------------------------------------310 unmodified linesmessages.append(ChatMessage(role=role, content=str(content)))messages.append(ChatMessage(role="user", content=user_text or ""))# KI-179 (2026-05-15) — 3-tier LLM stack with Google Gemini 2.0 Flash# PRIMARY (Tier 0), NIM fast-brain chain Tier 1, OpenRouter free-tier# pool Tier 2. Google AI Studio's free tier is 1500 req/day with native# JSON mode; quality > NIM/OR free tiers for conversational fact-find.## Order: Gemini → NIM → OR → final error.# `llm` is rebound to whichever provider served so the empty-reply# retry path (KI-169, further down) re-uses the SAME provider that# just answered — no re-tier on retry.llm = Noneresult = Noneserved_tier: str = "" # "gemini" | "nim" | "or"gemini_exc: Optional[BaseException] = Nonenim_exc: Optional[BaseException] = Noneor_exc: Optional[BaseException] = None# ---- Tier 0 — Google Gemini 2.5 Flash Lite ----# KI-183 (2026-05-15) — gemini-2.0-flash is retired for new accounts# (HTTP 404 "no longer available to new users"). gemini-2.5-flash-lite# is the supported replacement: faster (~900ms vs ~1100ms for 2.5-flash),# cleaner JSON-mode output, same free quota.gemini_llm = Nonetry:gemini_llm = get_gemini_llm(model="gemini-2.5-flash-lite", timeout=25.0)except Exception as e: # noqa: BLE001gemini_exc = elogging.info("sales_brain: Gemini unavailable, skipping to NIM (session=%s): %s: %s",session_id, type(e).__name__, str(e)[:200],)if gemini_llm is not None:try:result = await asyncio.wait_for(gemini_llm.chat(messages=messages,temperature=_TEMPERATURE,max_tokens=_MAX_TOKENS,response_format={"type": "json_object"},),timeout=_TIMEOUT_S,)llm = gemini_llmserved_tier = "gemini"except asyncio.TimeoutError as e:gemini_exc = elogging.info("sales_brain: Gemini timed out, falling back to NIM (session=%s)",session_id,)except Exception as e: # noqa: BLE001gemini_exc = elogging.info("sales_brain: Gemini raised %s, falling back to NIM (session=%s): %s",type(e).__name__, session_id, str(e)[:200],)# ---- Tier 1 — NIM fast-brain chain ----if result is None:nim_llm = get_fast_brain_llm()try:result = await asyncio.wait_for(nim_llm.chat(messages=messages,temperature=_TEMPERATURE,max_tokens=_MAX_TOKENS,response_format={"type": "json_object"},),timeout=_TIMEOUT_S,)llm = nim_llmserved_tier = "nim"except asyncio.TimeoutError as e:nim_exc = elogging.info("sales_brain: NIM timed out, falling back to OpenRouter (session=%s)",session_id,)except Exception as e: # noqa: BLE001nim_exc = elogging.info("sales_brain: NIM raised %s, falling back to OpenRouter (session=%s): %s",type(e).__name__, session_id, str(e)[:200],)# ---- Tier 2 — OpenRouter free-tier frontier pool ----if result is None:or_llm = Nonetry:or_llm = get_openrouter_llm(chain_name="sales_brain")except Exception as e: # noqa: BLE001 — missing API key etc.or_exc = elogging.info("sales_brain: OpenRouter unavailable (session=%s): %s: %s",session_id, type(e).__name__, str(e)[:200],)if or_llm is not None:try:result = await asyncio.wait_for(or_llm.chat(messages=messages,temperature=_TEMPERATURE,max_tokens=_MAX_TOKENS,response_format={"type": "json_object"},models=_OR_MODELS,),timeout=_TIMEOUT_S,)llm = or_llmserved_tier = "or"except asyncio.TimeoutError as e:or_exc = eexcept Exception as e: # noqa: BLE001or_exc = e# ---- All three tiers exhausted — final error ----if result is None:elapsed = time.time() - t0logging.warning("sales_brain ALL TIERS FAILED (session=%s, %.1fs, ""gemini_exc=%s, nim_exc=%s, or_exc=%s)",session_id, elapsed,f"{type(gemini_exc).__name__}" if gemini_exc else "n/a",f"{type(nim_exc).__name__}" if nim_exc else "n/a",f"{type(or_exc).__name__}" if or_exc else "n/a",)# Classify reason: timeout-everywhere is its own bucket vs mixed errors.all_timeouts = all(isinstance(e, asyncio.TimeoutError) for e in (gemini_exc, nim_exc, or_exc)if e is not None)reason_tag = "timeout_all_tiers" if all_timeouts else "llm_error_all_tiers"return SalesBrainResult(reply_text="",captured_updates={},ready_for_recommendations=False,brain_used=f"sales_brain::error:{reason_tag}",error_reason=(f"gemini_exc={type(gemini_exc).__name__ if gemini_exc else 'n/a'}; "f"nim_exc={type(nim_exc).__name__ if nim_exc else 'n/a'}; "f"or_exc={type(or_exc).__name__ if or_exc else 'n/a'}; "f"elapsed={elapsed:.1f}s"),)# Parse the JSON object from the LLM response.90 unmodified linesreply_text=retry_reply,captured_updates=captured_updates,ready_for_recommendations=ready_for_recommendations,brain_used=f"sales_brain::{served_tier}:{retry_model}::retry",raw_json=retry_parsed,error_reason=None,)16 unmodified linesreply_text=reply_text,captured_updates=captured_updates,ready_for_recommendations=ready_for_recommendations,brain_used=f"sales_brain::{served_tier}:{served_model}",raw_json=parsed,error_reason=None,)
9 unmodified lines1011121314151622 unmodified lines394041424344455 unmodified lines515253549 unmodified lines| --- | --- || `generate_gold.py` | Builds `gold_qa.json` from `40-data/policy_facts/`: for each curated field with a verbatim quote, emits a natural-language question + expected answer + expected citation. || `gold_qa.json` | 96-Q gold set. Each entry: `{policy_id, question, expected_answer, expected_regex, source_quote, source_pdf}`. || `run.py` | Runner. For each pair: calls `backend.orchestrator.handle_turn` with `policy_filter_ids=[pair.policy_id]` so retrieval is scoped to the policy under test. Grades each reply twice — regex hard-facts + NIM Mistral Large 3 judge chain (different family from the NIM Qwen brain → non-circular). Falls through to Groq Llama only at the cross-provider tail of `JUDGE_CHAIN`. || `results.json` | Machine-readable last-run results. || `results.md` | Human-readable last-run report — per-question pass/fail, per-category rollup, hallucination breakdown. || `info_source_map.json` | Generated by `tools/info_source_map.py`. Claim → URL → verdict (✅ 798 / ⚠️ 321 / ❌ 0 / ⏳ 1385 as of 2026-05-14). The canonical source-grounding KPI. |22 unmodified lines| Layer | What it checks | Output field || --- | --- | --- || Regex hard-facts | Expected numeric / boolean / waiting-period value appears verbatim in `reply_text`. | `regex_pass` || LLM judge (NIM Mistral Large 3 675B primary; OpenAI GPT-OSS 120B / Moonshot Kimi K2 / Llama-4 Maverick / Groq Llama-3.3-70B fallbacks) | Reply *semantically* answers the question and cites the expected source. Different family from the NIM Qwen brain → non-circular. | `judge_pass` || Faithfulness gate | The 4-gate guard in `backend/faithfulness.py` already ran during `handle_turn`; eval records whether it blocked. | `blocked` |## Acceptance bar5 unmodified lines- [`backend/faithfulness.py`](../backend/faithfulness.py) — the 4-gate guard that produces the `blocked` verdict- [`kb/AUDIT_TRAIL.md`](../kb/AUDIT_TRAIL.md) § "Live bot replies" — provenance trail for any flagged reply- `tools/info_source_map.py` — generator of `info_source_map.json`- [ADR-014](../70-docs/60-decisions/ADR-014-groq-llama-grader.md) (superseded — but the Groq-judge-of-different-family principle survives)9 unmodified lines1011121314151622 unmodified lines394041424344455 unmodified lines51525354559 unmodified lines| --- | --- || `generate_gold.py` | Builds `gold_qa.json` from `40-data/policy_facts/`: for each curated field with a verbatim quote, emits a natural-language question + expected answer + expected citation. || `gold_qa.json` | 96-Q gold set. Each entry: `{policy_id, question, expected_answer, expected_regex, source_quote, source_pdf}`. || `run.py` | Runner. For each pair: calls `backend.orchestrator.handle_turn` with `policy_filter_ids=[pair.policy_id]` so retrieval is scoped to the policy under test. Grades each reply twice — regex hard-facts + `JUDGE_CHAIN` (NIM Mistral Large 3 675B primary; different family from the Gemini brain → non-circular). Falls through to NIM Llama-4 Maverick → OpenRouter Qwen 80B `:free` → NIM Nemotron 49B at the tail. Emits `brain_used` like `sales_brain::continue` / `sales_brain::complete` / `brain_main::<elected_model>` / `brain_main::graceful_error`. || `results.json` | Machine-readable last-run results. || `results.md` | Human-readable last-run report — per-question pass/fail, per-category rollup, hallucination breakdown. || `info_source_map.json` | Generated by `tools/info_source_map.py`. Claim → URL → verdict (✅ 798 / ⚠️ 321 / ❌ 0 / ⏳ 1385 as of 2026-05-14). The canonical source-grounding KPI. |22 unmodified lines| Layer | What it checks | Output field || --- | --- | --- || Regex hard-facts | Expected numeric / boolean / waiting-period value appears verbatim in `reply_text`. | `regex_pass` || LLM judge (`JUDGE_CHAIN`: NIM Mistral Large 3 675B primary; NIM Llama-4 Maverick / OR Qwen 80B `:free` / NIM Nemotron 49B fallbacks per [ADR-040](../70-docs/60-decisions/ADR-040-google-gemini-primary.md)) | Reply *semantically* answers the question and cites the expected source. Different family from the Gemini brain → non-circular. | `judge_pass` || Faithfulness gate | The 4-gate guard in `backend/faithfulness.py` already ran during `handle_turn`; eval records whether it blocked. | `blocked` |## Acceptance bar5 unmodified lines- [`backend/faithfulness.py`](../backend/faithfulness.py) — the 4-gate guard that produces the `blocked` verdict- [`kb/AUDIT_TRAIL.md`](../kb/AUDIT_TRAIL.md) § "Live bot replies" — provenance trail for any flagged reply- `tools/info_source_map.py` — generator of `info_source_map.json`- [ADR-014](../70-docs/60-decisions/ADR-014-groq-llama-grader.md) (superseded — but the cross-family judge principle survives; current judge is NIM Mistral 675B, brain is Gemini)- [ADR-040](../70-docs/60-decisions/ADR-040-google-gemini-primary.md) — current chain shape (Google → NIM → OpenRouter)
12 unmodified lines13141516171819202122232412 unmodified lines| `src/app/globals.css` | Tailwind v4 entrypoint + the shadcn/ui token layer ([ADR-013](../70-docs/60-decisions/ADR-013-tailwind-shadcn-ui.md)). || `src/lib/api.ts` | Typed API client. Generated types via `openapi-typescript` from the FastAPI OpenAPI schema ([ADR-015](../70-docs/60-decisions/ADR-015-openapi-typescript-codegen.md)). || `src/lib/useLiveConversation.ts` | The continuously-open-mic VAD hook that powers Live mode + barge-in. State persists in `localStorage.insurance_live_pref` ([ADR-028](../70-docs/60-decisions/ADR-028-voice-ux-single-default-mode.md)). || `src/lib/i18n.ts` | EN ↔ हिं strings + the 13-term `GLOSSARY` mirrored to [`kb/methodology/glossary.json`](../kb/methodology/glossary.json). |## Voice UX invariants ([ADR-028](../70-docs/60-decisions/ADR-028-voice-ux-single-default-mode.md))- **One default voice mode + one fallback.** Live mode is the default; the toolbar pill toggles it (green = on, red = off). The 🎤 push-to-talk button suspends Live for one turn → captures with VAD silence-cutoff → resumes Live if the user preference is still on.- **Hands-free mode was removed in KI-027.** Any reference to it in code or docs is stale.- **Bot TTS plays via the in-DOM `<audio>` element inside `Message`** (autoplay-on-mount via ref'd `useEffect`). **Never use `new Audio(url).play()`** — those detached instances are invisible to the `document.querySelectorAll("audio").pause()` call in the barge-in handler, so they keep playing under the user's speech.## Tooling12 unmodified lines13141516171819202122232425262712 unmodified lines| `src/app/globals.css` | Tailwind v4 entrypoint + the shadcn/ui token layer ([ADR-013](../70-docs/60-decisions/ADR-013-tailwind-shadcn-ui.md)). || `src/lib/api.ts` | Typed API client. Generated types via `openapi-typescript` from the FastAPI OpenAPI schema ([ADR-015](../70-docs/60-decisions/ADR-015-openapi-typescript-codegen.md)). || `src/lib/useLiveConversation.ts` | The continuously-open-mic VAD hook that powers Live mode + barge-in. State persists in `localStorage.insurance_live_pref` ([ADR-028](../70-docs/60-decisions/ADR-028-voice-ux-single-default-mode.md)). || `src/lib/useStreamingVoice.ts` | **KI-168 hybrid voice capture.** Runs Web Speech API (interim transcripts streamed live to the chat input) and `MediaRecorder` (authoritative audio blob) in parallel; on browser silence-detect the blob is POSTed to `/api/transcribe` (Sarvam Saarika STT). Auto-submits the Sarvam transcript; falls back to the Web Speech transcript only if Sarvam errors. KI-173 heartbeat + KI-174 `visibilitychange` / `focus` revival hooks keep the mic alive across tab / app switches. || `src/lib/i18n.ts` | EN ↔ हिं strings + the 13-term `GLOSSARY` mirrored to [`kb/methodology/glossary.json`](../kb/methodology/glossary.json). |## Voice UX invariants ([ADR-028](../70-docs/60-decisions/ADR-028-voice-ux-single-default-mode.md))- **One default voice mode + one fallback.** Live mode is the default; the toolbar pill toggles it (green = on, red = off). The 🎤 push-to-talk button suspends Live for one turn → captures with VAD silence-cutoff → resumes Live if the user preference is still on.- **Hands-free mode was removed in KI-027.** Any reference to it in code or docs is stale.- **Hybrid capture (KI-168).** Web Speech API drives the live interim transcript on the chat input; `MediaRecorder` captures the authoritative blob in parallel. On browser silence-detect the blob is POSTed to `/api/transcribe` (Sarvam) for the authoritative transcript; Web Speech is the fallback only if Sarvam errors. See `src/lib/useStreamingVoice.ts`.- **Mic survives tab / app switches (KI-173 / KI-174).** Heartbeat keeps the mic stream alive while the tab is backgrounded; `visibilitychange` / `focus` revival hooks reattach the mic on tab return.- **Bot TTS plays via the in-DOM `<audio>` element inside `Message`** (autoplay-on-mount via ref'd `useEffect`). **Never use `new Audio(url).play()`** — those detached instances are invisible to the `document.querySelectorAll("audio").pause()` call in the barge-in handler, so they keep playing under the user's speech.## Tooling
726 unmodified lines727728729730731732726 unmodified linesfunction $(id) { return document.getElementById(id); }function clearChildren(el) {while (el.firstChild) el.removeChild(el.firstChild);}726 unmodified lines727728729730731732733726 unmodified linesfunction $(id) { return document.getElementById(id); }function clearChildren(el) {if (!el) return;while (el.firstChild) el.removeChild(el.firstChild);}
29 unmodified lines3031323334353637383940414243444546474849505152535455568 unmodified lines6566676869707116 unmodified lines8889909192939439 unmodified lines13413513613713813914053 unmodified lines19419519619719829 unmodified lines[7] [8] [9]VECTOR INDEX STRUCTURED EXTRACTION SCORECARD- Chroma persistent - Sarvam-M extraction - rules-based 6-sub-scoreclient with HealthPolicy weighted aggregation- metadata per chunk Pydantic schema - A-F grade- rag/vectors/*.sqlite3 - DeepSeek-V3 fallback - 24 of 62 fields used→ rag/extracted/*.json→ rag/policies.duckdb[10] [11] [12]RETRIEVAL ORCHESTRATION FAITHFULNESS GATES- Voyage at query time - intent classifier - Gate 1: retrieval floor(BGE for matching) - brain router (Sarvam-M - Gate 2: citation integrity- top-k cosine → Llama/DeepSeek) - Gate 3: regex numeric- per-policy filter - persona prompt grounding- chat history - Gate 4: LLM-judge[13] [14] [15]RESPONSE TTS UI RENDER- reply_text + citations - Sarvam Bulbul - chat bubble- brain used, latency - audio response - source links per- faithfulness verdict - language match citation- scorecard (P1)```## 2. Every artifact at every stage8 unmodified lines| 5 CHUNK | chunks (in-memory) | _ephemeral_ | `rag/ingest.py:chunk_pages` | run ingest with `--dry-run` || 6 EMBED | 384-dim vectors | _embedded in Chroma_ | `backend/providers/local_embeddings.py` | re-encode the same text || 7 VECTOR INDEX | persistent sqlite | `rag/vectors/chroma.sqlite3` + HNSW binaries | `chromadb.PersistentClient` | open with chromadb client || 8 STRUCTURED EXTRACTION | 62-field JSON per policy | `rag/extracted/<policy_id>.json` | `rag/extract.py` (Sarvam-M → DeepSeek-V3 fallback) | re-run extraction; compare || 8 STRUCTURED EXTRACTION | aggregate table | `rag/policies.duckdb` | upsert in `rag/extract.py` | `duckdb` CLI query || 9 SCORECARD | per-policy grade | `kb/policies/<policy_id>.md` (live in code via `backend/scorecard.py`) | `rag/build_kb.py` + `backend/scorecard.py` | re-run `build_kb` || 10 RETRIEVAL (runtime) | top-k chunks | _ephemeral, logged_ | `rag/retrieve.py` | replay query against Chroma |16 unmodified lines- **Risk if tampered**: silent retrieval poisoning. Mitigation: chunk content stored alongside the embedding; can be re-verified against source PDF on demand.### Extracted structured data (Stage 8)- **Provenance**: LLM (Sarvam-M / DeepSeek-V3) over full PDF text + Pydantic schema- **Verifiable**: `extraction_confidence_pct` field per record + re-runnable in <30s with `python -m rag.extract --policy <id>`- **Risk if tampered**: bad downstream scorecard + filter results. Mitigation: schema validates types; manual spot-check 5%.39 unmodified linesHonesty about gaps:- **Insurer-side PDF tampering** — we trust the insurer's published PDF was real at download time. We don't have a re-fetch + diff pipeline yet. v2 enhancement.- **LLM determinism** — Sarvam-M / DeepSeek-V3 can produce slightly different extraction across runs even at `temperature=0`. We pin model versions in `backend/config.py`; for full reproducibility we'd cache extraction outputs. v2 enhancement.- **Embedding model drift** — if BGE updates, our cached vectors become stale relative to query-time embeddings. v2: pin model commit hash.- **Chroma version compatibility** — different `chromadb` releases store metadata differently (we hit `KeyError: '_type'` on first HF deploy). Pinned to `0.5.20` in `requirements.txt`.53 unmodified lines- **EN ↔ हिं i18n** — full bilingual UI with the 13-term jargon glossary at `frontend/src/lib/i18n.ts` (mirrored to `kb/methodology/glossary.json`).- **Scorecard methodology expander** — every grade opens a transparency panel sourced from `METHODOLOGY_BLUEPRINT` (mirrored to `kb/methodology/scorecard.json`).- **Source-quote popovers** — hovering a fact on a policy card surfaces the verbatim PDF quote that backed it.- **2026-05-14 Stack A consolidation (D-019)** — 4 third-party LLM providers (Groq, OpenRouter, direct DeepSeek, Cerebras) collapsed onto a single NVIDIA NIM endpoint. Brain = Qwen 80B (current brain primary) (heavy intents) + V4-Flash (voice + fact-find). Judge = Meta Mistral Large 3 675B (different family). Sarvam scoped to voice STT/TTS + Indic translation only. Free tier, 40 req/min, no daily cap. ~600 LOC of legacy provider wiring deleted.- **2026-05-14 Space/data split (D-020)** — `rag/corpus/` (188 MB), `rag/vectors/` (129 MB), and `rag/extracted/` moved to companion HF dataset `rohitsar567/insurance-bot-data` (50 GB free quota). Dockerfile pulls them at image build time. Space repo collapses from 286 MB → ~3 MB code-only.29 unmodified lines30313233343536373839404142434445464748495051525354555657585960618 unmodified lines7071727374757616 unmodified lines9394959697989939 unmodified lines13914014114214314414553 unmodified lines19920020120220320420520620720820921021121221321421521621729 unmodified lines[7] [8] [9]VECTOR INDEX STRUCTURED EXTRACTION SCORECARD- Chroma persistent - NimChainLLM(BRAIN_CHAIN)- rules-based 6-sub-scoreclient with HealthPolicy weighted aggregation- metadata per chunk Pydantic schema - A-F grade- rag/vectors/*.sqlite3 - native JSON mode - 24 of 62 fields used→ rag/extracted/*.json→ rag/policies.duckdb[10] [11] [12]RETRIEVAL ORCHESTRATION FAITHFULNESS GATES- BGE-small at query time - intent classifier - Gate 1: retrieval floor(local CPU, 384-d) - sales_brain (fact-find) - Gate 2: citation integrity- top-k cosine / BRAIN_CHAIN (QA, etc) - Gate 3: regex numeric- per-policy filter - persona prompt grounding- profile_rag (session- - chat history - Gate 4: LLM-judgescoped, KI-102) (NIM Mistral 675B,skipped on fact-find +recommendation, KI-171)[13] [14] [15]RESPONSE TTS UI RENDER- reply_text + citations - Sarvam Bulbul v2 - chat bubble- brain used (Gemini / - voice_format strips - source links perNIM / OR + model id), CoT + ₹ shorthand citationlatency - base64 in same JSON - scorecard (P1)- faithfulness verdict response - in-DOM <audio> forbarge-in compatibility```## 2. Every artifact at every stage8 unmodified lines| 5 CHUNK | chunks (in-memory) | _ephemeral_ | `rag/ingest.py:chunk_pages` | run ingest with `--dry-run` || 6 EMBED | 384-dim vectors | _embedded in Chroma_ | `backend/providers/local_embeddings.py` | re-encode the same text || 7 VECTOR INDEX | persistent sqlite | `rag/vectors/chroma.sqlite3` + HNSW binaries | `chromadb.PersistentClient` | open with chromadb client || 8 STRUCTURED EXTRACTION | 62-field JSON per policy | `rag/extracted/<policy_id>.json` | `rag/extract.py` (`NimChainLLM(BRAIN_CHAIN)` with native JSON mode) | re-run extraction; compare || 8 STRUCTURED EXTRACTION | aggregate table | `rag/policies.duckdb` | upsert in `rag/extract.py` | `duckdb` CLI query || 9 SCORECARD | per-policy grade | `kb/policies/<policy_id>.md` (live in code via `backend/scorecard.py`) | `rag/build_kb.py` + `backend/scorecard.py` | re-run `build_kb` || 10 RETRIEVAL (runtime) | top-k chunks | _ephemeral, logged_ | `rag/retrieve.py` | replay query against Chroma |16 unmodified lines- **Risk if tampered**: silent retrieval poisoning. Mitigation: chunk content stored alongside the embedding; can be re-verified against source PDF on demand.### Extracted structured data (Stage 8)- **Provenance**: `NimChainLLM(BRAIN_CHAIN)` over full PDF text + Pydantic schema, native JSON mode- **Verifiable**: `extraction_confidence_pct` field per record + re-runnable in <30s with `python -m rag.extract --policy <id>`- **Risk if tampered**: bad downstream scorecard + filter results. Mitigation: schema validates types; manual spot-check 5%.39 unmodified linesHonesty about gaps:- **Insurer-side PDF tampering** — we trust the insurer's published PDF was real at download time. We don't have a re-fetch + diff pipeline yet. v2 enhancement.- **LLM determinism** — every brain candidate (Gemini, Qwen, Mistral, Maverick) can produce slightly different extraction across runs even at `temperature=0`. Model versions are pinned in `backend/config.py`; for full reproducibility we'd cache extraction outputs. v2 enhancement.- **Embedding model drift** — if BGE updates, our cached vectors become stale relative to query-time embeddings. v2: pin model commit hash.- **Chroma version compatibility** — different `chromadb` releases store metadata differently (we hit `KeyError: '_type'` on first HF deploy). Pinned to `0.5.20` in `requirements.txt`.53 unmodified lines- **EN ↔ हिं i18n** — full bilingual UI with the 13-term jargon glossary at `frontend/src/lib/i18n.ts` (mirrored to `kb/methodology/glossary.json`).- **Scorecard methodology expander** — every grade opens a transparency panel sourced from `METHODOLOGY_BLUEPRINT` (mirrored to `kb/methodology/scorecard.json`).- **Source-quote popovers** — hovering a fact on a policy card surfaces the verbatim PDF quote that backed it.- **2026-05-14 Stack A consolidation (D-019)** — 4 third-party LLM providers (Groq, OpenRouter, direct DeepSeek, Cerebras) collapsed onto a single NVIDIA NIM endpoint. Brain = Qwen 80B (heavy intents) + Nemotron Nano 30B (voice + fact-find). Judge = Mistral Large 3 675B (different family). Sarvam scoped to voice STT/TTS + Indic translation only. Free tier, 40 req/min, no daily cap. ~600 LOC of legacy provider wiring deleted.- **2026-05-14 Space/data split (D-020)** — `rag/corpus/` (188 MB), `rag/vectors/` (129 MB), and `rag/extracted/` moved to companion HF dataset `rohitsar567/insurance-bot-data` (50 GB free quota). Dockerfile pulls them at image build time. Space repo collapses from 286 MB → ~3 MB code-only.## Batch — 2026-05-15The day's sprint produced a chain-level rewrite, a provider integration, and a fact-find rip-out. See [`70-docs/40-evaluation/quality-sprint-2026-05-14.md`](../70-docs/40-evaluation/quality-sprint-2026-05-14.md) (Follow-on sprint section) for the full KI list.- **KI-167 / [ADR-039](../70-docs/60-decisions/ADR-039-llm-driven-sales-brain.md)** — Ripped out `backend/fact_find_brain.py` (441 LOC) + `_canonical_fallback` + the `<FF>{...}</FF>` trailer convention. Replaced with `backend/sales_brain.py` — one LLM call per turn against `FAST_BRAIN_CHAIN` using native provider JSON mode (`response_mime_type=application/json` on Gemini, `response_format={"type":"json_object"}` on NIM). New deterministic post-processor `backend/sales_brain_normalizer.py` validates and normalises captured fields.- **KI-168** — Hybrid voice capture: Web Speech API streams interim transcripts to chat input (live UX feel) while `MediaRecorder` runs in parallel; on browser silence-detect the audio blob is POSTed to `/api/transcribe` (Sarvam Saarika v2.5) for the authoritative transcript. Auto-submits the Sarvam result; falls back to Web Speech only if Sarvam errors.- **KI-171** — Skip faithfulness Gate 4 (LLM judge) on `fact_find` + `recommendation` intents — no retrieved context to grade against on those turns.- **KI-173 / KI-174** — Voice heartbeat + `visibilitychange` / `focus` revival keeps the mic alive across tab / app switches.- **KI-175 / KI-176** — Chain reorder: NIM Nemotron 49B demoted from primary to last resort across all three chains (Mistral 675B / Qwen 80B consistently outperform on live audit). OpenRouter re-added as cross-provider diversity using OR's `models: [...]` server-side fallback within the OR free pool.- **KI-178** — Live audit of which OpenRouter free-tier models support `response_format`. Only NIM-style native JSON mode is supported on `nvidia/nemotron-3-super-120b-a12b:free`, `qwen/qwen3-next-80b-a3b-instruct:free`, and `google/gemma-4-31b:free`. Llama 3.3 70B / Hermes 3 405B on OR free do NOT — excluded from chains.- **KI-179 / [ADR-040](../70-docs/60-decisions/ADR-040-google-gemini-primary.md)** — Operator obtained a Google AI Studio API key. New `backend/providers/google_gemini_llm.py` wraps Google's REST API (`gemini-2.0-flash` for Brain Fast / sales_brain, `gemini-2.5-flash` for Brain Main / synthesis; native JSON mode via `response_mime_type=application/json`; 1500 req/day free quota). Promoted to **Tier 0 primary** on Brain Fast + Brain Main. NIM stays as Tier 1 fallback (Mistral 675B / Maverick / Qwen 80B); OpenRouter `:free` sits as Tier 2 diversity. **Judge stays on NIM Mistral Large 3 675B** (different family from Gemini — preserves brain ↔ judge family-diversity invariant). NIM-only lock from [ADR-038](../70-docs/60-decisions/ADR-038-nim-only-chains.md) relaxed (the `<FF>` trailer convention that motivated the lock is permanently retired post-KI-167). KI-080 sticky-primary election machinery extends naturally to the Google provider.**Net architectural shape after the sprint:** 3-tier chains across Google → NIM → OpenRouter for Brain Fast + Brain Main; NIM-only with OR `:free` diversity for Judge. Sarvam unchanged (STT + TTS + Indic translation). All structured-output traffic uses native provider JSON mode; no trailer conventions remain.
11 unmodified lines1213141516171811 unmodified lines| `download_retry.py` | 3. DOWNLOAD | Retries the failures from the previous run. || `download_regulatory.py` | 3. DOWNLOAD | IRDAI / regulatory PDFs (deferred from v1; see [ADR-017](../70-docs/60-decisions/ADR-017-irdai-corpus-playwright-rescue.md)). || `ingest.py` | 4. PARSE → 5. CHUNK → 6. EMBED → 7. INDEX | The big one. `read_pdf_pages` (pdfplumber) → `chunk_pages` (800-tok / 120 overlap, sentence-aware) → BGE embed → `chromadb.PersistentClient.add(...)`. Carries the in-process HNSW bloat tripwire ([ADR-029](../70-docs/60-decisions/ADR-029-hnsw-bloat-tripwire.md)). || `extract.py` | 8. STRUCTURED EXTRACTION | LLM extraction over each PDF using `schema.py::HealthPolicy` (62 fields). `get_brain_llm()` (Qwen 3-Next 80B primary) + `get_fast_brain_llm()` (Nemotron Nano 30B) — both `NimChainLLM` fallback chains. Writes `rag/extracted/<policy_id>.json` + upserts `policies.duckdb`. || `build_kb.py` | 9. SCORECARD → KB MIRROR | Runs `backend/scorecard.py` per policy and regenerates the human-readable `kb/policies/<id>.md` tree. || `source_map.py` | post-build | Builds `source_map.json` — every chunk → (PDF path, page, span) for citation rendering. |11 unmodified lines1213141516171811 unmodified lines| `download_retry.py` | 3. DOWNLOAD | Retries the failures from the previous run. || `download_regulatory.py` | 3. DOWNLOAD | IRDAI / regulatory PDFs (deferred from v1; see [ADR-017](../70-docs/60-decisions/ADR-017-irdai-corpus-playwright-rescue.md)). || `ingest.py` | 4. PARSE → 5. CHUNK → 6. EMBED → 7. INDEX | The big one. `read_pdf_pages` (pdfplumber) → `chunk_pages` (800-tok / 120 overlap, sentence-aware) → BGE embed → `chromadb.PersistentClient.add(...)`. Carries the in-process HNSW bloat tripwire ([ADR-029](../70-docs/60-decisions/ADR-029-hnsw-bloat-tripwire.md)). || `extract.py` | 8. STRUCTURED EXTRACTION | LLM extraction over each PDF using `schema.py::HealthPolicy` (62 fields). `get_brain_llm()` (Brain Main: Gemini 2.5 Flash primary per [ADR-040](../70-docs/60-decisions/ADR-040-google-gemini-primary.md)) + `get_fast_brain_llm()` (Brain Fast: Gemini 2.0 Flash primary) — both `NimChainLLM` fallback chains across Google → NIM → OpenRouter. Native JSON mode (`response_mime_type=application/json` on Gemini, `response_format={"type":"json_object"}` on NIM). Writes `rag/extracted/<policy_id>.json` + upserts `policies.duckdb`. || `build_kb.py` | 9. SCORECARD → KB MIRROR | Runs `backend/scorecard.py` per policy and regenerates the human-readable `kb/policies/<id>.md` tree. || `source_map.py` | post-build | Builds `source_map.json` — every chunk → (PDF path, page, span) for citation rendering. |
40 unmodified lines41424344454647484950515253545540 unmodified lines| --- | --- || `upload_to_hf.py` | Code-side push to the HF Space repo (`huggingface.co/spaces/rohitsar567/InsuranceBot`). || `upload_corpus_to_dataset.py`, `upload_extracted_to_dataset.py`, `upload_vectors_to_dataset.py`, `upload_all_to_dataset.py` | Push specific slices of `rag/` to the companion HF Dataset `rohitsar567/insurance-bot-data`. See [ADR-020](../70-docs/60-decisions/ADR-020-code-data-split-hf-dataset.md) and [ADR-024](../70-docs/60-decisions/ADR-024-triple-mirror-code-and-data.md). || `set_hf_secrets.py` | One-shot helper that pushes the runtime secrets into the HF Space (idempotent). |## Probes + diagnostics| Script | Provider it pokes || --- | --- || `sarvam_probe.py`, `sarvam_nothink_probe.py` | Sarvam-M / Saarika / Bulbul connectivity + latency. || `groq_probe.py`, `groq_long_probe.py` | Groq Llama free-tier latency + sustained-rate test. || `openrouter_probe.py`, `or_models.py` | OpenRouter routing + model-list inspection. || `pdf_probe.py` | pdfplumber parse on a single PDF — first stop when extraction silently produces empty text. || `heavy_smoke_test.py` | End-to-end smoke against the live HF Space (every provider in one call). |40 unmodified lines41424344454647484950515253545540 unmodified lines| --- | --- || `upload_to_hf.py` | Code-side push to the HF Space repo (`huggingface.co/spaces/rohitsar567/InsuranceBot`). || `upload_corpus_to_dataset.py`, `upload_extracted_to_dataset.py`, `upload_vectors_to_dataset.py`, `upload_all_to_dataset.py` | Push specific slices of `rag/` to the companion HF Dataset `rohitsar567/insurance-bot-data`. See [ADR-020](../70-docs/60-decisions/ADR-020-code-data-split-hf-dataset.md) and [ADR-024](../70-docs/60-decisions/ADR-024-triple-mirror-code-and-data.md). || `set_hf_secrets.py` | One-shot helper that pushes the runtime secrets into the HF Space (idempotent). Current secret set: `GOOGLE_API_KEY` (Google AI Studio, per [ADR-040](../70-docs/60-decisions/ADR-040-google-gemini-primary.md)), `NVIDIA_NIM_API_KEY`, `OPENROUTER_API_KEY`, `SARVAM_API_KEY`, plus admin password / IP allowlist. |## Probes + diagnostics| Script | Provider it pokes || --- | --- || `sarvam_probe.py`, `sarvam_nothink_probe.py` | Sarvam-M / Saarika / Bulbul connectivity + latency. || `groq_probe.py`, `groq_long_probe.py` | Historical Groq Llama free-tier probe — Groq is no longer in any production chain (removed in [ADR-038](../70-docs/60-decisions/ADR-038-nim-only-chains.md), not re-added in [ADR-040](../70-docs/60-decisions/ADR-040-google-gemini-primary.md)). Kept for benchmarking. || `openrouter_probe.py`, `or_models.py` | OpenRouter routing + model-list inspection. Used by KI-178 to audit which `:free` models expose `response_format`. || `pdf_probe.py` | pdfplumber parse on a single PDF — first stop when extraction silently produces empty text. || `heavy_smoke_test.py` | End-to-end smoke against the live HF Space (every provider in one call). |
30 unmodified lines31323334353630 unmodified linesSECRETS_TO_SET = ["SARVAM_API_KEY", "VOYAGE_API_KEY", "NVIDIA_NIM_API_KEY","OPENROUTER_API_KEY", "GROQ_API_KEY","ADMIN_IP_ALLOWLIST", "ADMIN_PASSWORD",]# Truly retired providers — delete from Space to prevent confusion.30 unmodified lines3132333435363730 unmodified linesSECRETS_TO_SET = ["SARVAM_API_KEY", "VOYAGE_API_KEY", "NVIDIA_NIM_API_KEY","OPENROUTER_API_KEY", "GROQ_API_KEY","GOOGLE_API_KEY", # KI-179 (2026-05-15) — Gemini Flash via Google AI Studio"ADMIN_IP_ALLOWLIST", "ADMIN_PASSWORD",]# Truly retired providers — delete from Space to prevent confusion.