AI-powered policy renewal system โ 21 autonomous agents across 5 layers, handling WhatsApp ยท Email ยท Voice outreach, UPI payments, IRDAI compliance, and human escalation for life insurance renewal.
The problem: Insurance companies lose revenue when customers forget to renew their policies. Manual follow-up by human agents is slow, expensive, and inconsistent.
The solution: RenewAI is a fully automated renewal engine. When a policy is due, the system:
- Analyses the customer (segment, lapse risk, best contact time)
- Reaches out via WhatsApp, Email, or Voice โ in their language
- Checks every message for quality, safety, and IRDAI compliance before sending
- Collects payment via UPI link, QR code, or AutoPay
- Escalates to a human specialist only when AI cannot handle it
- Learns from outcomes โ each paid/lapsed result makes the next prediction more accurate
๐ก In production terms: one agent handles ~500 renewal reminders/day, with < 2% escalation rate and full IRDAI audit trail โ zero human effort for standard cases.
Tech: Python 3.10 ยท Gemini AI (gemini-2.5-pro / gemini-2.5-flash) ยท LangGraph ยท ChromaDB ยท ElevenLabs TTS ยท Twilio ยท Razorpay ยท SQLite ยท Streamlit
Four advanced AI-engineering patterns that make RenewAI production-grade:
| # | Pattern | Where | What it does |
|---|---|---|---|
| ๐ต | RAG โ Retrieval-Augmented Generation | knowledge/ |
170+ documents (FAQs, objections, IRDAI rules) grounded into every agent prompt via ChromaDB |
| ๐ฃ | Plan & Execute Framework | agents/layer1_strategic/orchestrator.py |
LangGraph state machine plans the full journey before any message is sent |
| ๐ | Model Tracing & Observability | observability/ ยท prompts/ |
Every Gemini call traced: token count, cost in โน/USD, SHA-256 audit chain |
| ๐ด | Critique Agent | agents/layer3_quality/critique_agent.py |
gemini-2.5-pro reviews every outbound message before it leaves the system |
Jump directly to detailed sections: RAG โ ยท Plan & Execute โ ยท Model Tracing โ ยท Critique Agent โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ PROJECT RENEWAI โ 5-LAYER AGENT SYSTEM โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ
โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ LAYER 1 โ STRATEGIC (gemini-2.5-pro) [PLAN & EXECUTE] โ โ
โ โ [Segmentation] โ [Propensity] โ [Timing] โ [Channel] โ [Orchestrator] โ โ
โ โ LangGraph state machine: segmentโpropensityโtimingโchannelโbuild_journey โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ journey plan (planned before execution) โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ LAYER 2 โ EXECUTION (gemini-2.5-flash) [RAG GROUNDED] โโ
โ โ [Dispatcher] โ [WhatsApp] โ [Email] โ [Voice] โ [Payment] โ [ObjectionโRAG] โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ messages + results โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ LAYER 3 โ QUALITY & SAFETY (gemini-2.5-pro + flash) [CRITIQUE AGENT] โ โ
โ โ [Critiqueโ
] โ [Safety] โ [Compliance] โ [Sentiment] โ [Quality Scorer] โ โ
โ โ scoreโฅ70 โ L4 learning โ score<70 or safety_flag=0 โ L5 escalation โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ routing decision โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ LAYER 4 โ LEARNING (gemini-2.5-flash) [MODEL TRACING + COST] โ โ
โ โ [Feedback Loop] โ [A/B Manager] โ [Drift Detector] โ [Report Agent] โ โ
โ โ โบ insights loop โ Orchestrator โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ escalation trigger โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ LAYER 5 โ HUMAN ESCALATION โ โ
โ โ [Queue Manager] โ [20 Specialists] โ [Supervisor Dashboard] โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Every agent prompt is grounded in verified knowledge โ no hallucinated policy terms, no made-up premium amounts.
Instead of relying on the LLM's parametric memory, RenewAI injects retrieved facts directly into every Gemini prompt at call time. The Knowledge Base is built once (idempotent) and queried in milliseconds for every agent invocation.
knowledge/
โโโ rag_knowledge_base.py โ single file, 887 lines
โ
โโโ PRODUCT_FAQS (10 docs)
โ faq_001 What is Term Insurance?
โ faq_002 What is an Endowment Policy?
โ faq_003 What is a ULIP?
โ faq_004 Pension / Annuity Plan
โ faq_005 Money Back Policy
โ faq_006 Health Insurance Rider
โ faq_007 Grace Period & Lapse Revival
โ faq_008 Free Look Period (IRDAI)
โ faq_009 Tax Benefits โ 80C / 10(10D)
โ faq_010 Nomination & Assignment
โ
โโโ OBJECTION RESPONSES (150 pairs ร 12 categories)
โ PRICE / AFFORDABILITY (15 pairs)
โ TRUST / COMPANY (12 pairs)
โ NEED / PRODUCT FIT (14 pairs)
โ TIMING / PROCRASTINATION (13 pairs)
โ EXISTING COVERAGE (11 pairs)
โ HEALTH / MEDICAL (12 pairs)
โ CLAIMS EXPERIENCE (10 pairs)
โ DIGITAL / PROCESS (11 pairs)
โ BEREAVEMENT / SENSITIVE (8 pairs)
โ COMPETITOR COMPARISON (10 pairs)
โ POLICY LAPSE HISTORY (12 pairs)
โ GENERAL OBJECTIONS (12 pairs)
โ
โโโ BENEFIT CALCULATORS (6 docs)
โ Maturity ยท Tax ยท Surrender ยท Death benefit
โ
โโโ IRDAI COMPLIANCE DOCS (4 docs)
โ Key IRDAI rules ยท Grievance ยท Free-look ยท Cooling-off
โ
โโโ RENEWAL SCRIPTS (6 docs)
Empathetic ยท Urgent ยท Friendly opening + closing scripts
kb.query("what is sum assured", n=3)
โ
โโโ ChromaDB available?
โ YES โ sentence-transformers embeddings โ semantic similarity search
โ
โโโ ChromaDB unavailable? (CI / lightweight env)
NO โ keyword overlap fallback (TF-IDF style) โ zero extra dependencies
# ObjectionHandler โ pulls top 3 matching objection responses before calling Gemini
kb = RagKnowledgeBase()
ctx = kb.build_context("premium is too high for my budget", n=3)
# โ injects [OBJECTION โ Premium Too High]\n... into the LLM prompt
# Any agent can call:
match = kb.get_objection_response("I already have LIC coverage")
docs = kb.query("IRDAI free look period rules", n=2, category="compliance")
ctx = kb.build_context("endowment maturity calculation", n=3)| File | Role |
|---|---|
knowledge/rag_knowledge_base.py |
Full corpus + ChromaDB indexing + keyword fallback (887 lines) |
knowledge/chroma_db/ |
Persisted ChromaDB vector store |
agents/layer2_execution/objection_handler.py |
Primary consumer โ RAG-grounded rebuttals |
memory/customer_memory.py |
Per-customer interaction history injected into prompts |
The system builds a complete multi-channel journey plan before sending a single message โ no reactive, one-shot prompting.
RenewAI implements the Plan โ Execute โ Observe โ Re-plan loop as a formal LangGraph state machine. Layer 1 is the Planner; Layers 2โ5 are the Executors.
โโโโโโโโโโโโโโโโ PLAN PHASE (Layer 1 โ LangGraph) โโโโโโโโโโโโโโโโโ
โ โ
โ START โ
โ โ โ
โ โผ โ
โ node_segment โ
โ SegmentationAgent (gemini-2.5-pro) โ
โ โ segment: champion / at_risk / dormant / high_risk โ
โ โ recommended_tone ยท recommended_strategy ยท risk_flag โ
โ โ โ
โ โผ โ
โ node_propensity โ
โ PropensityAgent (gemini-2.5-pro) โ
โ โ lapse_score: 0โ100 โ
โ โ intervention_intensity: urgent / intensive / moderate โ
โ โ top_reasons ยท recommended_actions โ
โ โ โ
โ โผ โ
โ node_timing โ
โ TimingAgent (gemini-2.5-flash) โ
โ โ best_contact_window: "18:00โ20:00" โ
โ โ best_days: ["Monday", "Wednesday"] โ
โ โ salary_day_flag ยท urgency_override โ
โ โ โ
โ โผ โ
โ node_channel โ
โ ChannelSelectorAgent (gemini-2.5-flash) โ
โ โ channel_sequence: [whatsapp, email, voice] โ
โ โ โ
โ โผ โ
โ node_build_journey โ
โ Assembles RenewalJourney with ordered JourneyStep list โ
โ โ persisted to SQLite immediately โ
โ โ โ
โ โผ โ
โ END โ journey object returned โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโ EXECUTE PHASE (Layers 2โ3) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Dispatcher reads the journey plan step-by-step โ
โ For each step โ fires the correct agent (WA / Email / Voice) โ
โ After execution โ Quality Gate (Critique โ Safety โ Compliance) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโ OBSERVE + RE-PLAN (Layer 4 โ Layer 1) โโโโโโโโโโโโโโโโโโโโโ
โ FeedbackLoop records outcome (paid / lapsed / objected) โ
โ DriftDetector checks for distribution shift โ
โ ReportAgent surfaces A/B winners + drift anomalies โ
โ โบ Orchestrator updated: best_channel, drift anomaly count โ
โ PropensityAgent.refresh_from_feedback() re-calibrates model โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Planner encodes intensity-based scheduling โ journeys are scheduled relative to policy due date, not ad-hoc:
INTENSITY_START offsets (days before due date):
urgent โ D-3 (or same day if < 3 days left)
intensive โ D-5
moderate โ D-7
light โ D-14
none โ D-5
Channel gap (days between consecutive steps):
WhatsApp โ 1 day
Email โ 2 days
Voice โ 1 day
SMS โ 1 day
result = run_batch_with_feedback(
customer_policy_pairs = [(c1, p1), (c2, p2), ...],
run_feedback_loop = True,
)
# โ {"journeys": [...], "feedback": FeedbackSummary, "prompt_refreshed": bool}
# PropensityAgent auto-recalibrates if >= 10 strong-signal events exist| File | Role |
|---|---|
agents/layer1_strategic/orchestrator.py |
LangGraph graph, all 5 nodes, run_layer1(), run_batch_with_feedback() |
agents/layer1_strategic/segmentation.py |
Node 1 โ CustomerSegment + tone/strategy |
agents/layer1_strategic/propensity.py |
Node 2 โ lapse_score + few-shot feedback loop |
agents/layer1_strategic/timing.py |
Node 3 โ contact window + urgency override |
agents/layer1_strategic/channel_selector.py |
Node 4 โ ordered channel sequence |
agents/layer2_execution/dispatcher.py |
Executor โ walks the journey step list |
Every Gemini call is logged with token counts, โน cost, agent identity, and a tamper-evident SHA-256 audit chain.
EVERY AGENT ACTION
โ
โโโโบ 1. COST TRACKER (observability/cost_tracker.py)
โ Captures per-call: model ยท input tokens ยท output tokens ยท USD cost ยท INR cost
โ
โ Pricing table (per 1K tokens):
โ gemini-2.5-flash โ $0.00015 in / $0.00060 out
โ gemini-2.5-pro โ $0.00125 in / $0.00500 out
โ Also tracks:
โ ElevenLabs $0.0003 / 1K chars
โ Twilio $0.005 / message (India)
โ Razorpay $0.002 / payment link
โ Roll-ups: per-journey ยท per-agent ยท per-day ยท per-model
โ Budget alert: warns when daily spend crosses Rs.500
โ
โโโโบ 2. AUDIT TRAIL (observability/audit_trail.py)
โ Append-only SQLite table โ no DELETE / UPDATE ever
โ SHA-256 chain hash: hash_n = SHA256(hash_{n-1} + payload_n)
โ any tampered record breaks the chain
โ Categories: COMMUNICATION ยท PAYMENT ยท ESCALATION
โ DATA_ACCESS ยท AGENT_ACTION ยท COMPLIANCE
โ IRDAI 5-year retention compliant
โ
โโโโบ 3. PROMPT REGISTRY (prompts/ package)
All 15 LLM prompt templates โ zero inline strings in agent code
prompts/layer1.py โ SEGMENTATION, PROPENSITY, TIMING, CHANNEL
prompts/layer2.py โ WA, EMAIL, VOICE, OBJECTION
prompts/layer3.py โ CRITIQUE, COMPLIANCE, SAFETY, SENTIMENT
prompts/layer4.py โ ENRICH, BRIEF
prompts/layer5.py โ ESCALATION
Every CostTracker.track_gemini() call writes a structured row:
event_id : EVT-A3F92C11
agent_name : critique_agent
model : gemini-2.5-pro
journey_id : JRN-F1037D93
input_tokens : 842
output_tokens : 156
cost_usd : $0.001858
cost_inr : Rs.0.1561
timestamp : 2026-03-10 05:25:09
All 15 LLM prompts live in prompts/ โ zero inline strings anywhere in agent code:
Before (scattered): After (prompts/ package):
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
objection_handler.py line 88 from prompts.layer2 import OBJECTION_PROMPT
critique_agent.py line 112 from prompts.layer3 import CRITIQUE_PROMPT
safety_agent.py line 95 from prompts.layer3 import SAFETY_PROMPT
report_agent.py line 201 from prompts.layer4 import ENRICH_PROMPT
...11 other files โ one file change to update any prompt
The 7-page Streamlit dashboard (dashboard/app.py) surfaces all trace data in real-time:
| Page | Metric shown |
|---|---|
| Overview | Total spend today vs Rs.500 budget |
| Cost Tracker | Per-agent breakdown, model distribution pie |
| Audit Trail | Chain-hash integrity, category filter |
| Quality | Per-customer quality scores over time |
| A/B Tests | Winner per variant type, lift %, significance |
| Drift Monitor | OK / WARNING / CRITICAL per dimension |
| Escalation Queue | Open cases, SLA countdown |
| File | Role |
|---|---|
observability/cost_tracker.py |
track_gemini(), track_elevenlabs(), daily_summary() |
observability/audit_trail.py |
Append-only log with SHA-256 chain |
prompts/ |
All 15 LLM prompt templates โ one place to edit |
dashboard/app.py |
Streamlit UI over live SQLite data |
No message ever reaches a customer without passing a
gemini-2.5-proreview for tone, accuracy, personalisation, and IRDAI compliance.
The Critique Agent is the first node in the Layer 3 Quality Gate. It receives the full message text + customer profile + policy data, calls gemini-2.5-pro, and returns a structured verdict before the message is dispatched.
OUTBOUND MESSAGE DRAFTED (by WA / Email / Voice Agent)
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CRITIQUE AGENT (gemini-2.5-pro) โ
โ โ
โ Evaluates on 4 dimensions: โ
โ โ
โ 1. TONE SCORE (1โ10) โ
โ Is the message empathetic, not pushy? โ
โ Does it match the customer segment & situation? โ
โ โ
โ 2. ACCURACY SCORE (1โ10) โ
โ Are the policy number, premium, due date correct? โ
โ No invented figures or hallucinated terms? โ
โ โ
โ 3. PERSONALISATION SCORE (1โ10) โ
โ Does it use the customer's name, language, โ
โ and reference their specific policy? โ
โ โ
โ 4. CONVERSION LIKELIHOOD (1โ10) โ
โ Based on segment + tone + urgency โ how likely is โ
โ this message to drive a renewal payment? โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
CritiqueResult returned
โ
โโโโโโโโโโดโโโโโโโโโ
โ โ
approved=True approved=False
โ โ
โผ โผ
Continue to Rewrite generated by Critique Agent
Safety Agent โ re-evaluated before sending
You are a senior communication quality reviewer for Suraksha Life Insurance.
CUSTOMER PROFILE:
Name: {name} Segment: {segment} Language: {language}
Age: {age} Occupation: {occupation}
POLICY:
Number: {policy_number} Premium: Rs.{premium:,}
Days to Lapse: {days_to_lapse} Lapse Score: {lapse_score}/100
MESSAGE (channel={channel}):
{message}
Return JSON:
{
"approved": true/false,
"tone_score": 1-10,
"accuracy_score": 1-10,
"personalisation_score": 1-10,
"conversion_likelihood": 1-10,
"issues": ["list of specific issues found"],
"rewrite": "improved version if rejected, else null",
"overall_verdict": "one sentence summary"
}
Be strict. Reject any message that is pushy, factually wrong, or generic.
The Critique Agent is Node 1 of a 5-node pipeline โ all must pass before the message is stored and scored:
Layer 3 Quality Gate
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
[1] CritiqueAgent gemini-2.5-pro tone ยท accuracy ยท personalisation ยท conversion
โ (approved=True OR rewrite applied)
[2] SafetyAgent gemini-2.5-flash distress ยท mis-selling ยท coercion ยท PII leak
โ (safety_score > 0)
[3] ComplianceAgent gemini-2.5-flash IRDAI R03 ยท R04 ยท R08 checks
โ (compliance_score >= 80)
[4] SentimentAgent gemini-2.5-flash customer sentiment trend (-1.0 to +1.0)
โ
[5] QualityScoringAgent weighted composite โ saved to DB
โโโ total_score >= 70 โ ROUTE TO LAYER 4 (learning)
total_score < 70 โ ROUTE TO LAYER 5 (human escalation)
safety_score = 0.0 โ IMMEDIATE LAYER 5 ESCALATION
Quality Score (0โ100):
Critique (tone + accuracy + personalisation + conversion) / 4 ร 30%
Safety 0.0 = immediate block ยท 1.0 = clear ร 30%
Compliance IRDAI rules passed / total rules checked ร 25%
Sentiment mapped -1.0โ+1.0 to 0โ100 ร 15%
| File | Role |
|---|---|
agents/layer3_quality/critique_agent.py |
Core agent โ CritiqueAgent.run(), mock + live |
agents/layer3_quality/safety_agent.py |
Safety flag detection (distress, mis-selling) |
agents/layer3_quality/compliance_agent.py |
IRDAI R03/R04/R08 rule checks |
agents/layer3_quality/sentiment_agent.py |
Sentiment scoring + trend tracking |
agents/layer3_quality/quality_scoring.py |
Composite scorer โ DB persist |
prompts/layer3.py |
All 4 Layer 3 prompt templates |
CUSTOMER POLICY DUE
โ
โโโโโโโโโโโโโโผโโโโโโโโโโโโ
โ SEGMENTATION AGENT โ
โ champion / at_risk / โ
โ dormant / churned โ
โโโโโโโโโโโโโโฌโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโผโโโโโโโโโโโโ
โ PROPENSITY SCORER โ
โ lapse_score: 0โ100 โ
โโโโโโโโโโโโโโฌโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโผโโโโโโโโโโโโ
โ TIMING OPTIMIZER โ
โ best time + day โ
โโโโโโโโโโโโโโฌโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโผโโโโโโโโโโโโ
โ CHANNEL SELECTOR โ
โ WhatsApp / Email / โ
โ Voice / Multi โ
โโโโโโโโโโโโโโฌโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโผโโโโโโโโโโโโ
โ MASTER ORCHESTRATOR โ
โ builds journey plan โ
โโโโโโโโโโโโโโฌโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโ
โ โ โ
โโโโโโโโโโโโผโโโ โโโโโโโโโโโโผโโโ โโโโโโโโโโโโผโโโ
โ WhatsApp โ โ Email โ โ Voice โ
โ Agent โ โ Agent โ โ Agent โ
โ (Twilio) โ โ (SMTP) โ โ (ElevenLabs)โ
โโโโโโโโโโโโฌโโโ โโโโโโโโโโโโฌโโโ โโโโโโโโโโโโฌโโโ
โ โ โ
โโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโผโโโโโโโโโโโโ
โ QUALITY GATE (L3) โ
โ critique โ safety โ โ
โ compliance โ score โ
โโโโโโโโโโโโโโฌโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโ
โ โ
โโโโโโโโโโโผโโโโโโโโโ โโโโโโโโโโโโโโโผโโโโโโโ
โ SCORE >= 70 โ โ SCORE < 70 OR โ
โ โ
CONTINUE โ โ SAFETY FLAG โ
โ โ โ ESCALATE โ
โโโโโโโโโโโฌโโโโโโโโโ โโโโโโโโโโโโโโโฌโโโโโโโ
โ โ
โโโโโโโโโโโผโโโโโโโโโ โโโโโโโโโโโโโโโผโโโโโโโ
โ PAYMENT AGENT โ โ HUMAN QUEUE (L5) โ
โ UPI deep link โ โ 20 specialists โ
โ QR code PNG โ โ skill routing โ
โ AutoPay/NACH โ โ SLA tracking โ
โ NetBanking โ โโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโฌโโโโโโโโโ
โ
โโโโโโโโโโโผโโโโโโโโโ
โ PAYMENT SUCCESS โ
โ โ
POLICY RENEWEDโ
โ PAS updated โ
โ CRM synced โ
โ IRDAI logged โ
โโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ SUPPORTED LANGUAGES (ElevenLabs multilingual_v2) โ
โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Language โ Greeting โ States / Regions โ
โโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Hindi hi โ namaste โ UP, MP, Bihar, Delhi, Raj โ
โ English en โ Hello โ Pan-India default โ
โ Tamil ta โ vanakkam โ Tamil Nadu, Sri Lanka โ
โ Telugu te โ namaskaram โ Andhra, Telangana โ
โ Kannada kn โ namaskara โ Karnataka โ
โ Malayalam mlโ namaskaram โ Kerala โ
โ Bengali bn โ namaskar โ West Bengal, Bangladesh โ
โ Marathi mr โ namaskar โ Maharashtra โ
โ Gujarati gu โ namaste โ Gujarat โ
โโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
PAYMENT AGENT
โ
โโโโบ UPI Deep Link โโโโโโโบ upi://pay?pa=suraksha.life@razorpay
โ &pn=Suraksha Life Insurance
โ &am=<premium>&cu=INR
โ
โโโโบ QR Code PNG โโโโโโโโโบ qrcode lib โ real PNG bytes โ base64
โ embeddable in WhatsApp / email
โ
โโโโบ AutoPay Mandate โโโโโบ UPI AutoPay / NACH
โ Razorpay Subscription API (real mode)
โ
โโโโบ NetBanking Links โโโบ SBI โ HDFC โ ICICI โ AXIS
KOTAK โ BOB โ PNB โ UNION
ESCALATION TRIGGER
โ
โผ
REASON DETECTED
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ distress โ mis_selling โ bereavement โ complaint โ
โ requested_human โ payment_failure โ legal โ medical โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
SKILL-BASED ROUTING
โ
โโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโ
โ โ โ
โโโโโโโโผโโโโโโโ โโโโโโโโโโโผโโโโโโโ โโโโโโโโโโโผโโโโโโโ
โ WELLNESS โ โ COMPLIANCE โ โ CLAIMS โ
โ Team (3) โ โ Team (3) โ โ Team (4) โ
โ distress โ โ mis_selling โ โ complaint โ
โ bereavementโ โ legal โ โ medical_query โ
โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโ
โ โ โ
โโโโโโโโผโโโโโโโ โโโโโโโโโโโผโโโโโโโ โโโโโโโโโโโผโโโโโโโ
โ RENEWAL โ โ TECH & โ โ SENIOR / โ
โ Team (5) โ โ PAYMENTS (3) โ โ ESCALATION(2) โ
โ requested โ โ payment_query โ โ ALL SKILLS โ
โ upsell โ โ mandate setup โ โ P1 PRIORITY โ
โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโ
SLA: P1 Urgent = 1h โ P2 High = 4h โ P3 Normal = 24h โ P4 Low = 72h
Every time a customer pays or lapses, the outcome is stored as a feedback_event. Once 10+ strong-signal events accumulate, the FeedbackLoopAgent automatically calls PropensityAgent.refresh_from_feedback(). This rebuilds the Gemini prompt with real few-shot examples drawn from actual outcomes โ no retraining, no manual work.
OUTCOME RECORDED (paid / lapsed)
โ
โผ
FeedbackLoopAgent.run()
outcome scores stored in DB ยท A/B test + drift check run
โ
โผ
>= 10 strong-signal events?
โ
Yes โผ
PropensityAgent.refresh_from_feedback()
reads top 5 PAID + top 5 LAPSED from real data
builds few-shot block:
age=42 ยท Mumbai ยท score=0.87 โ PAID
age=58 ยท Pune ยท score=0.21 โ LAPSED
stores in module-level cache _FEEDBACK_FEW_SHOT
โ
โผ
Next PropensityAgent.run() call
few-shot block prepended to Gemini prompt
lapse_score is now grounded in real outcomes
Key files:
| File | What it does |
|---|---|
agents/layer1_strategic/propensity.py |
refresh_from_feedback() + _FEEDBACK_FEW_SHOT cache |
agents/layer4_learning/feedback_loop.py |
Auto-triggers refresh at end of run() |
agents/layer1_strategic/orchestrator.py |
run_batch_with_feedback() โ batch + auto-learn in one call |
tests/test_feedback_propensity_loop.py |
7 tests covering the full loop |
EVERY API CALL
โ
โโโโบ COST TRACKER โโโโโโโบ SQLite cost_events table
โ Gemini (per model, in/out tokens) Daily budget: Rs.500
โ ElevenLabs (per 1K chars) Alert on breach
โ Twilio (per message)
โ Razorpay (per transaction)
โ
โโโโบ AUDIT TRAIL โโโโโโโโบ SQLite audit_trail table (append-only)
SHA-256 chain hash (tamper-evident)
Categories: COMMUNICATION โ PAYMENT โ ESCALATION
DATA_ACCESS โ AGENT_ACTION โ COMPLIANCE
IRDAI 5-year retention compliant
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ INTEGRATION STUBS โ
โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ CRM โ upsert_contact, log_interaction, create_task โ
โ Stub โ โ Salesforce / Zoho / custom CRM (real mode) โ
โโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ PAS โ get_policy, update_renewal_status, grace_period โ
โ Stub โ โ DuckCreek / Majesco / in-house PAS โ
โโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ IRDAI โ report_communication, file_grievance, ack, close โ
โ Stub โ โ IRDAI Bima Bharosa portal โ
โโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Payment GW โ parse_webhook, verify_payment, HMAC validation โ
โ Stub โ โ Razorpay (payment.captured / failed / refund) โ
โโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
InsuranceAI/
โ
โโโ agents/
โ โโโ layer1_strategic/ # Segmentation, Propensity, Timing, Channel, Orchestrator
โ โโโ layer2_execution/ # WhatsApp, Email, Voice, Payment, Objection, Language Utils
โ โโโ layer3_quality/ # Critique (โ
), Safety, Compliance, Sentiment, Quality Scorer
โ โโโ layer4_learning/ # Feedback Loop, A/B Manager, Drift Detector, Report Agent
โ โโโ layer5_human/ # Queue Manager (20 specialists), Supervisor Dashboard
โ
โโโ prompts/ (โ
) All 15 LLM prompt templates โ centralised registry
โ โโโ layer1.py # SEGMENTATION, PROPENSITY, TIMING, CHANNEL prompts
โ โโโ layer2.py # WA, EMAIL, VOICE, OBJECTION prompts
โ โโโ layer3.py # CRITIQUE (โ
), COMPLIANCE, SAFETY, SENTIMENT prompts
โ โโโ layer4.py # ENRICH, BRIEF prompts
โ โโโ layer5.py # ESCALATION prompt
โ
โโโ knowledge/ (โ
) RAG Knowledge Base โ 170+ documents
โ โโโ rag_knowledge_base.py # Corpus + ChromaDB index + keyword fallback
โ โโโ chroma_db/ # Persisted ChromaDB vector store
โ
โโโ memory/ # Customer memory store (ChromaDB + SQLite)
โ โโโ customer_memory.py # Per-customer context โ channel pref, sentiment, objections
โ
โโโ observability/ (โ
) Model Tracing
โ โโโ cost_tracker.py # Token + API cost tracking (Rs. + USD) โ per call
โ โโโ audit_trail.py # IRDAI-compliant SHA-256 append-only audit log
โ
โโโ core/
โ โโโ config.py # All settings + Gemini client helpers
โ โโโ models.py # Pydantic data models
โ โโโ database.py # SQLite helpers + seed
โ
โโโ dashboard/
โ โโโ app.py # 7-page Streamlit admin dashboard
โ โโโ data_service.py # Read-only DB query layer
โ
โโโ integrations/
โ โโโ crm_stub.py # CRM integration (Salesforce/Zoho)
โ โโโ pas_stub.py # Policy Administration System
โ โโโ irdai_stub.py # IRDAI regulatory reporting
โ โโโ payment_gw_stub.py # Razorpay webhook handler
โ
โโโ data/
โ โโโ seed.py # Sample data seeder
โ โโโ renewai.db # SQLite database
โ
โโโ run_e2e.py # Full 5-layer live demo runner
โโโ tests/ # 206 unit tests (~8s)
โโโ pytest.ini # Default: skip e2e tests
โโโ requirements.txt
โโโ .env # API keys (gitignored)
| Component | Technology |
|---|---|
| LLM โ Orchestration | gemini-2.5-pro |
| LLM โ Execution | gemini-2.5-flash |
| LLM โ Critique / Review (โ ) | gemini-2.5-pro |
| LLM โ Safety / Classify | gemini-2.5-flash |
| Agent Framework (โ ) | LangGraph โ Plan & Execute state machine |
| RAG โ Vector DB (โ ) | ChromaDB (persistent) + keyword fallback |
| RAG โ Corpus (โ ) | 170+ documents (FAQs, objections, IRDAI rules, scripts) |
| Model Tracing (โ ) | Custom CostTracker + AuditTrail (SHA-256 chain) |
| Prompt Registry (โ ) | prompts/ package โ 15 templates, zero inline strings |
| Voice TTS | ElevenLabs eleven_multilingual_v2 |
| Twilio Sandbox | |
| SMTP (MailHog local / SendGrid prod) | |
| Payments | Razorpay โ UPI, QR, AutoPay, NetBanking |
| Customer Memory | SQLite + ChromaDB |
| Database | SQLite |
| Dashboard | Streamlit + Plotly |
| Testing | pytest โ 206 tests |
| Language | Python 3.10 |
(โ ) = RAG ยท Plan & Execute ยท Model Tracing ยท Critique Agent โ the four highlighted patterns
# 1. Clone & install
git clone https://github.com/Brohammad/InsuranceAI
cd InsuranceAI
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
# 2. Configure
cp .env.example .env
# Edit .env โ fill in:
# GEMINI_API_KEY=AIza...
# ELEVENLABS_API_KEY=sk_...
# TWILIO_ACCOUNT_SID=AC...
# TWILIO_AUTH_TOKEN=...
# TWILIO_WHATSAPP_FROM=whatsapp:+14155238886
# RAZORPAY_KEY_ID=rzp_test_...
# RAZORPAY_KEY_SECRET=...
# 3. Seed database
python data/seed.py
# 4. Run tests (206 fast unit tests)
pytest # unit tests only (~8s)
pytest -m e2e # full e2e with real Gemini (~14min)
# 5. Run full E2E demo (all 5 layers)
python run_e2e.py # fresh seed + all 3 customers + all 5 layers
# 6. Launch dashboard
streamlit run dashboard/app.py
# โ http://localhost:8501Real output from
python run_e2e.pyโ all 5 layers, 3 customers, fresh DB seed.
โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ ๐ก๏ธ RenewAI โ Full End-to-End Run โ
โ Mock mode โข All 5 layers โข DB updates verified in real-time โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
Table Rows
โโโโโโโโโโโโโโโโโโโโโโโโโ
renewal_journeys 6 โ 6 pre-paid baseline journeys
interactions 0
quality_scores 0
ab_test_results 0
โโโโโโโโ โถ Customer 1/3: Fatima Khan (due in 2 days) โโโโโโโโโโ
โ Layer 1 โ Segmentation โ Propensity โ Timing โ Channel
Segmented SLI-1419237 | Fatima Khan โ [high_risk] | risk=high
Propensity scored | Fatima Khan โ score=85 | intensity=urgent
Timing | Fatima Khan โ 18:00-20:00 on [Mon, Wed] | urgency=True
Channel | Fatima Khan โ ['whatsapp', 'email', 'voice']
โ
Journey created: JRN-F1037D93 โ Segment: high_risk โ Steps: 3
๐ค Layer 2 โ Dispatching messages
WA sent WA-69E3E4D668 โ Fatima Khan | outcome=read
Email EMAIL-C83DA1CA โ Fatima Khan | outcome=no_response
Voice CALL-4D03B912 โ Fatima Khan | outcome=responded | intent=interested | 141s
Payment TXN-3C869ED7 โ Rs.11,000 | qr=1123B | autopay=yes | banks=8
๐ Layer 3 โ Quality Gate
โ
Quality score: 88.6 Grade: B
โ
Score 88.6 โฅ 70 โ routing to L4 learning
โโโโโโโโ โถ Customer 2/3: Mohammed Iqbal (due in 4 days) โโโโโโโ
โ Layer 1 โ Journey JRN-846C2D4D โ high_risk โ score=85 โ Steps: 3
๐ค Layer 2 โ WA: payment_made โ journey stopped (payment received)
๐ Layer 3 โ Score 88.6 โฅ 70 โ L4
โโโโโโโโ โถ Customer 3/3: Rekha Nambiar (due in 5 days) โโโโโโโโ
โ Layer 1 โ Journey JRN-38DBF154 โ high_risk โ score=85 โ Steps: 3
๐ค Layer 2 โ WA: read | Email: delivered | Voice: payment_made โ journey stopped
๐ Layer 3 โ Score 88.6 โฅ 70 โ L4
โโโโโโโ ๐ Layer 4 โ Feedback โ A/B Test โ Drift โ Report โโโโโโ
Journeys routed to L4 : 3 (score โฅ 70)
Events processed : 7 โ Positive: 6 โ Negative: 1
A/B channel โ winner=voice conv=50.0% lift=+50.2%
Drift โ โ WARNING โ 2 anomalies detected
Report โ outputs/reports/report_daily_20260310_052518.md โ
โบ Insights loop โ Orchestrator: best_channel=voice | 2 drift alerts
โโ ๐จ Layer 5 โ Human Escalation Queue + Supervisor Dashboard โโโ
Journeys routed to L5 : 0 (all scores โฅ 70 this run)
Renewal Rate: 88.9% โ Premium Recovered: Rs.581,700
Avg Quality Score: 88.6/100 โ IRDAI Compliance: 100.0%
Escalation Queue: โ empty โ no open escalations
โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ โ
End-to-End Run Complete! โ
โ โข 3 journeys created & dispatched โ
โ โข 3 quality scores written (renewal_journeys: 9, interactions: 7) โ
โ โข DB updated in real-time โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
Why these specific technologies and patterns โ and what the alternatives were.
| Option | Why rejected |
|---|---|
| Plain sequential function calls | No state schema โ agent outputs are dict-scattered, hard to test individual nodes |
| LangChain AgentExecutor | Tool-calling loop model doesn't fit a deterministic pipeline with fixed node order |
| LangGraph StateGraph โ | Typed JourneyState TypedDict enforces what each node reads and writes; nodes are independently unit-testable; graph is inspectable; easy to add conditional edges later (e.g. skip voice for DND customers) |
The key constraint: Layer 1 must plan first, execute later โ the entire journey (channels, timing, steps) is assembled before a single message is sent. LangGraph's compile-then-invoke model maps directly onto that.
| Concern | Answer |
|---|---|
| "Won't SQLite break under load?" | This is a single-tenant renewal engine (one insurer, one portfolio). At 500 journeys/day, SQLite handles this comfortably; it's used in production by many apps at this scale. |
| "Concurrent writes?" | All writes are from a single Python process in this architecture; WAL mode handles the rare concurrent dashboard read. |
| "Migration path?" | core/database.py is the only file that knows about SQLite โ swap the connection string and you're on Postgres with zero agent changes. |
SQLite also means zero infrastructure to set up for a new developer โ python data/seed.py and you're running. That was a deliberate "day-zero" design choice.
| Option | Trade-off |
|---|---|
| pgvector | Requires Postgres โ contradicts the zero-infra goal above |
| Pinecone / Weaviate | Network call + API key + cost for a 170-doc corpus โ overkill |
| ChromaDB local โ | Persists to knowledge/chroma_db/ on disk; zero network; works offline; the keyword fallback means tests pass even without sentence-transformers installed |
At 170 documents, semantic search quality from a local ChromaDB is indistinguishable from a cloud vector DB. The switch to Pinecone would be a one-line change in RagKnowledgeBase.__init__.
Every agent has a mock_delivery=True path that returns realistic, deterministic output without calling any external API. This was a deliberate design choice:
BENEFITS
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
1. 206 tests run in 8s with no API keys needed
2. CI/CD works without secrets in the pipeline
3. Developers can build new agents offline
4. Outcome distributions in mock mode are tuned to be realistic
(payment_made / read / no_response / objection in real ratios)
5. Switching to live mode is a single env-var: MOCK_DELIVERY=false
The mock layer is not a test stub โ it's a first-class code path that the full E2E run_e2e.py uses by default. Real API calls are opt-in via .env.
Inline prompt strings scattered across 14 agent files meant:
- A/B testing a prompt required finding it in a 200-line agent file
- Prompt changes weren't diff-reviewable in isolation
- No way to version or audit what prompt produced which output
The prompts/ package makes every prompt a named constant, importable, and diff-able. A prompt change shows as a clean one-file diff in git log --stat.
tests/test_language_utils.py 39 passed
tests/test_voice_agent.py 35 passed
tests/test_observability.py 35 passed
tests/test_integrations.py 35 passed
tests/test_dashboard.py 40 passed
tests/test_payment_agent.py 21 passed
tests/test_human_queue.py 11 passed
tests/test_feedback_propensity_loop.py 7 passed -- closed feedback loop
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
TOTAL 206 passed ~8s
| Commit | Feature |
|---|---|
ddeb6ee |
Foundation โ 21-agent system, all 5 layers |
3cfd910 |
Multi-language support โ 9 Indian languages |
953bf99 |
Voice agent โ ElevenLabs + IRDAI + intent detection |
2d6e7dc |
Payment agent โ UPI + QR + AutoPay + NetBanking |
7b16ac8 |
Admin dashboard โ 7-page Streamlit UI |
f6fb523 |
Observability (โ ) โ cost tracker + SHA-256 audit trail |
dc10d4f |
Integration stubs โ CRM, PAS, IRDAI, Payment GW |
b147c8a |
20-specialist human queue + skill-based routing |
59c0fbf |
Closed feedback loop โ PropensityAgent auto-recalibrates |
be9707a |
RAG Knowledge Base (โ ) โ 170+ docs, ChromaDB, keyword fallback |
6416b23 |
WORKFLOW.md โ beginner-friendly guide with glossary |
f31d558 |
Prompt Registry (โ
) โ all 15 LLM prompts to prompts/ package |
0f78ee9 |
Plan & Execute (โ ) + Critique Agent (โ ) โ workflow.xml compliance, L3โL4/L5 routing, full L4 sub-pipeline |
543068b |
docs: prominently highlight RAG, Plan & Execute, Model Tracing, Critique Agent in README |
3d0a004 |
docs: add .env.example, fix duplicate separator, E2E snapshot, Design Decisions section |
(โ ) = RAG ยท Plan & Execute ยท Model Tracing ยท Critique Agent โ the four highlighted patterns
Built for Suraksha Life Insurance ยท Project RenewAI ยท Python 3.10 ยท Gemini AI ยท LangGraph ยท ChromaDB ยท 21 Agents ยท 5 Layers ยท 206 Tests