Rahul-rr commited on
Commit
91651eb
·
1 Parent(s): 2f52cd9

Deploy CAMS Assistant

Browse files
action_engine.py ADDED
@@ -0,0 +1,401 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ action_engine.py
3
+ -----------------
4
+ Action Engine for the Voice & Chat Assistant.
5
+ Evaluates the LLM analysis result and triggers appropriate backend actions
6
+ based on the detected intent — with mandatory compliance checks before
7
+ executing any financial transactions.
8
+
9
+ Compliance-first design:
10
+ - Every action passes through a compliance gate
11
+ - Compliance flags (AML, SEBI, FATCA) block action execution
12
+ - All actions and compliance decisions are audit-logged
13
+ - No financial action is executed without a clean compliance check
14
+ """
15
+
16
+ import uuid
17
+ import logging
18
+ from schemas import (
19
+ LLMAnalysisResult,
20
+ ActionResult,
21
+ ActionStatus,
22
+ Intent,
23
+ Sentiment,
24
+ )
25
+
26
+ # ── Module Logger ────────────────────────────────────────────────────────────
27
+ logger = logging.getLogger(__name__)
28
+
29
+
30
+ # ── Compliance Keywords ───────────────────────────────────────────────────────
31
+ # Any of these flags in extracted entities will block action execution
32
+ # and trigger a compliance escalation for human review.
33
+ COMPLIANCE_BLOCK_KEYWORDS = {
34
+ "aml", "fatca", "suspicious", "fraud", "money laundering",
35
+ "sebi complaint", "court", "legal", "freeze", "blocked",
36
+ }
37
+
38
+
39
+ # ── Compliance Check ──────────────────────────────────────────────────────────
40
+ def _run_compliance_check(analysis: LLMAnalysisResult) -> tuple[bool, str]:
41
+ """
42
+ Run a compliance gate check before executing any financial action.
43
+
44
+ Checks for:
45
+ 1. Compliance flags in extracted entities (AML, FATCA, SEBI keywords)
46
+ 2. Suspicious transaction amounts (> ₹10,00,000 triggers AML review)
47
+ 3. Escalation flag set by the LLM
48
+
49
+ Args:
50
+ analysis (LLMAnalysisResult): The LLM analysis output containing
51
+ entities and escalation flags.
52
+
53
+ Returns:
54
+ tuple[bool, str]:
55
+ - bool: True if compliance passed (safe to proceed), False if blocked.
56
+ - str: Human-readable reason for the compliance decision.
57
+ """
58
+ logger.info("Running compliance check...")
59
+
60
+ # ── Check 1: Compliance flag in entities ─────────────────────────────
61
+ compliance_flag = analysis.entities.compliance_flag
62
+ if compliance_flag:
63
+ flag_lower = compliance_flag.lower()
64
+ for keyword in COMPLIANCE_BLOCK_KEYWORDS:
65
+ if keyword in flag_lower:
66
+ reason = (
67
+ f"Compliance flag detected: '{compliance_flag}'. "
68
+ f"Action blocked pending compliance team review."
69
+ )
70
+ logger.warning(f"Compliance BLOCKED | reason={reason}")
71
+ return False, reason
72
+
73
+ # ── Check 2: High-value transaction AML threshold ────────────────────
74
+ amount = analysis.entities.amount
75
+ if amount and amount > 1_000_000: # ₹10 Lakh threshold
76
+ reason = (
77
+ f"High-value transaction of ₹{amount:,.2f} detected. "
78
+ f"AML review required before processing."
79
+ )
80
+ logger.warning(f"Compliance BLOCKED (AML threshold) | amount={amount} | reason={reason}")
81
+ return False, reason
82
+
83
+ # ── Check 3: Escalation flag ──────────────────────────────────────────
84
+ if analysis.requires_escalation and analysis.intent == Intent.ESCALATION:
85
+ reason = "Customer explicitly requested escalation. Routing to human agent."
86
+ logger.info(f"Compliance CHECK — escalation triggered | reason={reason}")
87
+ return False, reason
88
+
89
+ logger.info("Compliance check PASSED. Action may proceed.")
90
+ return True, "Compliance check passed."
91
+
92
+
93
+ # ── Action Dispatcher ─────────────────────────────────────────────────────────
94
+ async def trigger_action(analysis: LLMAnalysisResult) -> ActionResult:
95
+ """
96
+ Evaluate the LLM analysis and trigger the appropriate backend action.
97
+
98
+ Flow:
99
+ 1. Run compliance check — block if flagged.
100
+ 2. Dispatch to the appropriate intent handler.
101
+ 3. Return a structured ActionResult with status, reference ID, and message.
102
+
103
+ Args:
104
+ analysis (LLMAnalysisResult): The full NLP analysis result from Groq LLM,
105
+ containing intent, entities, and escalation flag.
106
+
107
+ Returns:
108
+ ActionResult: The outcome of the triggered (or blocked) action, including:
109
+ - action_taken: What was attempted.
110
+ - status: Success / Blocked / Pending / Not Required.
111
+ - reference_id: Unique ID for audit trail.
112
+ - message: Human-readable outcome description.
113
+ - compliance_checked: Whether compliance gate was run.
114
+
115
+ Raises:
116
+ RuntimeError: If an unexpected error occurs during action dispatch.
117
+ """
118
+ logger.info(
119
+ f"Action engine triggered | intent={analysis.intent} | "
120
+ f"sentiment={analysis.sentiment} | escalation={analysis.requires_escalation}"
121
+ )
122
+
123
+ reference_id = str(uuid.uuid4())[:12].upper() # Short reference ID for audit
124
+
125
+ try:
126
+ # ── Step 1: Compliance Gate ───────────────────────────────────────
127
+ compliance_passed, compliance_reason = _run_compliance_check(analysis)
128
+
129
+ if not compliance_passed:
130
+ logger.warning(
131
+ f"Action BLOCKED by compliance gate | ref={reference_id} | "
132
+ f"reason={compliance_reason}"
133
+ )
134
+ return ActionResult(
135
+ action_taken = f"Attempted: {analysis.intent.value}",
136
+ status = ActionStatus.BLOCKED_COMPLIANCE,
137
+ reference_id = reference_id,
138
+ message = compliance_reason,
139
+ compliance_checked = True,
140
+ )
141
+
142
+ # ── Step 2: Intent-based Action Dispatch ─────────────────────────
143
+ intent = analysis.intent
144
+
145
+ if intent == Intent.REDEMPTION_REQUEST:
146
+ return await _handle_redemption(analysis, reference_id)
147
+
148
+ elif intent == Intent.ACCOUNT_STATEMENT:
149
+ return await _handle_account_statement(analysis, reference_id)
150
+
151
+ elif intent == Intent.COMPLIANCE_QUERY:
152
+ return await _handle_compliance_query(analysis, reference_id)
153
+
154
+ elif intent == Intent.PORTFOLIO_ENQUIRY:
155
+ return await _handle_portfolio_enquiry(analysis, reference_id)
156
+
157
+ elif intent == Intent.TRANSACTION_STATUS:
158
+ return await _handle_transaction_status(analysis, reference_id)
159
+
160
+ elif intent == Intent.KYC_UPDATE:
161
+ return await _handle_kyc_update(analysis, reference_id)
162
+
163
+ elif intent in (Intent.ESCALATION, Intent.UNKNOWN):
164
+ return await _handle_escalation(analysis, reference_id)
165
+
166
+ else:
167
+ # General enquiry or dividend info — informational, no action needed
168
+ logger.info(f"Intent '{intent}' requires no backend action.")
169
+ return ActionResult(
170
+ action_taken = f"Informational response for: {intent.value}",
171
+ status = ActionStatus.NOT_REQUIRED,
172
+ reference_id = reference_id,
173
+ message = "No backend action required for this query.",
174
+ compliance_checked = True,
175
+ )
176
+
177
+ except Exception as e:
178
+ logger.error(
179
+ f"Unexpected error in action engine | intent={analysis.intent} | "
180
+ f"ref={reference_id} | error={str(e)}",
181
+ exc_info=True,
182
+ )
183
+ raise RuntimeError(
184
+ f"Action engine failed for intent '{analysis.intent}': {str(e)}"
185
+ ) from e
186
+
187
+
188
+ # ── Intent Handlers ───────────────────────────────────────────────────────────
189
+
190
+ async def _handle_redemption(analysis: LLMAnalysisResult, ref_id: str) -> ActionResult:
191
+ """
192
+ Handle a mutual fund redemption request.
193
+
194
+ In production, this would call the CAMS redemption API.
195
+ Currently simulates successful initiation for prototype purposes.
196
+
197
+ Args:
198
+ analysis (LLMAnalysisResult): NLP result with entity details.
199
+ ref_id (str): Audit reference ID.
200
+
201
+ Returns:
202
+ ActionResult: Redemption initiation result.
203
+ """
204
+ logger.info(
205
+ f"Processing redemption request | investor={analysis.entities.investor_id} | "
206
+ f"fund={analysis.entities.fund_name} | amount={analysis.entities.amount} | "
207
+ f"ref={ref_id}"
208
+ )
209
+
210
+ # TODO: Replace with actual CAMS Redemption API call
211
+ # e.g., await cams_api.initiate_redemption(investor_id, fund_name, amount)
212
+
213
+ return ActionResult(
214
+ action_taken = "Redemption request initiated",
215
+ status = ActionStatus.PENDING,
216
+ reference_id = ref_id,
217
+ message = (
218
+ f"Your redemption request has been received and is being processed. "
219
+ f"Reference ID: {ref_id}. You will receive a confirmation within 1–2 business days."
220
+ ),
221
+ compliance_checked = True,
222
+ )
223
+
224
+
225
+ async def _handle_account_statement(analysis: LLMAnalysisResult, ref_id: str) -> ActionResult:
226
+ """
227
+ Handle an account statement request.
228
+
229
+ Args:
230
+ analysis (LLMAnalysisResult): NLP result with investor details.
231
+ ref_id (str): Audit reference ID.
232
+
233
+ Returns:
234
+ ActionResult: Statement request result.
235
+ """
236
+ logger.info(
237
+ f"Processing account statement request | investor={analysis.entities.investor_id} | "
238
+ f"ref={ref_id}"
239
+ )
240
+
241
+ # TODO: Replace with actual CAMS Statement API call
242
+
243
+ return ActionResult(
244
+ action_taken = "Account statement request processed",
245
+ status = ActionStatus.SUCCESS,
246
+ reference_id = ref_id,
247
+ message = (
248
+ f"Your account statement has been queued for generation. "
249
+ f"It will be sent to your registered email within 24 hours. Ref: {ref_id}."
250
+ ),
251
+ compliance_checked = True,
252
+ )
253
+
254
+
255
+ async def _handle_compliance_query(analysis: LLMAnalysisResult, ref_id: str) -> ActionResult:
256
+ """
257
+ Handle a compliance-related query (SEBI, AML, FATCA, KYC).
258
+
259
+ Compliance queries are always escalated to the compliance team.
260
+
261
+ Args:
262
+ analysis (LLMAnalysisResult): NLP result.
263
+ ref_id (str): Audit reference ID.
264
+
265
+ Returns:
266
+ ActionResult: Compliance query routing result.
267
+ """
268
+ logger.info(f"Routing compliance query to compliance team | ref={ref_id}")
269
+
270
+ return ActionResult(
271
+ action_taken = "Compliance query escalated to compliance team",
272
+ status = ActionStatus.PENDING,
273
+ reference_id = ref_id,
274
+ message = (
275
+ f"Your compliance query has been forwarded to our dedicated compliance team. "
276
+ f"A compliance officer will contact you within 2 business days. Ref: {ref_id}."
277
+ ),
278
+ compliance_checked = True,
279
+ )
280
+
281
+
282
+ async def _handle_portfolio_enquiry(analysis: LLMAnalysisResult, ref_id: str) -> ActionResult:
283
+ """
284
+ Handle a portfolio enquiry.
285
+
286
+ Args:
287
+ analysis (LLMAnalysisResult): NLP result.
288
+ ref_id (str): Audit reference ID.
289
+
290
+ Returns:
291
+ ActionResult: Portfolio enquiry result.
292
+ """
293
+ logger.info(
294
+ f"Processing portfolio enquiry | investor={analysis.entities.investor_id} | ref={ref_id}"
295
+ )
296
+
297
+ # TODO: Replace with actual CAMS Portfolio API call
298
+
299
+ return ActionResult(
300
+ action_taken = "Portfolio enquiry processed",
301
+ status = ActionStatus.SUCCESS,
302
+ reference_id = ref_id,
303
+ message = (
304
+ "Your portfolio details are being fetched. "
305
+ "Please check your registered email or the CAMS portal for the latest NAV and holdings."
306
+ ),
307
+ compliance_checked = True,
308
+ )
309
+
310
+
311
+ async def _handle_transaction_status(analysis: LLMAnalysisResult, ref_id: str) -> ActionResult:
312
+ """
313
+ Handle a transaction status check.
314
+
315
+ Args:
316
+ analysis (LLMAnalysisResult): NLP result.
317
+ ref_id (str): Audit reference ID.
318
+
319
+ Returns:
320
+ ActionResult: Transaction status result.
321
+ """
322
+ logger.info(
323
+ f"Checking transaction status | investor={analysis.entities.investor_id} | ref={ref_id}"
324
+ )
325
+
326
+ # TODO: Replace with actual CAMS Transaction Status API call
327
+
328
+ return ActionResult(
329
+ action_taken = "Transaction status lookup initiated",
330
+ status = ActionStatus.SUCCESS,
331
+ reference_id = ref_id,
332
+ message = (
333
+ "Your transaction status is being retrieved. "
334
+ "Please allow a few moments or check the CAMS portal for real-time updates."
335
+ ),
336
+ compliance_checked = True,
337
+ )
338
+
339
+
340
+ async def _handle_kyc_update(analysis: LLMAnalysisResult, ref_id: str) -> ActionResult:
341
+ """
342
+ Handle a KYC update request.
343
+
344
+ KYC updates require document verification; this creates a ticket.
345
+
346
+ Args:
347
+ analysis (LLMAnalysisResult): NLP result.
348
+ ref_id (str): Audit reference ID.
349
+
350
+ Returns:
351
+ ActionResult: KYC update request result.
352
+ """
353
+ logger.info(
354
+ f"Processing KYC update request | investor={analysis.entities.investor_id} | ref={ref_id}"
355
+ )
356
+
357
+ # TODO: Replace with actual KYC portal API call
358
+
359
+ return ActionResult(
360
+ action_taken = "KYC update request created",
361
+ status = ActionStatus.PENDING,
362
+ reference_id = ref_id,
363
+ message = (
364
+ f"A KYC update request has been created (Ref: {ref_id}). "
365
+ "Our team will contact you with the required document list within 1 business day."
366
+ ),
367
+ compliance_checked = True,
368
+ )
369
+
370
+
371
+ async def _handle_escalation(analysis: LLMAnalysisResult, ref_id: str) -> ActionResult:
372
+ """
373
+ Handle escalation to a human agent.
374
+
375
+ Triggered when the customer is frustrated, urgently needs help,
376
+ or when the intent cannot be determined.
377
+
378
+ Args:
379
+ analysis (LLMAnalysisResult): NLP result.
380
+ ref_id (str): Audit reference ID.
381
+
382
+ Returns:
383
+ ActionResult: Escalation result.
384
+ """
385
+ logger.info(
386
+ f"Escalating to human agent | sentiment={analysis.sentiment} | "
387
+ f"intent={analysis.intent} | ref={ref_id}"
388
+ )
389
+
390
+ # TODO: Trigger CRM ticket / live agent queue in production
391
+
392
+ return ActionResult(
393
+ action_taken = "Escalated to human agent queue",
394
+ status = ActionStatus.PENDING,
395
+ reference_id = ref_id,
396
+ message = (
397
+ f"Your request has been escalated to a senior agent (Ref: {ref_id}). "
398
+ "You will be connected shortly. We apologise for any inconvenience."
399
+ ),
400
+ compliance_checked = True,
401
+ )
app.py ADDED
@@ -0,0 +1,501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ app.py — Hugging Face Spaces (Streamlit SDK)
3
+ ---------------------------------------------
4
+ Streamlit SDK = single process. FastAPI runs as a background thread on :7861.
5
+ Streamlit serves the UI on :7860 (HF's public port).
6
+
7
+ HF Spaces proxies both ports:
8
+ :7860 → https://<space>.hf.space (Streamlit UI — public)
9
+ :7861 → https://<space>-7861.hf.space (FastAPI — called by JS)
10
+
11
+ Secrets (set in HF Space → Settings → Secrets):
12
+ SARVAM_API_KEY, GROQ_API_KEY
13
+ """
14
+
15
+ import os
16
+ import sys
17
+ import time
18
+ import threading
19
+
20
+ import streamlit as st
21
+ import streamlit.components.v1 as components
22
+ from streamlit_javascript import st_javascript
23
+
24
+ # ── Start FastAPI in a background daemon thread ───────────────────────────────
25
+ # Streamlit reruns this file on every interaction — use a flag to start only once
26
+ if "api_started" not in st.session_state:
27
+ st.session_state.api_started = True
28
+
29
+ def _run_api():
30
+ # Run setup_data first if data files are missing
31
+ if not os.path.exists("data/investors.json"):
32
+ import setup_data
33
+ setup_data.run()
34
+ import uvicorn
35
+ from main import app as fastapi_app
36
+ uvicorn.run(fastapi_app, host="0.0.0.0", port=7861,
37
+ log_level="warning", reload=False)
38
+
39
+ t = threading.Thread(target=_run_api, daemon=True)
40
+ t.start()
41
+ time.sleep(3) # Give FastAPI time to be ready before first render
42
+
43
+ # ── API_BASE: HF proxies port 7861 as a sibling subdomain ────────────────────
44
+ SPACE_ID = os.environ.get("SPACE_ID", "") # Auto-set by HF: "username/space-name"
45
+ if SPACE_ID:
46
+ slug = SPACE_ID.replace("/", "-").lower()
47
+ API_BASE = f"https://{slug}-7861.hf.space"
48
+ else:
49
+ API_BASE = "http://localhost:7861" # local dev fallback
50
+
51
+ # ── Streamlit page setup ──────────────────────────────────────────────────────
52
+ st.set_page_config(
53
+ page_title = "CAMS Voice & Chat Assistant",
54
+ page_icon = "🎙️",
55
+ layout = "wide",
56
+ initial_sidebar_state = "collapsed",
57
+ )
58
+
59
+ st.markdown("""
60
+ <style>
61
+ #MainMenu, header, footer,
62
+ [data-testid="stToolbar"],
63
+ [data-testid="stDecoration"],
64
+ [data-testid="stStatusWidget"] { visibility: hidden !important; height: 0 !important; }
65
+ .block-container { padding: 0 !important; margin: 0 !important; max-width: 100% !important; }
66
+ section.main > div { padding: 0 !important; }
67
+ section.main { overflow: hidden !important; }
68
+ iframe { display: block !important; border: none !important; }
69
+ [data-testid="stAppViewContainer"] { overflow: hidden !important; }
70
+ [data-testid="stVerticalBlock"] { gap: 0 !important; }
71
+ </style>
72
+ """, unsafe_allow_html=True)
73
+
74
+ win_height = st_javascript("window.innerHeight")
75
+ iframe_height = int(win_height) - 80 if win_height and int(win_height) > 100 else 720
76
+
77
+ # ── Full chat UI — same HTML/JS as local version ──────────────────────────────
78
+ components.html(f"""
79
+ <!DOCTYPE html>
80
+ <html lang="en">
81
+ <head>
82
+ <meta charset="UTF-8"/>
83
+ <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
84
+ <title>CAMS Assistant</title>
85
+ <style>
86
+ * {{ box-sizing: border-box; margin: 0; padding: 0; }}
87
+ :root {{
88
+ --bg: #0f1117;
89
+ --surface: #1a1d27;
90
+ --border: #2d3148;
91
+ --accent: #4f8ef7;
92
+ --accent2: #7c6af7;
93
+ --text: #e8eaf6;
94
+ --sub: #8892b0;
95
+ --user-bg: #1e2a4a;
96
+ --bot-bg: #1a1d27;
97
+ --green: #43d49e;
98
+ --red: #e05a5a;
99
+ --orange: #f7a94f;
100
+ }}
101
+ body {{ font-family: 'Segoe UI', system-ui, sans-serif; background: var(--bg); color: var(--text);
102
+ height: {iframe_height}px; display: flex; flex-direction: column; overflow: hidden; }}
103
+
104
+ /* ── Header ── */
105
+ .header {{ display:flex; align-items:center; gap:12px; padding:14px 20px;
106
+ background:var(--surface); border-bottom:1px solid var(--border);
107
+ flex-shrink:0; }}
108
+ .header-icon {{ font-size:26px; }}
109
+ .header-info h1 {{ font-size:16px; font-weight:700; color:var(--text); }}
110
+ .header-info p {{ font-size:12px; color:var(--sub); }}
111
+ .status-dot {{ width:8px; height:8px; border-radius:50%; background:var(--green);
112
+ box-shadow:0 0 8px var(--green); margin-left:auto; flex-shrink:0; }}
113
+ #lang-badge {{ margin-left:8px; padding:3px 10px; border-radius:20px;
114
+ background:#1e2a4a; font-size:11px; }}
115
+ #lang-badge span {{ color:var(--accent); font-weight:600; }}
116
+
117
+ /* ── Chat area ── */
118
+ #chat {{ flex:1; overflow-y:auto; padding:20px; display:flex;
119
+ flex-direction:column; gap:16px; scroll-behavior:smooth; }}
120
+ #chat::-webkit-scrollbar {{ width:4px; }}
121
+ #chat::-webkit-scrollbar-thumb {{ background:var(--border); border-radius:4px; }}
122
+
123
+ .msg {{ display:flex; gap:10px; align-items:flex-start; max-width:85%; }}
124
+ .msg.user {{ flex-direction:row-reverse; margin-left:auto; }}
125
+ .avatar {{ width:32px; height:32px; border-radius:50%; display:flex;
126
+ align-items:center; justify-content:center; font-size:16px;
127
+ flex-shrink:0; background:var(--border); }}
128
+ .msg.user .avatar {{ background:var(--user-bg); }}
129
+
130
+ .bubble {{ padding:12px 16px; border-radius:16px; font-size:14px;
131
+ line-height:1.6; max-width:100%; word-wrap:break-word; }}
132
+ .msg.user .bubble {{ background:var(--user-bg); border-top-right-radius:4px; color:var(--text); }}
133
+ .msg.bot .bubble {{ background:var(--bot-bg); border:1px solid var(--border);
134
+ border-top-left-radius:4px; color:var(--text); }}
135
+
136
+ /* ── Meta badges ── */
137
+ .meta {{ display:flex; flex-wrap:wrap; gap:6px; margin-top:8px; }}
138
+ .badge {{ display:inline-flex; align-items:center; gap:5px; padding:3px 10px;
139
+ border-radius:20px; font-size:11px; font-weight:500; }}
140
+ .badge.intent {{ background:#1e2a4a; color:var(--accent); }}
141
+ .badge.sentiment {{ background:#1e2a1e; color:var(--green); }}
142
+ .badge.confidence {{ background:#2a1e2a; color:#c084fc; }}
143
+ .badge.action-success {{ background:#1a2e1a; color:var(--green); }}
144
+ .badge.action-pending {{ background:#2a2a1a; color:var(--orange); }}
145
+ .badge.action-blocked {{ background:#2e1a1a; color:var(--red); }}
146
+ .badge.escalation {{ background:#3a1a1a; color:var(--red); }}
147
+ .badge.action-nr {{ background:var(--border); color:var(--sub); }}
148
+ .ref-id {{ font-size:10px; color:var(--sub); margin-top:4px; }}
149
+
150
+ /* ── Audio player ── */
151
+ audio {{ width:100%; margin-top:8px; height:32px; filter:invert(1) hue-rotate(180deg); }}
152
+
153
+ /* ── Typing indicator ── */
154
+ .typing {{ display:flex; gap:5px; padding:8px 0; align-items:center; }}
155
+ .typing span {{ width:8px; height:8px; border-radius:50%; background:var(--accent);
156
+ animation:blink 1.2s infinite; flex-shrink:0; }}
157
+ .typing span:nth-child(2) {{ animation-delay: .2s; }}
158
+ .typing span:nth-child(3) {{ animation-delay: .4s; }}
159
+ @keyframes blink {{ 0%,80%,100% {{ opacity:.2 }} 40% {{ opacity:1 }} }}
160
+
161
+ /* ── Input bar ── */
162
+ .input-bar {{ padding:12px 16px; background:var(--surface);
163
+ border-top:1px solid var(--border); flex-shrink:0; }}
164
+ .input-row {{ display:flex; gap:8px; align-items:center; }}
165
+ .input-wrap {{ flex:1; display:flex; align-items:center;
166
+ background:var(--bg); border:1px solid var(--border);
167
+ border-radius:12px; padding:0 12px; gap:8px;
168
+ transition:border-color .2s; }}
169
+ .input-wrap:focus-within {{ border-color:var(--accent); }}
170
+ textarea#text-input {{ flex:1; background:transparent; border:none; outline:none;
171
+ color:var(--text); font-size:14px; padding:10px 0;
172
+ resize:none; height:42px; line-height:1.5;
173
+ font-family:inherit; }}
174
+ textarea#text-input::placeholder {{ color:var(--sub); }}
175
+ .icon-btn {{ background:none; border:none; cursor:pointer; font-size:20px;
176
+ padding:6px; border-radius:8px; color:var(--sub);
177
+ transition:all .2s; flex-shrink:0; }}
178
+ .icon-btn:hover {{ background:var(--border); color:var(--text); }}
179
+ .icon-btn.recording {{ color:var(--red); animation:pulse 1s infinite; }}
180
+ @keyframes pulse {{ 0%,100% {{ transform:scale(1) }} 50% {{ transform:scale(1.1) }} }}
181
+ #send-btn {{ background:var(--accent); border:none; cursor:pointer;
182
+ font-size:18px; padding:10px 14px; border-radius:12px;
183
+ color:#fff; transition:all .2s; flex-shrink:0; }}
184
+ #send-btn:hover {{ background:var(--accent2); transform:scale(1.05); }}
185
+ #send-btn:disabled {{ opacity:.4; cursor:not-allowed; transform:none; }}
186
+ .file-row {{ display:flex; align-items:center; gap:8px; margin-top:8px;
187
+ font-size:12px; color:var(--sub); }}
188
+ #send-audio-btn {{ display:none; padding:4px 12px; background:var(--accent);
189
+ border:none; border-radius:8px; color:#fff;
190
+ cursor:pointer; font-size:12px; }}
191
+ #mic-status {{ display:none; font-size:11px; color:var(--red); }}
192
+ .hint {{ font-size:11px; color:var(--sub); text-align:center; margin-top:6px; }}
193
+ </style>
194
+ </head>
195
+ <body>
196
+
197
+ <div class="header">
198
+ <div class="header-icon">🏦</div>
199
+ <div class="header-info">
200
+ <h1>CAMS Assistant</h1>
201
+ <p>Mutual Fund Support — Portfolio · SIP · KYC · Compliance</p>
202
+ </div>
203
+ <div id="lang-badge">🌐 <span id="lang-text">EN</span></div>
204
+ <div class="status-dot"></div>
205
+ </div>
206
+
207
+ <div id="chat">
208
+ <div class="msg bot">
209
+ <div class="avatar">🤖</div>
210
+ <div class="bubble">
211
+ Namaste! I'm your CAMS Assistant. I can help you with your mutual fund portfolio,
212
+ SIP details, redemptions, KYC updates, and SEBI compliance queries.
213
+ <br><br>
214
+ To get started with account queries, please share your <strong>PAN number</strong>.
215
+ For general queries about SEBI rules, KYC documents, or fund information — just ask!
216
+ <div class="meta">
217
+ <span class="badge intent">🎯 Ready</span>
218
+ <span class="badge sentiment">🌐 EN / हिं / தமி</span>
219
+ </div>
220
+ </div>
221
+ </div>
222
+ </div>
223
+
224
+ <div class="input-bar">
225
+ <div class="input-row">
226
+ <div class="input-wrap">
227
+ <button class="icon-btn" id="mic-btn" title="Record voice">🎙️</button>
228
+ <label class="icon-btn" title="Upload audio file">
229
+ 📎 <input type="file" id="file-input" accept="audio/*" style="display:none"/>
230
+ </label>
231
+ <textarea id="text-input" rows="1"
232
+ placeholder="Type your query... e.g. What is my portfolio balance?"
233
+ autocomplete="off"
234
+ ></textarea>
235
+ <button id="send-btn" title="Send">➤</button>
236
+ </div>
237
+ </div>
238
+ <div class="file-row">
239
+ <span id="mic-status">● Recording...</span>
240
+ <span id="file-name"></span>
241
+ <button id="send-audio-btn">Send Audio ➤</button>
242
+ </div>
243
+ <div class="hint">Supports English · हिंदी · தமிழ் — voice or text</div>
244
+ </div>
245
+
246
+ <script>
247
+ const API_BASE = "{API_BASE}";
248
+ const sessionId = crypto.randomUUID();
249
+ const chat = document.getElementById("chat");
250
+ const textInput = document.getElementById("text-input");
251
+ const sendBtn = document.getElementById("send-btn");
252
+ const micBtn = document.getElementById("mic-btn");
253
+ const micStatus = document.getElementById("mic-status");
254
+ const fileInput = document.getElementById("file-input");
255
+ const fileName = document.getElementById("file-name");
256
+ const sendAudio = document.getElementById("send-audio-btn");
257
+
258
+ let mediaRecorder = null;
259
+ let audioChunks = [];
260
+ let isRecording = false;
261
+ let pendingAudioBlob = null;
262
+
263
+ let conversationHistory = [];
264
+ let sessionInvestorId = null;
265
+
266
+ function extractPAN(text) {{
267
+ const m = text && text.match(/\b[A-Z]{{5}}[0-9]{{4}}[A-Z]\b/i);
268
+ return m ? m[0].toUpperCase() : null;
269
+ }}
270
+
271
+ function updateSessionPAN(text) {{
272
+ const pan = extractPAN(text);
273
+ if (pan && pan !== sessionInvestorId) {{
274
+ sessionInvestorId = pan;
275
+ console.log("Session PAN updated:", pan);
276
+ }}
277
+ }}
278
+
279
+ function scrollBottom() {{ chat.scrollTop = chat.scrollHeight; }}
280
+
281
+ function escHtml(s) {{
282
+ return String(s||"")
283
+ .replace(/&/g,"&amp;").replace(/</g,"&lt;")
284
+ .replace(/>/g,"&gt;").replace(/"/g,"&quot;");
285
+ }}
286
+
287
+ function addUserMsg(text) {{
288
+ const d = document.createElement("div");
289
+ d.className = "msg user";
290
+ d.innerHTML = `<div class="avatar">👤</div><div class="bubble">${{escHtml(text)}}</div>`;
291
+ chat.appendChild(d); scrollBottom();
292
+ }}
293
+
294
+ function intentIcon(i) {{
295
+ const m = {{
296
+ portfolio_enquiry:"📊", account_statement:"📄", redemption_request:"💸",
297
+ transaction_status:"🔄", sip_enquiry:"📅", kyc_update:"🪪",
298
+ compliance_query:"⚖️", dividend_info:"💰", general_enquiry:"💬",
299
+ escalation:"🚨", unknown:"❓"
300
+ }};
301
+ return m[i] || "🎯";
302
+ }}
303
+ function intentLabel(i) {{
304
+ return (i||"unknown").replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());
305
+ }}
306
+ function sentimentIcon(s) {{
307
+ return {{positive:"😊",neutral:"😐",negative:"😟",frustrated:"😤",urgent:"⚡"}}[s]||"😐";
308
+ }}
309
+ function actionClass(s) {{
310
+ return {{success:"action-success",pending:"action-pending",
311
+ blocked_compliance:"action-blocked",failed:"action-blocked",
312
+ not_required:"action-nr"}}[s]||"action-nr";
313
+ }}
314
+ function actionIcon(s) {{
315
+ return {{success:"🟢",pending:"🟡",blocked_compliance:"🔴",failed:"🔴",not_required:"⚪"}}[s]||"⚪";
316
+ }}
317
+
318
+ function addBotResponse(data) {{
319
+ removeTyping();
320
+ const d = document.createElement("div");
321
+ d.className = "msg bot";
322
+
323
+ const langMap = {{"en":"EN","hi":"HI","ta":"TA","en-IN":"EN"}};
324
+ const lang = langMap[data.detected_language||"en"]||"EN";
325
+ document.getElementById("lang-text").textContent = lang;
326
+
327
+ let audioHtml = "";
328
+ if (data.audio_url) {{
329
+ const src = data.audio_url.startsWith("data:") ? data.audio_url
330
+ : `data:audio/wav;base64,${{data.audio_url}}`;
331
+ audioHtml = `<audio controls autoplay src="${{src}}"></audio>`;
332
+ }}
333
+
334
+ const conf = data.confidence ? Math.round(data.confidence * 100) : 0;
335
+ const act = data.action_result || {{}};
336
+ const ref = act.reference_id || "";
337
+ const actionBadge = act.status && act.status !== "not_required"
338
+ ? `<span class="badge ${{actionClass(act.status)}}">${{actionIcon(act.status)}} Action: ${{act.status}}</span>`
339
+ : `<span class="badge action-nr">⚪ No Action</span>`;
340
+ const escBadge = data.requires_escalation
341
+ ? `<span class="badge escalation">🚨 Escalation Required</span>` : "";
342
+ const refHtml = ref ? `<div class="ref-id">Ref: ${{ref.slice(0,12).toUpperCase()}}</div>` : "";
343
+
344
+ d.innerHTML = `
345
+ <div class="avatar">🤖</div>
346
+ <div class="bubble">
347
+ ${{escHtml(data.response_text)}}
348
+ ${{audioHtml}}
349
+ <div class="meta">
350
+ <span class="badge intent">${{intentIcon(data.intent)}} ${{intentLabel(data.intent)}}</span>
351
+ <span class="badge sentiment">${{sentimentIcon(data.sentiment)}} ${{(data.sentiment||"neutral").replace(/\b\w/g,c=>c.toUpperCase())}}</span>
352
+ <span class="badge confidence">${{conf}}% confident</span>
353
+ ${{actionBadge}}
354
+ ${{escBadge}}
355
+ </div>
356
+ ${{refHtml}}
357
+ </div>`;
358
+ chat.appendChild(d);
359
+ scrollBottom();
360
+ }}
361
+
362
+ function addTyping() {{
363
+ removeTyping();
364
+ const d = document.createElement("div");
365
+ d.className = "msg bot"; d.id = "typing-indicator";
366
+ d.innerHTML = `<div class="avatar">🤖</div><div class="bubble"><div class="typing"><span></span><span></span><span></span></div></div>`;
367
+ chat.appendChild(d); scrollBottom();
368
+ }}
369
+ function removeTyping() {{
370
+ const t = document.getElementById("typing-indicator");
371
+ if (t) t.remove();
372
+ }}
373
+ function addError(msg) {{
374
+ removeTyping();
375
+ const d = document.createElement("div");
376
+ d.className = "msg bot";
377
+ d.innerHTML = `<div class="avatar">🤖</div><div class="bubble" style="color:var(--red)">❌ ${{escHtml(msg)}}</div>`;
378
+ chat.appendChild(d); scrollBottom();
379
+ }}
380
+
381
+ // ── Send text ──────────────────────────────────────────────────────────────
382
+ async function sendText() {{
383
+ const msg = textInput.value.trim();
384
+ if (!msg) return;
385
+ addUserMsg(msg);
386
+ textInput.value = "";
387
+ sendBtn.disabled = true;
388
+ addTyping();
389
+
390
+ conversationHistory.push({{ role: "user", content: msg }});
391
+ updateSessionPAN(msg);
392
+
393
+ try {{
394
+ const r = await fetch(`${{API_BASE}}/api/chat`, {{
395
+ method: "POST",
396
+ headers: {{"Content-Type": "application/json"}},
397
+ body: JSON.stringify({{
398
+ message: msg,
399
+ language: "en-IN",
400
+ session_id: sessionId,
401
+ investor_id: sessionInvestorId || "",
402
+ conversation_history: conversationHistory.slice(-8),
403
+ }})
404
+ }});
405
+ const data = await r.json();
406
+ if (!r.ok) throw new Error(data.detail || "API error");
407
+ if (data.entities && data.entities.investor_id)
408
+ updateSessionPAN(data.entities.investor_id);
409
+ conversationHistory.push({{ role: "assistant", content: data.response_text || "" }});
410
+ addBotResponse(data);
411
+ }} catch(e) {{
412
+ addError(e.message);
413
+ conversationHistory.pop();
414
+ }} finally {{
415
+ sendBtn.disabled = false;
416
+ }}
417
+ }}
418
+
419
+ // ── Send audio blob ────────────────────────────────────────────────────────
420
+ async function sendAudioBlob(blob, filename) {{
421
+ addUserMsg(`🎙️ ${{filename}}`);
422
+ addTyping();
423
+ try {{
424
+ const form = new FormData();
425
+ form.append("audio_file", blob, filename);
426
+ form.append("session_id", sessionId);
427
+ form.append("investor_id", sessionInvestorId || "");
428
+ const r = await fetch(`${{API_BASE}}/api/voice`, {{ method: "POST", body: form }});
429
+ const data = await r.json();
430
+ if (!r.ok) throw new Error(data.detail || "API error");
431
+ if (data.transcribed_text) {{
432
+ updateSessionPAN(data.transcribed_text);
433
+ conversationHistory.push({{ role: "user", content: data.transcribed_text }});
434
+ conversationHistory.push({{ role: "assistant", content: data.response_text || "" }});
435
+ }}
436
+ if (data.entities && data.entities.investor_id)
437
+ updateSessionPAN(data.entities.investor_id);
438
+ addBotResponse(data);
439
+ }} catch(e) {{
440
+ addError(e.message);
441
+ }}
442
+ }}
443
+
444
+ // ── Mic recording ──────────────────────────────────────────────────────────
445
+ micBtn.addEventListener("click", async () => {{
446
+ if (isRecording) {{
447
+ isRecording = false;
448
+ micBtn.classList.remove("recording");
449
+ micStatus.style.display = "none";
450
+ mediaRecorder && mediaRecorder.stop();
451
+ return;
452
+ }}
453
+ try {{
454
+ const stream = await navigator.mediaDevices.getUserMedia({{ audio: true }});
455
+ mediaRecorder = new MediaRecorder(stream);
456
+ audioChunks = [];
457
+ isRecording = true;
458
+ micBtn.classList.add("recording");
459
+ micStatus.style.display = "inline";
460
+ mediaRecorder.ondataavailable = e => audioChunks.push(e.data);
461
+ mediaRecorder.onstop = () => {{
462
+ stream.getTracks().forEach(t => t.stop());
463
+ const blob = new Blob(audioChunks, {{ type: "audio/webm" }});
464
+ pendingAudioBlob = blob;
465
+ pendingAudioBlob.name = "mic_recording.webm";
466
+ fileName.textContent = "mic_recording.webm";
467
+ sendAudio.style.display = "inline-block";
468
+ }};
469
+ mediaRecorder.start();
470
+ }} catch(e) {{
471
+ addError("Microphone access denied: " + e.message);
472
+ }}
473
+ }});
474
+
475
+ sendAudio.addEventListener("click", async () => {{
476
+ sendAudio.style.display = "none";
477
+ fileName.textContent = "";
478
+ await sendAudioBlob(pendingAudioBlob, pendingAudioBlob.name);
479
+ }});
480
+
481
+ fileInput.addEventListener("change", () => {{
482
+ if (fileInput.files[0]) {{
483
+ pendingAudioBlob = fileInput.files[0];
484
+ fileName.textContent = fileInput.files[0].name;
485
+ sendAudio.style.display = "inline-block";
486
+ }}
487
+ }});
488
+
489
+ // ── Key + button bindings ──────────────────────────────────────────────────
490
+ sendBtn.addEventListener("click", sendText);
491
+ textInput.addEventListener("keydown", e => {{
492
+ if (e.key === "Enter" && !e.shiftKey) {{ e.preventDefault(); sendText(); }}
493
+ }});
494
+ textInput.addEventListener("input", () => {{
495
+ textInput.style.height = "42px";
496
+ textInput.style.height = Math.min(textInput.scrollHeight, 120) + "px";
497
+ }});
498
+ </script>
499
+ </body>
500
+ </html>
501
+ """, height=iframe_height, scrolling=False)
config.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ config.py
3
+ ---------
4
+ Centralised configuration management for the Voice & Chat Assistant.
5
+ Loads all settings from environment variables via pydantic-settings.
6
+ Provides a single `settings` instance imported across the entire app.
7
+
8
+ Services used:
9
+ - Sarvam AI : STT (Saaras:v3) + TTS (Bulbul:v3) — all 3 languages
10
+ - Groq : LLM inference (intent, sentiment, response)
11
+ """
12
+
13
+ import logging
14
+ from functools import lru_cache
15
+ from pydantic_settings import BaseSettings, SettingsConfigDict
16
+ from pydantic import Field, field_validator
17
+
18
+
19
+ # ── Module Logger ─────────────────────────────────────────────────────────────
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ # ── Settings Model ────────────────────────────────────────────────────────────
24
+ class Settings(BaseSettings):
25
+ """
26
+ Application-wide settings loaded from environment variables / .env file.
27
+
28
+ All fields map 1-to-1 with keys defined in .env.example.
29
+ Pydantic validates types and raises clear errors on misconfiguration.
30
+ """
31
+
32
+ model_config = SettingsConfigDict(
33
+ env_file = ".env",
34
+ env_file_encoding = "utf-8",
35
+ case_sensitive = False,
36
+ extra = "ignore", # Silently ignore unknown env vars
37
+ )
38
+
39
+ # ── Sarvam AI (STT + TTS) ─────────────────────────────────────────────────
40
+ sarvam_api_key: str = Field(..., description="Sarvam AI API key for STT and TTS")
41
+ sarvam_stt_model: str = Field(default="saaras:v3", description="Sarvam STT model")
42
+ sarvam_tts_model: str = Field(default="bulbul:v3", description="Sarvam TTS model")
43
+ sarvam_tts_speaker: str = Field(default="anushka", description="Sarvam TTS speaker voice")
44
+
45
+ # ── Groq (LLM) ────────────────────────────────────────────────────────────
46
+ groq_api_key: str = Field(..., description="Groq API key for LLM inference")
47
+ groq_model: str = Field(default="llama-3.3-70b-versatile", description="Groq model identifier")
48
+ groq_max_tokens: int = Field(default=1024, description="Max tokens for LLM response")
49
+ groq_temperature: float = Field(default=0.2, description="LLM temperature — lower = more deterministic")
50
+
51
+ # ── App ───────────────────────────────────────────────────────────────────
52
+ app_env: str = Field(default="development", description="Runtime environment")
53
+ log_level: str = Field(default="INFO", description="Logging level")
54
+ app_host: str = Field(default="0.0.0.0", description="FastAPI host")
55
+ app_port: int = Field(default=8000, description="FastAPI port")
56
+
57
+ # ── Validators ────────────────────────────────────────────────────────────
58
+ @field_validator("groq_temperature")
59
+ @classmethod
60
+ def validate_temperature(cls, value: float) -> float:
61
+ """Ensure temperature stays within valid LLM range [0.0, 1.0]."""
62
+ if not (0.0 <= value <= 1.0):
63
+ raise ValueError(
64
+ f"groq_temperature must be between 0.0 and 1.0, got {value}"
65
+ )
66
+ return value
67
+
68
+ @field_validator("log_level")
69
+ @classmethod
70
+ def validate_log_level(cls, value: str) -> str:
71
+ """Ensure log level is a valid Python logging level."""
72
+ valid_levels = {"DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"}
73
+ upper = value.upper()
74
+ if upper not in valid_levels:
75
+ raise ValueError(
76
+ f"log_level must be one of {valid_levels}, got '{value}'"
77
+ )
78
+ return upper
79
+
80
+ @field_validator("app_env")
81
+ @classmethod
82
+ def validate_app_env(cls, value: str) -> str:
83
+ """Ensure environment is either development or production."""
84
+ valid_envs = {"development", "production"}
85
+ lower = value.lower()
86
+ if lower not in valid_envs:
87
+ raise ValueError(
88
+ f"app_env must be one of {valid_envs}, got '{value}'"
89
+ )
90
+ return lower
91
+
92
+
93
+ # ── Singleton Factory ─────────────────────────────────────────────────────────
94
+ @lru_cache(maxsize=1)
95
+ def get_settings() -> Settings:
96
+ """
97
+ Return a cached singleton instance of Settings.
98
+
99
+ Using @lru_cache ensures the .env file is read only once at startup,
100
+ avoiding repeated I/O on every request.
101
+
102
+ Returns:
103
+ Settings: Validated application settings instance.
104
+
105
+ Raises:
106
+ ValidationError: If required env vars are missing or invalid.
107
+ FileNotFoundError: If .env file is missing in production.
108
+ """
109
+ try:
110
+ logger.info("Loading application settings from environment...")
111
+ config = Settings()
112
+ logger.info(
113
+ f"Settings loaded | env={config.app_env} | "
114
+ f"log_level={config.log_level} | "
115
+ f"groq_model={config.groq_model} | "
116
+ f"sarvam_stt={config.sarvam_stt_model} | "
117
+ f"sarvam_tts={config.sarvam_tts_model} | "
118
+ f"sarvam_speaker={config.sarvam_tts_speaker}"
119
+ )
120
+ return config
121
+ except Exception as e:
122
+ logger.critical(
123
+ f"Failed to load application settings. "
124
+ f"Please verify your .env file. Error: {str(e)}"
125
+ )
126
+ raise
127
+
128
+
129
+ # ── Module-level settings instance ───────────────────────────────────────────
130
+ # Import this directly across all modules: `from config import settings`
131
+ settings: Settings = get_settings()
data/knowledge_base_generator.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ data/knowledge_base_generator.py
3
+ ----------------------------------
4
+ Generates synthetic CAMS knowledge base documents for RAG Path B.
5
+ These are policy/FAQ documents — not investor account data.
6
+
7
+ Categories:
8
+ - kyc → KYC rules, documents required, update process
9
+ - compliance → SEBI regulations, AML, FATCA
10
+ - fund_info → How mutual funds work, NAV, exit load
11
+ - sip → SIP rules, pause, cancellation
12
+ - redemption → Redemption process, T+3, taxes
13
+ - general → CAMS services, contact, portal guide
14
+ """
15
+ import json
16
+ from pathlib import Path
17
+
18
+ KNOWLEDGE_BASE = [
19
+ # ── KYC ──────────────────────────────────────────────────────────────────
20
+ {
21
+ "title": "KYC Requirements for Mutual Fund Investment",
22
+ "category": "kyc",
23
+ "content": (
24
+ "KYC (Know Your Customer) is mandatory for all mutual fund investments in India. "
25
+ "Required documents: PAN card (mandatory), Aadhaar card or passport for address proof, "
26
+ "passport-size photograph, and bank account details. "
27
+ "KYC can be completed online via Video KYC (VKYC) or offline at any CAMS service centre. "
28
+ "Once KYC is verified, it is valid across all mutual fund investments — no re-KYC needed. "
29
+ "NRIs require additional documents: passport copy, overseas address proof, and FEMA declaration."
30
+ )
31
+ },
32
+ {
33
+ "title": "KYC Update Process",
34
+ "category": "kyc",
35
+ "content": (
36
+ "To update KYC details (address, mobile, email, bank account, nominee): "
37
+ "1. Visit camsonline.com and log in with your folio number or PAN. "
38
+ "2. Go to 'KYC Update' section and submit the change request. "
39
+ "3. Upload supporting documents (address proof for address change, cancelled cheque for bank change). "
40
+ "4. Changes are processed within 2-3 working days. "
41
+ "Alternatively, visit the nearest CAMS service centre with original documents. "
42
+ "Mobile number update requires OTP verification on the new number. "
43
+ "Bank account change requires a cancelled cheque of the new account."
44
+ )
45
+ },
46
+ # ── Compliance ────────────────────────────────────────────────────────────
47
+ {
48
+ "title": "SEBI Regulations for Mutual Funds",
49
+ "category": "compliance",
50
+ "content": (
51
+ "SEBI (Securities and Exchange Board of India) regulates all mutual funds in India. "
52
+ "Key SEBI regulations: "
53
+ "- Mutual funds must publish NAV daily for all open-ended schemes. "
54
+ "- Total Expense Ratio (TER) is capped by SEBI based on AUM. "
55
+ "- Fund houses must disclose portfolio holdings monthly. "
56
+ "- SEBI mandates a 3-day (T+3) settlement for redemptions. "
57
+ "- Investors can file complaints on SEBI SCORES portal at scores.sebi.gov.in. "
58
+ "- Mutual fund advertisements must carry the statutory warning about market risks."
59
+ )
60
+ },
61
+ {
62
+ "title": "AML and FATCA Compliance",
63
+ "category": "compliance",
64
+ "content": (
65
+ "Anti-Money Laundering (AML): All transactions above ₹50,000 require PAN. "
66
+ "Suspicious transactions are reported to the Financial Intelligence Unit (FIU-IND). "
67
+ "CAMS performs enhanced due diligence for high-value transactions. "
68
+ "FATCA (Foreign Account Tax Compliance Act): US persons and entities must declare "
69
+ "their US tax status when investing in Indian mutual funds. "
70
+ "FATCA self-certification is mandatory for new folios. "
71
+ "Existing investors must submit FATCA declaration if not already done. "
72
+ "Non-compliance may result in account restriction or mandatory redemption."
73
+ )
74
+ },
75
+ # ── Fund Info ─────────────────────────────────────────────────────────────
76
+ {
77
+ "title": "Understanding NAV and Exit Load",
78
+ "category": "fund_info",
79
+ "content": (
80
+ "NAV (Net Asset Value) is the per-unit price of a mutual fund scheme, calculated daily. "
81
+ "NAV = (Total Assets - Total Liabilities) / Total Units Outstanding. "
82
+ "For equity funds, NAV is declared at end of each business day. "
83
+ "For liquid funds, NAV is declared for all calendar days including weekends. "
84
+ "Exit Load: A charge deducted when you redeem units before the specified holding period. "
85
+ "Most equity funds charge 1% exit load if redeemed within 1 year. "
86
+ "ELSS funds have a mandatory 3-year lock-in — no exit load applies after lock-in. "
87
+ "Liquid and overnight funds typically have no exit load or a very minimal one (0.0070%)."
88
+ )
89
+ },
90
+ {
91
+ "title": "Types of Mutual Fund Categories",
92
+ "category": "fund_info",
93
+ "content": (
94
+ "SEBI has categorised mutual funds as: "
95
+ "Equity Funds: Large Cap (top 100 companies), Mid Cap (101-250), Small Cap (251+), "
96
+ "Flexi Cap (any market cap), ELSS (tax-saving with 3-year lock-in). "
97
+ "Debt Funds: Liquid (up to 91 days), Short Duration, Corporate Bond, Gilt. "
98
+ "Hybrid Funds: Balanced Advantage, Aggressive Hybrid, Conservative Hybrid. "
99
+ "Index Funds and ETFs: Track a specific index like Nifty 50 or Sensex. "
100
+ "Equity funds are suitable for long-term goals (5+ years). "
101
+ "Debt funds are suitable for short-term goals (1-3 years). "
102
+ "ELSS offers tax deduction under Section 80C up to ₹1.5 lakh per year."
103
+ )
104
+ },
105
+ # ── SIP ───────────────────────────────────────────────────────────────────
106
+ {
107
+ "title": "SIP — How It Works, Pause and Cancellation",
108
+ "category": "sip",
109
+ "content": (
110
+ "SIP (Systematic Investment Plan) allows investing a fixed amount at regular intervals. "
111
+ "SIP can be weekly, monthly, or quarterly. Minimum SIP amount is ₹100-500 depending on fund. "
112
+ "SIP pause: You can pause your SIP for 1-3 months without cancelling. "
113
+ "Log in to camsonline.com → SIP → Pause/Modify. "
114
+ "SIP cancellation: Must be submitted at least 7 working days before the next SIP date. "
115
+ "Missed SIP: If bank account has insufficient funds, the SIP installment is skipped. "
116
+ "3 consecutive missed SIPs may result in automatic SIP cancellation by the fund house. "
117
+ "SIP Step-Up: Automatically increase SIP amount annually (e.g., by 10% each year)."
118
+ )
119
+ },
120
+ # ── Redemption ────────────────────────────────────────────────────────────
121
+ {
122
+ "title": "Redemption Process and Timeline",
123
+ "category": "redemption",
124
+ "content": (
125
+ "Redemption is the process of selling mutual fund units to receive cash. "
126
+ "For equity and hybrid funds: Redemption proceeds are credited within T+3 working days. "
127
+ "For debt funds: T+2 working days. For liquid funds: T+1 working day. "
128
+ "Redemption can be full (all units) or partial (specific amount or units). "
129
+ "Tax on redemption: Short-term capital gains (STCG) for equity held < 1 year = 20%. "
130
+ "Long-term capital gains (LTCG) for equity held > 1 year = 12.5% above ₹1.25 lakh. "
131
+ "ELSS funds cannot be redeemed before 3 years (lock-in period). "
132
+ "Redemption requests submitted after 3 PM are processed at next day's NAV."
133
+ )
134
+ },
135
+ # ── General ───────────────────────────────────────────────────────────────
136
+ {
137
+ "title": "CAMS Services and Contact Information",
138
+ "category": "general",
139
+ "content": (
140
+ "CAMS (Computer Age Management Services) is India's largest mutual fund registrar and transfer agent. "
141
+ "CAMS services: Account statement, SIP management, redemption, KYC update, nomination change. "
142
+ "Online portal: camsonline.com — available 24/7 for all self-service needs. "
143
+ "Mobile app: myCAMS — available on Android and iOS. "
144
+ "Customer care: 1800-3010-6767 (toll-free), available Monday-Friday 8 AM to 8 PM. "
145
+ "Email: enq@camsonline.com. "
146
+ "CAMS service centres available in 270+ cities across India. "
147
+ "For complaints: Register on SEBI SCORES or approach CAMS grievance officer."
148
+ )
149
+ },
150
+ {
151
+ "title": "Account Statement and Portfolio Report",
152
+ "category": "general",
153
+ "content": (
154
+ "CAMS provides consolidated account statements (CAS) covering all mutual fund holdings. "
155
+ "CAS is sent automatically to registered email every month if there are transactions. "
156
+ "To get a statement on demand: Visit camsonline.com → Account Statement → Enter PAN and email. "
157
+ "Statement is sent to the registered email address within minutes. "
158
+ "Capital Gains Statement: Available for tax filing purposes, shows gains/losses for a financial year. "
159
+ "To download: camsonline.com → Capital Gains Statement → Select financial year. "
160
+ "Consolidated statement includes all fund houses �� HDFC, SBI, Axis, Mirae, etc."
161
+ )
162
+ },
163
+ {
164
+ "title": "Dividend and IDCW Information",
165
+ "category": "general",
166
+ "content": (
167
+ "IDCW (Income Distribution cum Capital Withdrawal) was formerly called Dividend option. "
168
+ "SEBI renamed 'Dividend' to 'IDCW' in 2021 to better reflect its nature. "
169
+ "IDCW is not guaranteed — it depends on the fund's distributable surplus. "
170
+ "When IDCW is declared, the NAV of the fund falls by the distribution amount. "
171
+ "IDCW is taxable in the hands of the investor as per their income tax slab. "
172
+ "TDS of 10% is deducted on IDCW exceeding ₹5,000 per year. "
173
+ "Growth option is preferred for long-term wealth creation as returns are compounded. "
174
+ "IDCW payout dates vary by fund — check the fund's scheme information document (SID)."
175
+ )
176
+ },
177
+ ]
178
+
179
+ if __name__ == "__main__":
180
+ out = Path(__file__).parent / "knowledge_base.json"
181
+ with open(out, "w") as f:
182
+ json.dump(KNOWLEDGE_BASE, f, indent=2)
183
+ print(f"✅ Generated {len(KNOWLEDGE_BASE)} KB documents → {out}")
184
+ for doc in KNOWLEDGE_BASE:
185
+ print(f" [{doc['category']}] {doc['title']}")
data/synthetic_investors.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ data/synthetic_investors.py
3
+ ----------------------------
4
+ Generates synthetic CAMS investor data as RAG-ready documents.
5
+ Each record becomes a searchable document in ChromaDB.
6
+
7
+ Run once: python setup_data.py
8
+ """
9
+ from __future__ import annotations
10
+ import json
11
+ import random
12
+ from datetime import datetime, timedelta
13
+ from pathlib import Path
14
+
15
+ random.seed(42)
16
+
17
+ FUNDS = [
18
+ {"name": "HDFC Top 100 Fund", "category": "Large Cap", "nav": 872.45},
19
+ {"name": "SBI Bluechip Fund", "category": "Large Cap", "nav": 65.32},
20
+ {"name": "Axis Midcap Fund", "category": "Mid Cap", "nav": 94.18},
21
+ {"name": "Mirae Asset Emerging Bluechip", "category": "Large & Mid", "nav": 112.60},
22
+ {"name": "Parag Parikh Flexi Cap Fund", "category": "Flexi Cap", "nav": 68.75},
23
+ {"name": "ICICI Pru Balanced Advantage", "category": "Hybrid", "nav": 55.40},
24
+ {"name": "Kotak Small Cap Fund", "category": "Small Cap", "nav": 215.30},
25
+ {"name": "Nippon India Small Cap", "category": "Small Cap", "nav": 148.90},
26
+ {"name": "DSP Tax Saver Fund", "category": "ELSS", "nav": 88.15},
27
+ {"name": "Aditya Birla Sun Life Liquid", "category": "Liquid", "nav": 382.10},
28
+ ]
29
+ FIRST_NAMES = ["Arjun","Priya","Rahul","Deepa","Vikram","Sunita","Karthik",
30
+ "Meena","Arun","Lakshmi","Suresh","Kavitha","Rajesh","Anitha",
31
+ "Murugan","Saranya","Dinesh","Padma","Venkat","Geetha"]
32
+ LAST_NAMES = ["Kumar","Sharma","Patel","Reddy","Nair","Iyer","Pillai",
33
+ "Singh","Gupta","Verma","Rao","Menon","Krishnan","Subramanian"]
34
+ CITIES = ["Chennai","Mumbai","Delhi","Bengaluru","Hyderabad","Pune",
35
+ "Kolkata","Ahmedabad","Coimbatore","Kochi"]
36
+
37
+ def _pan() -> str:
38
+ L = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
39
+ return "".join(random.choices(L,k=5)) + "".join(random.choices("0123456789",k=4)) + random.choice(L)
40
+
41
+ def _date(years_back=5) -> str:
42
+ start = datetime.now() - timedelta(days=years_back*365)
43
+ return (start + timedelta(days=random.randint(0, years_back*365))).strftime("%d-%m-%Y")
44
+
45
+ def _holdings(n=3) -> list:
46
+ holdings = []
47
+ for fund in random.sample(FUNDS, n):
48
+ units = round(random.uniform(50, 5000), 3)
49
+ value = round(units * fund["nav"], 2)
50
+ invested = round(value * random.uniform(0.6, 1.2), 2)
51
+ has_sip = random.choice([True, True, False])
52
+ holdings.append({
53
+ "fund_name": fund["name"],
54
+ "category": fund["category"],
55
+ "folio_number": f"{random.randint(10000000,99999999)}/{random.randint(10,99)}",
56
+ "units": units,
57
+ "nav": fund["nav"],
58
+ "current_value": value,
59
+ "invested_amount": invested,
60
+ "gain_loss": round(value - invested, 2),
61
+ "gain_loss_pct": round((value-invested)/invested*100, 2),
62
+ "sip_active": has_sip,
63
+ "sip_amount": random.choice([1000,2000,3000,5000,10000]) if has_sip else None,
64
+ "sip_date": random.randint(1,28) if has_sip else None,
65
+ "dividend_option": random.choice(["Growth","IDCW"]),
66
+ "investment_date": _date(5),
67
+ "last_nav_date": datetime.now().strftime("%d-%m-%Y"),
68
+ })
69
+ return holdings
70
+
71
+ def _transactions(holdings, n=3) -> list:
72
+ txns = []
73
+ for _ in range(n):
74
+ h = random.choice(holdings)
75
+ txns.append({
76
+ "txn_id": f"TXN{random.randint(1000000,9999999)}",
77
+ "fund_name": h["fund_name"],
78
+ "type": random.choice(["SIP","Redemption","Lump Sum Purchase","Dividend Reinvestment"]),
79
+ "amount": random.choice([1000,2000,5000,10000,25000,50000]),
80
+ "units": round(random.uniform(5,500), 3),
81
+ "nav": h["nav"],
82
+ "date": _date(1),
83
+ "status": random.choice(["Processed","Processed","Processed","Pending"]),
84
+ })
85
+ return txns
86
+
87
+ def generate_investors(count=20) -> list:
88
+ investors, used_pans = [], set()
89
+ for i in range(count):
90
+ first, last = random.choice(FIRST_NAMES), random.choice(LAST_NAMES)
91
+ pan = _pan()
92
+ while pan in used_pans: pan = _pan()
93
+ used_pans.add(pan)
94
+
95
+ holdings = _holdings(random.randint(2,4))
96
+ total_invested = sum(h["invested_amount"] for h in holdings)
97
+ total_value = sum(h["current_value"] for h in holdings)
98
+ total_gain = round(total_value - total_invested, 2)
99
+
100
+ investors.append({
101
+ "investor_id": f"CAMS{str(i+1).zfill(5)}",
102
+ "name": f"{first} {last}",
103
+ "pan": pan,
104
+ "email": f"{first.lower()}.{last.lower()}{random.randint(1,99)}@gmail.com",
105
+ "mobile": f"9{random.randint(100000000,999999999)}",
106
+ "city": random.choice(CITIES),
107
+ "dob": _date(40),
108
+ "kyc_status": random.choice(["Verified","Verified","Verified","Pending"]),
109
+ "account_since": _date(7),
110
+ "nominee_name": f"{random.choice(FIRST_NAMES)} {last}",
111
+ "nominee_relation": random.choice(["Spouse","Son","Daughter","Father","Mother"]),
112
+ "total_invested": round(total_invested, 2),
113
+ "total_current_value": round(total_value, 2),
114
+ "total_gain_loss": total_gain,
115
+ "total_gain_loss_pct": round(total_gain/total_invested*100, 2) if total_invested else 0,
116
+ "total_sip_amount": sum(h["sip_amount"] for h in holdings if h["sip_active"]),
117
+ "num_funds": len(holdings),
118
+ "holdings": holdings,
119
+ "recent_transactions": _transactions(holdings),
120
+ })
121
+ return investors
122
+
123
+ if __name__ == "__main__":
124
+ investors = generate_investors(20)
125
+ out = Path(__file__).parent / "investors.json"
126
+ with open(out,"w") as f: json.dump(investors, f, indent=2)
127
+ print(f"Generated {len(investors)} investors → {out}")
128
+ s = investors[0]
129
+ print(f"Sample: {s['name']} | PAN: {s['pan']} | Value: ₹{s['total_current_value']:,.2f}")
main.py ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ main.py — CAMS Voice & Chat Assistant v3.1
3
+ -------------------------------------------
4
+ Latency-optimized pipeline. Single LLM call per request.
5
+
6
+ CHAT timeline:
7
+ Retrieval (PATH A exact): ~0ms
8
+ LLM (single call): ~0.4s
9
+ TTS + Action (parallel): ~1.0s
10
+ Total: ~1.5s ✅
11
+
12
+ VOICE timeline:
13
+ STT: ~1.5s
14
+ Retrieval (PATH A): ~0ms
15
+ LLM (single call): ~0.4s
16
+ TTS + Action (parallel): ~1.0s
17
+ Total: ~3.0s ✅
18
+
19
+ Key fixes vs previous version:
20
+ - Removed double LLM call (was calling analyse_message twice for PATH B)
21
+ - KB context retrieved and injected BEFORE single LLM call
22
+ - TF-IDF removed — simple keyword search for KB is fast enough
23
+ - Persistent HTTP client reused for all Sarvam calls
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import asyncio
28
+ import time
29
+ import uuid
30
+ import logging
31
+ from typing import Optional
32
+ from contextlib import asynccontextmanager
33
+
34
+ import httpx
35
+ import uvicorn
36
+ from fastapi import FastAPI, UploadFile, File, Form, HTTPException
37
+ from fastapi.middleware.cors import CORSMiddleware
38
+
39
+ from config import settings
40
+ from schemas import ChatRequest, AssistantResponse
41
+ from services.groq_llm import analyse_message
42
+ from services.data_retriever import get_investor_context
43
+ from services.vector_store import get_vector_store
44
+ from action_engine import trigger_action
45
+
46
+ logging.basicConfig(
47
+ level = getattr(logging, settings.log_level, logging.INFO),
48
+ format = "%(asctime)s | %(levelname)-8s | %(name)s | %(message)s",
49
+ datefmt = "%Y-%m-%d %H:%M:%S",
50
+ )
51
+ logger = logging.getLogger(__name__)
52
+
53
+ # ── Persistent HTTP client ────────────────────────────────────────────────────
54
+ _http_client: Optional[httpx.AsyncClient] = None
55
+
56
+ def get_http_client() -> httpx.AsyncClient:
57
+ global _http_client
58
+ if _http_client is None or _http_client.is_closed:
59
+ _http_client = httpx.AsyncClient(
60
+ timeout = httpx.Timeout(connect=5.0, read=30.0, write=10.0, pool=5.0),
61
+ limits = httpx.Limits(max_connections=20, max_keepalive_connections=10),
62
+ )
63
+ return _http_client
64
+
65
+ @asynccontextmanager
66
+ async def lifespan(app: FastAPI):
67
+ # Auto-generate data files if missing (needed on HF Spaces fresh container)
68
+ import importlib.util, os
69
+ if not os.path.exists("data/investors.json") or not os.path.exists("data/knowledge_base.json"):
70
+ logger.info("Data files missing — running setup_data...")
71
+ import setup_data
72
+ setup_data.run()
73
+ get_http_client()
74
+ get_vector_store()
75
+ logger.info("Startup complete — HTTP client and vector store ready.")
76
+ yield
77
+ if _http_client and not _http_client.is_closed:
78
+ await _http_client.aclose()
79
+
80
+ app = FastAPI(title="CAMS Assistant", version="3.1.0", lifespan=lifespan)
81
+ app.add_middleware(
82
+ CORSMiddleware,
83
+ allow_origins=["*"], allow_credentials=True,
84
+ allow_methods=["*"], allow_headers=["*"],
85
+ )
86
+
87
+
88
+ @app.get("/health")
89
+ async def health():
90
+ return {"status": "ok"}
91
+
92
+
93
+ # ── STT ───────────────────────────────────────────────────────────────────────
94
+ async def _stt(audio_bytes: bytes, mime_type: str) -> dict:
95
+ from services.sarvam_stt import SARVAM_STT_URL, SARVAM_LANG_MAP
96
+ filename = "audio.wav" if "wav" in mime_type else "audio.webm"
97
+ r = await get_http_client().post(
98
+ SARVAM_STT_URL,
99
+ files = {"file": (filename, audio_bytes, mime_type)},
100
+ data = {"model": settings.sarvam_stt_model, "language_code": "unknown"},
101
+ headers = {"api-subscription-key": settings.sarvam_api_key},
102
+ )
103
+ if r.status_code != 200:
104
+ raise RuntimeError(f"STT error {r.status_code}: {r.text[:200]}")
105
+ data = r.json()
106
+ transcript = (data.get("transcript") or "").strip()
107
+ if not transcript:
108
+ raise RuntimeError("No speech detected — please speak clearly.")
109
+ lang = SARVAM_LANG_MAP.get((data.get("language_code") or "en").lower(), "en")
110
+ return {"transcript": transcript, "detected_language": lang}
111
+
112
+
113
+ # ── TTS ───────────────────────────────────────────────────────────────────────
114
+ async def _tts(text: str, language: str) -> dict:
115
+ from services.sarvam_tts import SARVAM_TTS_URL, LANGUAGE_MAP
116
+ r = await get_http_client().post(
117
+ SARVAM_TTS_URL,
118
+ json = {
119
+ "inputs": [text[:400]], # Cap at 400 chars — faster TTS
120
+ "target_language_code": LANGUAGE_MAP.get(language, "en-IN"),
121
+ "speaker": settings.sarvam_tts_speaker,
122
+ "model": settings.sarvam_tts_model,
123
+ "speech_sample_rate": 8000, # 8kHz — 3x smaller payload
124
+ "pace": 1.1,
125
+ },
126
+ headers = {"api-subscription-key": settings.sarvam_api_key,
127
+ "Content-Type": "application/json"},
128
+ )
129
+ if r.status_code != 200:
130
+ logger.warning(f"TTS error {r.status_code}")
131
+ return {"audio": None}
132
+ audios = r.json().get("audios") or []
133
+ return {"audio": audios[0] if audios else None}
134
+
135
+
136
+ # ── Context retrieval (single path — no double LLM call) ─────────────────────
137
+ async def _get_context(
138
+ message: str,
139
+ investor_id: Optional[str] = None,
140
+ conversation_history: Optional[list] = None,
141
+ ) -> tuple[Optional[dict], str]:
142
+ """
143
+ Resolve which investor to fetch data for, in priority order:
144
+ 1. PAN explicitly in the CURRENT message ← always wins (user switching accounts)
145
+ 2. investor_id passed from frontend session (already verified earlier)
146
+ 3. PAN found in conversation history (user gave it a few turns ago)
147
+ 4. Knowledge base search (policy/FAQ queries)
148
+
149
+ Priority 1 > 2 ensures that when a user types a NEW PAN,
150
+ we switch to that investor immediately instead of using the old session PAN.
151
+ """
152
+ import re
153
+ PAN_RE = re.compile(r"\b[A-Z]{5}[0-9]{4}[A-Z]\b", re.IGNORECASE)
154
+ vs = get_vector_store()
155
+
156
+ # ── 1. PAN in CURRENT message (highest priority) ──────────────────────
157
+ current_pan = None
158
+ m = PAN_RE.search(message.upper())
159
+ if m:
160
+ current_pan = m.group(0)
161
+ logger.info(f"PAN in current message: {current_pan}")
162
+
163
+ # ── 2. Session investor_id (only if no new PAN in current message) ────
164
+ resolved_id = current_pan or investor_id or None
165
+
166
+ # ── 3. Scan history (only if still nothing resolved) ─────────────────
167
+ if not resolved_id and conversation_history:
168
+ for turn in reversed(conversation_history):
169
+ text = turn.get("content", "") or ""
170
+ m2 = PAN_RE.search(text.upper())
171
+ if m2:
172
+ resolved_id = m2.group(0)
173
+ logger.info(f"PAN from history: {resolved_id}")
174
+ break
175
+
176
+ # ── PATH A: exact investor lookup ─────────────────────────────────────
177
+ if resolved_id:
178
+ investor, account_ctx = await get_investor_context(
179
+ user_message = message,
180
+ extracted_entities = {"investor_id": resolved_id},
181
+ )
182
+ if account_ctx:
183
+ return investor, account_ctx
184
+
185
+ # ── PATH B: knowledge base ────────────────────────────────────────────
186
+ kb_ctx = await vs.search_knowledge(message, top_k=2)
187
+ if kb_ctx:
188
+ return None, kb_ctx
189
+
190
+ return None, ""
191
+
192
+
193
+ # ── CHAT endpoint ─────────────────────────────────────────────────────────────
194
+ @app.post("/api/chat", response_model=AssistantResponse)
195
+ async def process_chat(request: ChatRequest) -> AssistantResponse:
196
+ session_id = request.session_id or str(uuid.uuid4())
197
+ t0 = time.perf_counter()
198
+
199
+ try:
200
+ # ── Retrieval + LLM + TTS timeline:
201
+ # [retrieval ~0ms] → [LLM ~0.4s] → [TTS ∥ Action ~1.0s] = ~1.5s total
202
+
203
+ t1 = time.perf_counter()
204
+ investor, context = await _get_context(
205
+ message = request.message,
206
+ investor_id = request.investor_id,
207
+ conversation_history = request.conversation_history or [],
208
+ )
209
+ logger.info(f"[CHAT] retrieval={time.perf_counter()-t1:.3f}s ctx={'account' if investor else ('kb' if context else 'none')}")
210
+
211
+ t2 = time.perf_counter()
212
+ analysis = await analyse_message(
213
+ user_message = request.message,
214
+ language = request.language or "en",
215
+ investor_id = request.investor_id or None,
216
+ conversation_history = request.conversation_history or [],
217
+ investor_context = context or None,
218
+ )
219
+ logger.info(f"[CHAT] llm={time.perf_counter()-t2:.2f}s intent={analysis.intent}")
220
+
221
+ t3 = time.perf_counter()
222
+ action_result, tts_result = await asyncio.gather(
223
+ trigger_action(analysis),
224
+ _tts(analysis.response_text, request.language or "en"),
225
+ )
226
+ logger.info(f"[CHAT] tts+action={time.perf_counter()-t3:.2f}s | TOTAL={time.perf_counter()-t0:.2f}s")
227
+
228
+ return AssistantResponse(
229
+ session_id = session_id,
230
+ transcribed_text = None,
231
+ detected_language = request.language or "en",
232
+ intent = analysis.intent,
233
+ sentiment = analysis.sentiment,
234
+ entities = analysis.entities,
235
+ response_text = analysis.response_text,
236
+ confidence = analysis.confidence,
237
+ requires_escalation = analysis.requires_escalation,
238
+ action_result = action_result,
239
+ audio_url = tts_result.get("audio"),
240
+ )
241
+
242
+ except HTTPException:
243
+ raise
244
+ except Exception as e:
245
+ logger.error(f"[CHAT] {e}", exc_info=True)
246
+ raise HTTPException(status_code=500, detail=str(e))
247
+
248
+
249
+ # ── VOICE endpoint ────────────────────────────────────────────────────────────
250
+ @app.post("/api/voice", response_model=AssistantResponse)
251
+ async def process_voice(
252
+ audio_file: UploadFile = File(...),
253
+ session_id: str = Form(default=""),
254
+ investor_id: str = Form(default=""),
255
+ ) -> AssistantResponse:
256
+ if not session_id:
257
+ session_id = str(uuid.uuid4())
258
+ t0 = time.perf_counter()
259
+
260
+ supported = {
261
+ "audio/wav","audio/wave","audio/x-wav","audio/mpeg",
262
+ "audio/mp3","audio/webm","audio/ogg","application/octet-stream",
263
+ }
264
+ if audio_file.content_type not in supported:
265
+ raise HTTPException(400, f"Unsupported: {audio_file.content_type}")
266
+
267
+ try:
268
+ audio_bytes = await audio_file.read()
269
+ if not audio_bytes:
270
+ raise HTTPException(400, "Empty audio file.")
271
+
272
+ # STT (unavoidable ~1.5s)
273
+ t1 = time.perf_counter()
274
+ stt = await _stt(audio_bytes, audio_file.content_type or "audio/wav")
275
+ transcript, lang = stt["transcript"], stt["detected_language"]
276
+ logger.info(f"[VOICE] stt={time.perf_counter()-t1:.2f}s lang={lang} '{transcript[:50]}'")
277
+
278
+ # Retrieval (instant for PATH A, ~5ms for PATH B)
279
+ t2 = time.perf_counter()
280
+ investor, context = await _get_context(
281
+ message = transcript,
282
+ investor_id = investor_id or None,
283
+ conversation_history = [], # Voice history tracked via sessionInvestorId on frontend
284
+ )
285
+ logger.info(f"[VOICE] retrieval={time.perf_counter()-t2:.3f}s ctx={'account' if investor else ('kb' if context else 'none')}")
286
+
287
+ # Single LLM call with full context
288
+ t3 = time.perf_counter()
289
+ analysis = await analyse_message(
290
+ user_message = transcript,
291
+ language = lang,
292
+ investor_id = investor_id or None,
293
+ conversation_history = [],
294
+ investor_context = context or None,
295
+ )
296
+ logger.info(f"[VOICE] llm={time.perf_counter()-t3:.2f}s intent={analysis.intent}")
297
+
298
+ # TTS + Action in parallel
299
+ t4 = time.perf_counter()
300
+ action_result, tts_result = await asyncio.gather(
301
+ trigger_action(analysis),
302
+ _tts(analysis.response_text, lang),
303
+ )
304
+ logger.info(f"[VOICE] tts+action={time.perf_counter()-t4:.2f}s | TOTAL={time.perf_counter()-t0:.2f}s ✅")
305
+
306
+ return AssistantResponse(
307
+ session_id = session_id,
308
+ transcribed_text = transcript,
309
+ detected_language = lang,
310
+ intent = analysis.intent,
311
+ sentiment = analysis.sentiment,
312
+ entities = analysis.entities,
313
+ response_text = analysis.response_text,
314
+ confidence = analysis.confidence,
315
+ requires_escalation = analysis.requires_escalation,
316
+ action_result = action_result,
317
+ audio_url = tts_result.get("audio"),
318
+ )
319
+
320
+ except HTTPException:
321
+ raise
322
+ except Exception as e:
323
+ logger.error(f"[VOICE] {e}", exc_info=True)
324
+ raise HTTPException(status_code=500, detail=str(e))
325
+
326
+
327
+ if __name__ == "__main__":
328
+ import os
329
+ port = int(os.environ.get("PORT", settings.app_port))
330
+ uvicorn.run(
331
+ "main:app",
332
+ host = settings.app_host,
333
+ port = port,
334
+ reload = False,
335
+ log_level = "warning",
336
+ workers = 1,
337
+ )
requirements.txt CHANGED
@@ -1,3 +1,35 @@
1
- altair
2
- pandas
3
- streamlit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ── Web Framework ─────────────────────────────────────────────────────────────
2
+ fastapi==0.115.0
3
+ uvicorn[standard]==0.30.6
4
+
5
+ # ── Async HTTP ────────────────────────────────────────────────────────────────
6
+ httpx==0.27.2
7
+ aiofiles==24.1.0
8
+
9
+ # ── AI Services ───────────────────────────────────────────────────────────────
10
+ sarvamai
11
+ groq==0.11.0
12
+
13
+ # ── Data Validation & Config ──────────────────────────────────────────────────
14
+ pydantic==2.9.2
15
+ pydantic-settings==2.5.2
16
+ python-dotenv==1.0.1
17
+ python-multipart==0.0.12
18
+
19
+ # ── Knowledge RAG ─────────────────────────────────────────────────────────────
20
+ scikit-learn>=1.3.0
21
+
22
+ # ── Audio Processing ──────────────────────────────────────────────────────────
23
+ noisereduce==3.0.3
24
+ webrtcvad==2.0.10
25
+ pydub==0.25.1
26
+ imageio-ffmpeg==0.5.1
27
+ numpy==1.26.4
28
+ scipy==1.13.1
29
+
30
+ # ── Frontend ──────────────────────────────────────────────────────────────────
31
+ streamlit==1.39.0
32
+ streamlit-javascript==0.1.5
33
+
34
+ # ── Logging ───────────────────────────────────────────────────────────────────
35
+ loguru==0.7.2
schemas.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ schemas.py
3
+ ----------
4
+ Pydantic models (request / response schemas) for the Voice & Chat Assistant.
5
+ These models are shared across routes, services, and the action engine —
6
+ ensuring consistent data contracts throughout the entire pipeline.
7
+ """
8
+
9
+ from enum import Enum
10
+ from typing import Optional
11
+ from pydantic import BaseModel, Field
12
+
13
+
14
+ # ── Enumerations ────────────────────────────────────────────────────────────
15
+
16
+ class Language(str, Enum):
17
+ """Supported languages for STT / TTS."""
18
+ ENGLISH = "en-IN"
19
+ HINDI = "hi"
20
+ TAMIL = "ta"
21
+
22
+
23
+ class Intent(str, Enum):
24
+ """
25
+ Financial intents the assistant can detect.
26
+ Extend this list as new use-cases are added.
27
+ """
28
+ REDEMPTION_REQUEST = "redemption_request"
29
+ ACCOUNT_STATEMENT = "account_statement"
30
+ COMPLIANCE_QUERY = "compliance_query"
31
+ PORTFOLIO_ENQUIRY = "portfolio_enquiry"
32
+ TRANSACTION_STATUS = "transaction_status"
33
+ KYC_UPDATE = "kyc_update"
34
+ DIVIDEND_INFO = "dividend_info"
35
+ GENERAL_ENQUIRY = "general_enquiry"
36
+ ESCALATION = "escalation"
37
+ UNKNOWN = "unknown"
38
+
39
+
40
+ class Sentiment(str, Enum):
41
+ """Customer sentiment categories detected from text / voice tone."""
42
+ POSITIVE = "positive"
43
+ NEUTRAL = "neutral"
44
+ NEGATIVE = "negative"
45
+ FRUSTRATED = "frustrated"
46
+ URGENT = "urgent"
47
+
48
+
49
+ class ActionStatus(str, Enum):
50
+ """Status of a triggered backend action."""
51
+ SUCCESS = "success"
52
+ PENDING = "pending"
53
+ BLOCKED_COMPLIANCE = "blocked_compliance"
54
+ FAILED = "failed"
55
+ NOT_REQUIRED = "not_required"
56
+
57
+
58
+ # ── Request Schemas ─────────────────────────────────────────────────────────
59
+
60
+ class ChatRequest(BaseModel):
61
+ """
62
+ Incoming chat (text) request from the user.
63
+
64
+ Attributes:
65
+ message (str): Raw user text message.
66
+ language (Language): Language of the message.
67
+ session_id (str): Unique session identifier for audit trail.
68
+ investor_id (Optional[str]): Investor account ID if already known.
69
+ """
70
+ message: str = Field(
71
+ ...,
72
+ min_length=1,
73
+ max_length=2000,
74
+ description="User's chat message"
75
+ )
76
+ language: Language = Field(
77
+ default=Language.ENGLISH,
78
+ description="Language of the message"
79
+ )
80
+ session_id: str = Field(
81
+ default="",
82
+ description="Unique session ID for audit trail"
83
+ )
84
+ investor_id: Optional[str] = Field(
85
+ default=None,
86
+ description="Optional investor account ID"
87
+ )
88
+ conversation_history: Optional[list] = Field(
89
+ default_factory=list,
90
+ description="Previous chat turns as [{role, content}] for context-aware responses"
91
+ )
92
+
93
+
94
+ class VoiceRequest(BaseModel):
95
+ """
96
+ Metadata accompanying a voice (audio) upload request.
97
+
98
+ Note: The actual audio bytes are passed as a FastAPI UploadFile,
99
+ not in this model. This model carries the auxiliary metadata.
100
+
101
+ Attributes:
102
+ language (Language): Expected language of the audio.
103
+ session_id (str): Unique session identifier for audit trail.
104
+ investor_id (Optional[str]): Investor account ID if already known.
105
+ """
106
+ language: Language = Field(
107
+ default=Language.ENGLISH,
108
+ description="Expected language in the audio"
109
+ )
110
+ session_id: str = Field(
111
+ ...,
112
+ description="Unique session ID for audit trail"
113
+ )
114
+ investor_id: Optional[str] = Field(
115
+ default=None,
116
+ description="Optional investor account ID"
117
+ )
118
+
119
+
120
+ # ── NLP / LLM Result Schemas ────────────────────────────────────────────────
121
+
122
+ class ExtractedEntities(BaseModel):
123
+ """
124
+ Entities extracted from the user's message by the LLM.
125
+
126
+ Attributes:
127
+ investor_id (Optional[str]): Investor/folio account number.
128
+ transaction_type (Optional[str]): e.g., SIP, lump-sum, redemption.
129
+ fund_name (Optional[str]): Mutual fund name mentioned.
130
+ amount (Optional[float]): Transaction amount in INR.
131
+ compliance_flag (Optional[str]): AML/SEBI compliance keyword detected.
132
+ date (Optional[str]): Date mentioned in the query.
133
+ """
134
+ investor_id: Optional[str] = Field(default=None, description="Investor account number")
135
+ transaction_type: Optional[str] = Field(default=None, description="Type of transaction")
136
+ fund_name: Optional[str] = Field(default=None, description="Fund name")
137
+ amount: Optional[float] = Field(default=None, description="Amount in INR")
138
+ compliance_flag: Optional[str] = Field(default=None, description="Compliance keyword detected")
139
+ date: Optional[str] = Field(default=None, description="Date mentioned")
140
+
141
+
142
+ class LLMAnalysisResult(BaseModel):
143
+ """
144
+ Full NLP analysis result returned by the Groq LLM service.
145
+
146
+ Attributes:
147
+ intent (Intent): Detected intent from the user's message.
148
+ sentiment (Sentiment): Detected customer sentiment.
149
+ entities (ExtractedEntities): Extracted financial entities.
150
+ response_text (str): Natural language response to send back to user.
151
+ confidence (float): LLM's confidence score for intent detection (0–1).
152
+ requires_escalation (bool): Whether this should be escalated to a human agent.
153
+ """
154
+ intent: Intent = Field(..., description="Detected intent")
155
+ sentiment: Sentiment = Field(..., description="Detected sentiment")
156
+ entities: ExtractedEntities = Field(default_factory=ExtractedEntities)
157
+ response_text: str = Field(..., description="Response to send to user")
158
+ confidence: float = Field(
159
+ default=0.0,
160
+ ge=0.0,
161
+ le=1.0,
162
+ description="Confidence score for intent (0–1)"
163
+ )
164
+ requires_escalation: bool = Field(
165
+ default=False,
166
+ description="Whether to escalate to human agent"
167
+ )
168
+
169
+
170
+ # ── Action Schemas ──────────────────────────────────────────────────────────
171
+
172
+ class ActionResult(BaseModel):
173
+ """
174
+ Result of an action triggered by the action engine.
175
+
176
+ Attributes:
177
+ action_taken (str): Human-readable description of the action performed.
178
+ status (ActionStatus): Outcome status of the action.
179
+ reference_id (Optional[str]): Transaction / ticket reference ID.
180
+ message (str): Explanation message for the user or internal logs.
181
+ compliance_checked (bool): Whether compliance check was performed.
182
+ """
183
+ action_taken: str = Field(..., description="Description of the action performed")
184
+ status: ActionStatus = Field(..., description="Outcome status")
185
+ reference_id: Optional[str] = Field(default=None, description="Transaction reference ID")
186
+ message: str = Field(..., description="Explanation message")
187
+ compliance_checked: bool = Field(
188
+ default=False,
189
+ description="Whether compliance was validated before action"
190
+ )
191
+
192
+
193
+ # ── Final Response Schema ───────────────────────────────────────────────────
194
+
195
+ class AssistantResponse(BaseModel):
196
+ """
197
+ Final unified response returned to the Streamlit frontend.
198
+
199
+ Attributes:
200
+ session_id (str): Echo of the session ID for tracking.
201
+ transcribed_text (Optional[str]): STT output (only for voice requests).
202
+ intent (Intent): Detected intent.
203
+ sentiment (Sentiment): Detected sentiment.
204
+ entities (ExtractedEntities): Extracted entities.
205
+ response_text (str): Text response to display / speak.
206
+ action_result (Optional[ActionResult]): Result of any triggered action.
207
+ audio_url (Optional[str]): URL / base64 of TTS audio (for voice responses).
208
+ requires_escalation (bool): Whether human escalation is needed.
209
+ confidence (float): Intent detection confidence.
210
+ """
211
+ session_id: str
212
+ transcribed_text: Optional[str] = Field(default=None)
213
+ detected_language: Optional[str] = Field(default=None, description="Auto-detected language from audio")
214
+ intent: Intent
215
+ sentiment: Sentiment
216
+ entities: ExtractedEntities = Field(default_factory=ExtractedEntities)
217
+ response_text: str
218
+ action_result: Optional[ActionResult] = Field(default=None)
219
+ audio_url: Optional[str] = Field(default=None, description="TTS audio as base64")
220
+ requires_escalation: bool = Field(default=False)
221
+ confidence: float = Field(default=0.0, ge=0.0, le=1.0)
services/__init__.py ADDED
File without changes
services/audio_processor.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ services/audio_processor.py
3
+ ----------------------------
4
+ Audio preprocessing pipeline — noise reduction + VAD for ALL formats.
5
+ Uses imageio-ffmpeg (bundled binary) so no manual ffmpeg install is needed.
6
+
7
+ Pipeline (runs for every audio format — WAV, WebM, MP3, OGG):
8
+ 1. Point pydub at imageio-ffmpeg bundled binary
9
+ 2. Convert any format → 16kHz mono WAV
10
+ 3. Noise reduction (noisereduce spectral subtraction)
11
+ 4. VAD — strip silence (webrtcvad)
12
+ 5. Return clean WAV bytes for Sarvam STT
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import io
18
+ import logging
19
+
20
+ import numpy as np
21
+ import noisereduce as nr
22
+ import webrtcvad
23
+ from pydub import AudioSegment
24
+
25
+ # ── Point pydub at imageio-ffmpeg bundled binary (no manual install needed) ───
26
+ try:
27
+ import imageio_ffmpeg
28
+ ffmpeg_path = imageio_ffmpeg.get_ffmpeg_exe()
29
+ AudioSegment.converter = ffmpeg_path
30
+ AudioSegment.ffmpeg = ffmpeg_path
31
+ AudioSegment.ffprobe = ffmpeg_path.replace("ffmpeg", "ffprobe")
32
+ import logging as _l
33
+ _l.getLogger(__name__).info(f"Using bundled ffmpeg: {ffmpeg_path}")
34
+ except Exception as _e:
35
+ _l.getLogger(__name__).warning(
36
+ f"imageio-ffmpeg not available ({_e}). "
37
+ f"WAV-only preprocessing will be used."
38
+ )
39
+ ffmpeg_path = None
40
+
41
+ # ── Module Logger ─────────────────────────────────────────────────────────────
42
+ logger = logging.getLogger(__name__)
43
+
44
+ # ── Constants ─────────────────────────────────────────────────────────────────
45
+ TARGET_SAMPLE_RATE = 16000
46
+ TARGET_CHANNELS = 1
47
+ VAD_AGGRESSIVENESS = 2
48
+ VAD_FRAME_DURATION = 30 # ms — must be 10, 20 or 30
49
+ VAD_PADDING_DURATION = 300 # ms padding around speech
50
+ MIN_SPEECH_DURATION = 500 # ms minimum speech after VAD
51
+
52
+
53
+ def _convert_to_wav(audio_bytes: bytes, mime_type: str) -> AudioSegment:
54
+ """
55
+ Convert any audio format to 16kHz mono WAV AudioSegment.
56
+ Uses imageio-ffmpeg bundled binary so no manual install needed.
57
+
58
+ Args:
59
+ audio_bytes (bytes): Raw audio bytes.
60
+ mime_type (str): MIME type e.g. 'audio/webm', 'audio/wav'.
61
+
62
+ Returns:
63
+ AudioSegment: 16kHz mono PCM segment.
64
+
65
+ Raises:
66
+ RuntimeError: If conversion fails.
67
+ """
68
+ fmt_map = {
69
+ "audio/mpeg": "mp3",
70
+ "audio/mp3": "mp3",
71
+ "audio/wav": "wav",
72
+ "audio/wave": "wav",
73
+ "audio/x-wav": "wav",
74
+ "audio/ogg": "ogg",
75
+ "audio/webm": "webm",
76
+ }
77
+ fmt = fmt_map.get(mime_type, "wav")
78
+
79
+ try:
80
+ if fmt == "wav":
81
+ segment = AudioSegment.from_wav(io.BytesIO(audio_bytes))
82
+ elif fmt == "mp3":
83
+ segment = AudioSegment.from_mp3(io.BytesIO(audio_bytes))
84
+ elif fmt == "ogg":
85
+ segment = AudioSegment.from_ogg(io.BytesIO(audio_bytes))
86
+ else:
87
+ # webm and other formats — needs ffmpeg (bundled via imageio-ffmpeg)
88
+ segment = AudioSegment.from_file(io.BytesIO(audio_bytes), format=fmt)
89
+
90
+ segment = segment.set_frame_rate(TARGET_SAMPLE_RATE)
91
+ segment = segment.set_channels(TARGET_CHANNELS)
92
+ segment = segment.set_sample_width(2) # 16-bit PCM
93
+
94
+ logger.debug(
95
+ f"Converted | fmt={fmt} | duration={len(segment)}ms | "
96
+ f"rate={segment.frame_rate}Hz"
97
+ )
98
+ return segment
99
+
100
+ except Exception as e:
101
+ logger.error(f"Audio format conversion failed: {str(e)}")
102
+ raise RuntimeError(f"Failed to convert audio format: {str(e)}") from e
103
+
104
+
105
+ def _reduce_noise(segment: AudioSegment) -> AudioSegment:
106
+ """
107
+ Spectral noise reduction via noisereduce.
108
+ Estimates noise from the signal itself and subtracts it.
109
+
110
+ Args:
111
+ segment (AudioSegment): 16kHz mono PCM segment.
112
+
113
+ Returns:
114
+ AudioSegment: Noise-reduced segment (falls back to original on failure).
115
+ """
116
+ try:
117
+ samples = np.array(segment.get_array_of_samples(), dtype=np.float32)
118
+ samples = samples / 32768.0
119
+
120
+ reduced = nr.reduce_noise(
121
+ y = samples,
122
+ sr = TARGET_SAMPLE_RATE,
123
+ stationary = True,
124
+ prop_decrease = 0.75,
125
+ )
126
+
127
+ reduced_int16 = (reduced * 32768.0).astype(np.int16)
128
+ clean = AudioSegment(
129
+ data = reduced_int16.tobytes(),
130
+ sample_width = 2,
131
+ frame_rate = TARGET_SAMPLE_RATE,
132
+ channels = TARGET_CHANNELS,
133
+ )
134
+ logger.debug(f"Noise reduction done | rms {segment.rms} → {clean.rms}")
135
+ return clean
136
+
137
+ except Exception as e:
138
+ logger.warning(f"Noise reduction failed — using original. Error: {e}")
139
+ return segment
140
+
141
+
142
+ def _apply_vad(segment: AudioSegment) -> AudioSegment:
143
+ """
144
+ Strip silence and non-speech using WebRTC VAD.
145
+
146
+ Args:
147
+ segment (AudioSegment): 16kHz mono PCM segment.
148
+
149
+ Returns:
150
+ AudioSegment: Speech-only segment (falls back to original on failure).
151
+ """
152
+ try:
153
+ vad = webrtcvad.Vad(VAD_AGGRESSIVENESS)
154
+ frame_length = int(TARGET_SAMPLE_RATE * VAD_FRAME_DURATION / 1000)
155
+ raw_bytes = segment.raw_data
156
+
157
+ frames = [
158
+ raw_bytes[i: i + frame_length * 2]
159
+ for i in range(0, len(raw_bytes) - frame_length * 2, frame_length * 2)
160
+ ]
161
+
162
+ if not frames:
163
+ return segment
164
+
165
+ speech_flags = []
166
+ for frame in frames:
167
+ try:
168
+ speech_flags.append(vad.is_speech(frame, TARGET_SAMPLE_RATE))
169
+ except Exception:
170
+ speech_flags.append(False)
171
+
172
+ speech_ratio = sum(speech_flags) / len(speech_flags)
173
+ logger.debug(f"VAD speech ratio: {speech_ratio:.1%}")
174
+
175
+ if speech_ratio < 0.1:
176
+ logger.warning("Very low speech ratio — skipping VAD to avoid over-filtering.")
177
+ return segment
178
+
179
+ # Pad speech frames
180
+ padding = int(VAD_PADDING_DURATION / VAD_FRAME_DURATION)
181
+ padded = list(speech_flags)
182
+ for i, is_speech in enumerate(speech_flags):
183
+ if is_speech:
184
+ for j in range(max(0, i - padding), min(len(padded), i + padding + 1)):
185
+ padded[j] = True
186
+
187
+ speech_bytes = b"".join(f for f, flag in zip(frames, padded) if flag)
188
+
189
+ if not speech_bytes:
190
+ return segment
191
+
192
+ result = AudioSegment(
193
+ data = speech_bytes,
194
+ sample_width = 2,
195
+ frame_rate = TARGET_SAMPLE_RATE,
196
+ channels = TARGET_CHANNELS,
197
+ )
198
+
199
+ if len(result) < MIN_SPEECH_DURATION:
200
+ logger.warning(f"VAD result too short ({len(result)}ms) — using original.")
201
+ return segment
202
+
203
+ logger.debug(f"VAD done | {len(segment)}ms → {len(result)}ms")
204
+ return result
205
+
206
+ except Exception as e:
207
+ logger.warning(f"VAD failed — using original. Error: {e}")
208
+ return segment
209
+
210
+
211
+ def _to_wav_bytes(segment: AudioSegment) -> bytes:
212
+ """Export AudioSegment to WAV bytes."""
213
+ buf = io.BytesIO()
214
+ segment.export(buf, format="wav")
215
+ return buf.getvalue()
216
+
217
+
218
+ async def preprocess_audio(
219
+ audio_bytes: bytes,
220
+ mime_type: str = "audio/wav",
221
+ apply_noise_reduction: bool = True,
222
+ apply_vad: bool = True,
223
+ ) -> tuple[bytes, str]:
224
+ """
225
+ Full preprocessing pipeline for ALL audio formats.
226
+ Uses bundled ffmpeg (imageio-ffmpeg) — no manual install needed.
227
+
228
+ Pipeline:
229
+ 1. Convert any format → 16kHz mono WAV
230
+ 2. Noise reduction (spectral subtraction)
231
+ 3. VAD (strip silence)
232
+ 4. Export clean WAV bytes
233
+
234
+ Gracefully falls back to raw bytes if any step fails.
235
+
236
+ Args:
237
+ audio_bytes (bytes): Raw audio in any format.
238
+ mime_type (str): MIME type e.g. 'audio/webm', 'audio/wav'.
239
+ apply_noise_reduction (bool): Run noise reduction. Default True.
240
+ apply_vad (bool): Run VAD. Default True.
241
+
242
+ Returns:
243
+ tuple[bytes, str]: (clean WAV bytes, 'audio/wav')
244
+
245
+ Raises:
246
+ ValueError: If audio_bytes is empty.
247
+ """
248
+ if not audio_bytes:
249
+ raise ValueError("audio_bytes cannot be empty.")
250
+
251
+ logger.info(
252
+ f"Preprocessing | mime={mime_type} | size={len(audio_bytes)} bytes | "
253
+ f"nr={apply_noise_reduction} | vad={apply_vad}"
254
+ )
255
+
256
+ try:
257
+ # Step 1: Convert to WAV
258
+ segment = _convert_to_wav(audio_bytes, mime_type)
259
+ logger.info(f"Step 1 done | duration={len(segment)}ms")
260
+
261
+ # Step 2: Noise reduction
262
+ if apply_noise_reduction:
263
+ segment = _reduce_noise(segment)
264
+ logger.info(f"Step 2 done | duration={len(segment)}ms")
265
+
266
+ # Step 3: VAD
267
+ if apply_vad:
268
+ segment = _apply_vad(segment)
269
+ logger.info(f"Step 3 done | duration={len(segment)}ms")
270
+
271
+ # Step 4: Export
272
+ clean_bytes = _to_wav_bytes(segment)
273
+ logger.info(
274
+ f"Preprocessing complete | "
275
+ f"{len(audio_bytes)} bytes → {len(clean_bytes)} bytes"
276
+ )
277
+ return clean_bytes, "audio/wav"
278
+
279
+ except Exception as e:
280
+ logger.warning(f"Preprocessing failed ({e}) — sending raw audio to Sarvam.")
281
+ return audio_bytes, mime_type
services/data_retriever.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ services/data_retriever.py
3
+ ---------------------------
4
+ Smart context retriever — decides which RAG path to use based on intent.
5
+
6
+ PATH A (Account data — instant):
7
+ portfolio_enquiry, account_statement, transaction_status,
8
+ redemption_request, dividend_info
9
+ → Exact PAN/ID lookup from investors.json
10
+
11
+ PATH B (Knowledge — ~300ms):
12
+ compliance_query, kyc_update, general_enquiry
13
+ → Groq embed + ChromaDB search over knowledge_base.json
14
+
15
+ Both paths return a formatted context string injected into the LLM prompt.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import logging
20
+ import re
21
+ from typing import Optional
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+ # Intents that need account data (PATH A)
26
+ ACCOUNT_INTENTS = {
27
+ "portfolio_enquiry",
28
+ "account_statement",
29
+ "transaction_status",
30
+ "redemption_request",
31
+ "dividend_info",
32
+ }
33
+
34
+ # Intents that need knowledge base (PATH B)
35
+ KNOWLEDGE_INTENTS = {
36
+ "compliance_query",
37
+ "kyc_update",
38
+ "general_enquiry",
39
+ "unknown",
40
+ }
41
+
42
+ PAN_RE = re.compile(r"\b[A-Z]{5}[0-9]{4}[A-Z]\b", re.IGNORECASE)
43
+ CAMSID_RE = re.compile(r"\bCAMS\d{5}\b", re.IGNORECASE)
44
+
45
+
46
+ def extract_identifiers(text: str) -> dict:
47
+ pan_m = PAN_RE.search(text.upper())
48
+ id_m = CAMSID_RE.search(text.upper())
49
+ return {
50
+ "pan": pan_m.group(0) if pan_m else None,
51
+ "investor_id": id_m.group(0) if id_m else None,
52
+ }
53
+
54
+
55
+ def format_investor_context(investor: dict) -> str:
56
+ """Format investor record as LLM-readable context string."""
57
+ lines = [
58
+ "INVESTOR ACCOUNT DATA:",
59
+ f" Name: {investor['name']}",
60
+ f" PAN: {investor['pan']}",
61
+ f" Investor ID: {investor['investor_id']}",
62
+ f" KYC Status: {investor['kyc_status']}",
63
+ f" City: {investor['city']}",
64
+ f" Member Since: {investor['account_since']}",
65
+ "",
66
+ "PORTFOLIO SUMMARY:",
67
+ f" Total Invested: ₹{investor['total_invested']:,.2f}",
68
+ f" Current Value: ₹{investor['total_current_value']:,.2f}",
69
+ f" Total Gain/Loss: ₹{investor['total_gain_loss']:,.2f} ({investor['total_gain_loss_pct']:+.2f}%)",
70
+ f" Monthly SIP: ₹{investor['total_sip_amount']:,}",
71
+ f" Number of Funds: {investor['num_funds']}",
72
+ "",
73
+ "FUND HOLDINGS:",
74
+ ]
75
+ for i, h in enumerate(investor["holdings"], 1):
76
+ sign = "+" if h["gain_loss"] >= 0 else ""
77
+ lines += [
78
+ f" {i}. {h['fund_name']} ({h['category']})",
79
+ f" Units: {h['units']} | NAV: ₹{h['nav']} | Value: ₹{h['current_value']:,.2f}",
80
+ f" Invested: ₹{h['invested_amount']:,.2f} | "
81
+ f"Gain/Loss: {sign}₹{h['gain_loss']:,.2f} ({sign}{h['gain_loss_pct']}%)",
82
+ f" SIP: {'₹'+str(h['sip_amount'])+'/month on '+str(h['sip_date'])+'th' if h['sip_active'] else 'No active SIP'} | Option: {h['dividend_option']}",
83
+ ]
84
+ if investor.get("recent_transactions"):
85
+ lines += ["", "RECENT TRANSACTIONS:"]
86
+ for t in investor["recent_transactions"][:3]:
87
+ lines.append(
88
+ f" [{t['date']}] {t['type']} | {t['fund_name']} | "
89
+ f"₹{t['amount']:,} | {t['units']} units | {t['status']} | Ref: {t['txn_id']}"
90
+ )
91
+ return "\n".join(lines)
92
+
93
+
94
+ async def get_context(
95
+ user_message: str,
96
+ intent: Optional[str] = None,
97
+ pan: Optional[str] = None,
98
+ investor_id: Optional[str] = None,
99
+ ) -> tuple[Optional[dict], str]:
100
+ """
101
+ Main retriever entry point.
102
+
103
+ Args:
104
+ user_message: Raw user text
105
+ intent: Detected intent (used to choose path A or B)
106
+ pan: PAN if already known from session
107
+ investor_id: Investor ID if already known
108
+
109
+ Returns:
110
+ (investor_record_or_None, context_string_for_llm)
111
+ """
112
+ from services.vector_store import get_vector_store
113
+ vs = get_vector_store()
114
+
115
+ # Extract identifiers from message
116
+ ids = extract_identifiers(user_message)
117
+ pan = pan or ids["pan"]
118
+ investor_id = investor_id or ids["investor_id"]
119
+
120
+ # ── PATH A: Account data (exact lookup) ───────────────────────────────
121
+ if intent in ACCOUNT_INTENTS or intent is None:
122
+ investor = vs.get_investor(pan=pan, investor_id=investor_id, query=user_message)
123
+ if investor:
124
+ context = format_investor_context(investor)
125
+ logger.info(f"PATH A: account data retrieved for {investor['name']}")
126
+ return investor, context
127
+ # No identifier found — return nothing, LLM will ask for PAN
128
+ logger.info("PATH A: no identifier found — LLM will ask for PAN")
129
+ return None, ""
130
+
131
+ # ── PATH B: Knowledge base RAG ────────────────────────────────────────
132
+ if intent in KNOWLEDGE_INTENTS:
133
+ kb_context = await vs.search_knowledge(user_message, top_k=2)
134
+ if kb_context:
135
+ logger.info(f"PATH B: knowledge context retrieved ({len(kb_context)} chars)")
136
+ return None, kb_context
137
+ logger.info("PATH B: no KB match found")
138
+ return None, ""
139
+
140
+ return None, ""
141
+
142
+
143
+ async def get_investor_context(
144
+ user_message: str,
145
+ extracted_entities: Optional[dict] = None,
146
+ ) -> tuple[Optional[dict], str]:
147
+ """
148
+ Backward-compatible wrapper used by main.py.
149
+ Passes through to get_context without intent routing
150
+ (intent not known yet at this stage — LLM determines it).
151
+ """
152
+ pan = None
153
+ investor_id = None
154
+ if extracted_entities:
155
+ investor_id = extracted_entities.get("investor_id")
156
+
157
+ ids = extract_identifiers(user_message)
158
+ pan = ids["pan"]
159
+ investor_id = investor_id or ids["investor_id"]
160
+
161
+ from services.vector_store import get_vector_store
162
+ vs = get_vector_store()
163
+ investor = vs.get_investor(pan=pan, investor_id=investor_id, query=user_message)
164
+
165
+ if investor:
166
+ context = format_investor_context(investor)
167
+ logger.info(f"Investor context: {investor['name']} | ₹{investor['total_current_value']:,.0f}")
168
+ return investor, context
169
+
170
+ return None, ""
services/groq_llm.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ services/groq_llm.py
3
+ ---------------------
4
+ Single LLM call per request — intent + response in one shot.
5
+ Optimized for <1s Groq latency with financial domain prompt.
6
+ """
7
+ from __future__ import annotations
8
+ import json
9
+ import logging
10
+ from typing import Optional
11
+ from groq import Groq, APIConnectionError, APIStatusError, RateLimitError
12
+ from schemas import LLMAnalysisResult, ExtractedEntities, Intent, Sentiment
13
+ from config import settings
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ # ── System Prompt — Financial domain, concise, fast ──────────────────────────
18
+ SYSTEM_PROMPT = """\
19
+ You are CAMS Assistant — a voice-first AI for CAMS (Computer Age Management Services), \
20
+ India's largest mutual fund registrar. You help investors with portfolio queries, SIPs, \
21
+ redemptions, KYC, and compliance. You speak like a knowledgeable, warm Indian financial advisor.
22
+
23
+ RESPONSE FORMAT — return ONLY valid JSON, no markdown, no explanation:
24
+ {
25
+ "intent": "<intent>",
26
+ "sentiment": "<sentiment>",
27
+ "confidence": <0.0-1.0>,
28
+ "requires_escalation": <true|false>,
29
+ "entities": {
30
+ "investor_id": "<string|null>",
31
+ "fund_name": "<string|null>",
32
+ "amount": <number|null>,
33
+ "transaction_type": "<string|null>",
34
+ "compliance_flag": "<string|null>",
35
+ "date": "<string|null>"
36
+ },
37
+ "response_text": "<your reply to the customer>"
38
+ }
39
+
40
+ INTENTS:
41
+ portfolio_enquiry — balance, current value, fund performance, gains/losses
42
+ account_statement — statement, transaction history, capital gains report
43
+ redemption_request — redeem, withdraw, sell units
44
+ transaction_status — status of SIP, lump-sum, redemption transaction
45
+ sip_enquiry — SIP amount, SIP date, pause, cancel, modify SIP
46
+ kyc_update — update address, mobile, bank, nominee, email
47
+ compliance_query — SEBI rules, AML, FATCA, tax, exit load, lock-in
48
+ dividend_info — IDCW, dividend declared, payout date
49
+ general_enquiry — greetings, CAMS services, how-to questions
50
+ escalation — human agent requested, very upset customer
51
+ unknown — cannot determine
52
+
53
+ SENTIMENTS: positive | neutral | negative | frustrated | urgent
54
+
55
+ ESCALATION: set true only if customer explicitly asks for human/manager, \
56
+ mentions SEBI complaint or legal action, or sentiment is frustrated.
57
+
58
+ ━━━ FINANCIAL KNOWLEDGE (use this to answer accurately) ━━━
59
+ • NAV: calculated daily; redemptions use same-day NAV if submitted before 3 PM
60
+ • Redemption settlement: Equity/Hybrid T+3, Debt T+2, Liquid T+1 working days
61
+ • Exit load: Most equity funds 1% if redeemed within 1 year; ELSS has 3-yr lock-in
62
+ • ELSS: Tax saving under Sec 80C up to ₹1.5L/yr; 3-year mandatory lock-in
63
+ • SIP: Min ₹100-500/month; pause up to 3 months; cancel 7 days before next date
64
+ • Capital Gains Tax: STCG equity <1yr = 20%; LTCG equity >1yr = 12.5% above ₹1.25L
65
+ • IDCW (formerly Dividend): Not guaranteed; taxable as per investor's income slab; TDS 10% above ₹5000/yr
66
+ • KYC: PAN mandatory; Aadhaar for address; update via camsonline.com or service centre
67
+ • AML: PAN required for transactions >₹50,000; suspicious transactions reported to FIU-IND
68
+ • FATCA: US persons must declare US tax status; self-certification mandatory
69
+ • CAMS portal: camsonline.com | Toll-free: 1800-3010-6767 | Mon-Fri 8AM-8PM
70
+
71
+ ━━━ BEHAVIOUR RULES ━━━
72
+ 1. INVESTOR DATA provided → use exact numbers. Never say "check the portal" when data is available.
73
+ 2. NO investor data + no PAN in history → ask for PAN ONCE only.
74
+ If chat history already contains a PAN (pattern: 5 letters + 4 digits + 1 letter) → DO NOT ask again.
75
+ 3. Ask ONE clarifying question at a time.
76
+ 4. Redemption: ask fund name first → then amount/units.
77
+ 5. KYC update: ask what to update → guide to camsonline.com or service centre.
78
+ 6. Response: 1-3 sentences, conversational, voice-friendly. No bullet points, no markdown.
79
+ 7. Never say "as an AI" or "I cannot access real-time data". Answer from the data provided.
80
+ 8. ACCOUNT SWITCHING: If user gives a NEW PAN different from history, or says "another account" /
81
+ "different account" — the RETRIEVED DATA block will already contain the correct investor.
82
+ Just answer using whatever data is in the RETRIEVED DATA block.
83
+ 9. "What is my name" / "my details" → answer from the Name field in RETRIEVED DATA.
84
+ 10. Language: Tamil input → Tamil reply. Hindi input → Hindi reply. Default → English. Never mix.
85
+ """
86
+
87
+ # ── Groq client singleton ─────────────────────────────────────────────────────
88
+ _groq_client: Optional[Groq] = None
89
+
90
+ def _get_client() -> Groq:
91
+ global _groq_client
92
+ if _groq_client is None:
93
+ if not settings.groq_api_key:
94
+ raise ValueError("GROQ_API_KEY not set.")
95
+ import httpx
96
+ _groq_client = Groq(
97
+ api_key = settings.groq_api_key,
98
+ http_client = httpx.Client(
99
+ timeout = httpx.Timeout(connect=3.0, read=15.0, write=5.0, pool=2.0),
100
+ limits = httpx.Limits(max_connections=5, max_keepalive_connections=3),
101
+ ),
102
+ )
103
+ logger.info("Groq client ready (connection pooling enabled)")
104
+ return _groq_client
105
+
106
+
107
+ async def analyse_message(
108
+ user_message: str,
109
+ language: str = "en",
110
+ investor_id: Optional[str] = None,
111
+ conversation_history: Optional[list] = None,
112
+ investor_context: Optional[str] = None,
113
+ ) -> LLMAnalysisResult:
114
+ """
115
+ Single LLM call: intent + entity extraction + response generation.
116
+ Injects investor data or KB context directly into the user prompt.
117
+ """
118
+ if not user_message or not user_message.strip():
119
+ raise ValueError("user_message is empty.")
120
+
121
+ msg = user_message.strip()
122
+
123
+ # ── Language hint ─────────────────────────────────────────────────────
124
+ lang_map = {"en": "English", "hi": "Hindi", "ta": "Tamil", "en-IN": "English"}
125
+ lang_name = lang_map.get(language, "English")
126
+
127
+ # ── Build user prompt ─────────────────────────────────────────────────
128
+ # Investor/KB context injected HERE — not in system prompt — keeps system prompt cached
129
+ context_block = ""
130
+ if investor_context:
131
+ context_block = (
132
+ f"\n\n--- RETRIEVED DATA ---\n{investor_context}\n--- END DATA ---\n"
133
+ "Use the above data to answer with exact numbers and fund names."
134
+ )
135
+
136
+ user_prompt = (
137
+ f'Customer said: "{msg}"\n'
138
+ f"Reply in: {lang_name}"
139
+ f"{context_block}\n\n"
140
+ "Return JSON only."
141
+ )
142
+
143
+ # ── Conversation history (last 4 turns only for speed) ────────────────
144
+ messages = [{"role": "system", "content": SYSTEM_PROMPT}]
145
+ if conversation_history:
146
+ for turn in (conversation_history or [])[-4:]:
147
+ messages.append({"role": turn["role"], "content": str(turn["content"])})
148
+ messages.append({"role": "user", "content": user_prompt})
149
+
150
+ logger.info(f"LLM call | lang={language} | ctx={'yes' if investor_context else 'no'} | '{msg[:50]}'")
151
+
152
+ try:
153
+ client = _get_client()
154
+ completion = client.chat.completions.create(
155
+ model = "llama-3.1-8b-instant",
156
+ messages = messages,
157
+ max_tokens = 300, # JSON response fits in 250 tokens
158
+ temperature = 0.1,
159
+ response_format = {"type": "json_object"},
160
+ stream = False,
161
+ )
162
+
163
+ raw = (completion.choices[0].message.content or "").strip()
164
+ if not raw:
165
+ raise RuntimeError("Empty LLM response.")
166
+
167
+ parsed = json.loads(raw)
168
+
169
+ try:
170
+ intent = Intent(parsed.get("intent", "unknown"))
171
+ except ValueError:
172
+ intent = Intent.UNKNOWN
173
+
174
+ try:
175
+ sentiment = Sentiment(parsed.get("sentiment", "neutral"))
176
+ except ValueError:
177
+ sentiment = Sentiment.NEUTRAL
178
+
179
+ e = parsed.get("entities") or {}
180
+ entities = ExtractedEntities(
181
+ investor_id = e.get("investor_id"),
182
+ transaction_type = e.get("transaction_type"),
183
+ fund_name = e.get("fund_name"),
184
+ amount = e.get("amount"),
185
+ compliance_flag = e.get("compliance_flag"),
186
+ date = e.get("date"),
187
+ )
188
+
189
+ result = LLMAnalysisResult(
190
+ intent = intent,
191
+ sentiment = sentiment,
192
+ entities = entities,
193
+ response_text = parsed.get("response_text", "Could you please clarify?"),
194
+ confidence = float(parsed.get("confidence", 0.8)),
195
+ requires_escalation = bool(parsed.get("requires_escalation", False)),
196
+ )
197
+ logger.info(f"LLM done | intent={result.intent} | confidence={result.confidence:.0%}")
198
+ return result
199
+
200
+ except json.JSONDecodeError as e:
201
+ raise RuntimeError(f"LLM returned invalid JSON: {e}") from e
202
+ except RateLimitError as e:
203
+ raise RuntimeError("Service busy — please retry.") from e
204
+ except APIConnectionError as e:
205
+ raise RuntimeError(f"Cannot reach AI service: {e}") from e
206
+ except APIStatusError as e:
207
+ raise RuntimeError(f"AI service error {e.status_code}: {e}") from e
208
+ except Exception as e:
209
+ logger.error(f"LLM error: {e}", exc_info=True)
210
+ raise RuntimeError(f"Analysis failed: {e}") from e
services/sarvam_stt.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ services/sarvam_stt.py
3
+ -----------------------
4
+ Speech-to-Text (STT) service using Sarvam AI Saaras:v3.
5
+ Handles all three supported languages: English, Hindi, Tamil.
6
+ Auto-detects language from audio — no language input required.
7
+
8
+ Pipeline:
9
+ 1. Preprocess audio (noise reduction + VAD)
10
+ 2. Send to Sarvam AI Saaras:v3 for transcription + language detection
11
+
12
+ Why Sarvam AI?
13
+ - Built specifically for Indian languages (22 languages supported)
14
+ - Accurate for Tamil, Hindi, and Indian-accented English
15
+ - Auto language detection works correctly for all three
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import logging
21
+ import httpx
22
+ from config import settings
23
+ from .audio_processor import preprocess_audio
24
+
25
+ # ── Module Logger ─────────────────────────────────────────────────────────────
26
+ logger = logging.getLogger(__name__)
27
+
28
+ # ── Constants ─────────────────────────────────────────────────────────────────
29
+ SARVAM_STT_URL = "https://api.sarvam.ai/speech-to-text"
30
+
31
+ # ── Language Code Normalisation ───────────────────────────────────────────────
32
+ SARVAM_LANG_MAP = {
33
+ "ta-in": "ta", "ta": "ta",
34
+ "hi-in": "hi", "hi": "hi",
35
+ "en-in": "en", "en": "en",
36
+ }
37
+
38
+
39
+ async def transcribe_audio(
40
+ audio_bytes: bytes,
41
+ mime_type: str = "audio/wav",
42
+ ) -> dict:
43
+ """
44
+ Transcribe audio using Sarvam AI Saaras:v3.
45
+ Auto-detects language (en / hi / ta) from the audio content.
46
+
47
+ Pipeline:
48
+ 1. Preprocess audio (noise reduction + VAD)
49
+ 2. Sarvam AI transcribes + detects language
50
+
51
+ Args:
52
+ audio_bytes (bytes): Raw audio bytes in any supported format.
53
+ mime_type (str): MIME type e.g. 'audio/wav', 'audio/mp3'.
54
+
55
+ Returns:
56
+ dict: Result containing:
57
+ - "transcript" (str): Transcribed text.
58
+ - "confidence" (float): Confidence score (always 1.0 — Sarvam does not return this).
59
+ - "detected_language" (str): Normalised language code (en / hi / ta).
60
+ - "words" (list): Empty list — Sarvam does not return word timestamps.
61
+ - "stt_provider" (str): Always 'sarvam'.
62
+
63
+ Raises:
64
+ ValueError: If audio_bytes is empty.
65
+ RuntimeError: If Sarvam API call fails or returns no transcript.
66
+ """
67
+ if not audio_bytes:
68
+ logger.error("transcribe_audio called with empty audio bytes.")
69
+ raise ValueError("audio_bytes cannot be empty.")
70
+
71
+ logger.info(
72
+ f"Starting STT pipeline | "
73
+ f"audio_size={len(audio_bytes)} bytes | mime_type={mime_type}"
74
+ )
75
+
76
+ try:
77
+ # ── Step 1: Preprocess — denoise + VAD ───────────────────────────
78
+ logger.info("Step 1: Preprocessing audio...")
79
+ audio_bytes, mime_type = await preprocess_audio(
80
+ audio_bytes = audio_bytes,
81
+ mime_type = mime_type,
82
+ apply_noise_reduction = False, # Sarvam handles noise — skip for speed
83
+ apply_vad = False, # Sarvam handles silence — skip for speed
84
+ )
85
+ logger.info(f"Preprocessing done | clean_size={len(audio_bytes)} bytes")
86
+
87
+ # ── Step 2: Sarvam AI STT ─────────────────────────────────────────
88
+ logger.info(f"Step 2: Sending to Sarvam AI | model={settings.sarvam_stt_model}")
89
+
90
+ filename = "audio.wav" if "wav" in mime_type else "audio.mp3"
91
+ files = {"file": (filename, audio_bytes, mime_type)}
92
+ form_data = {
93
+ "model": settings.sarvam_stt_model, # saaras:v3
94
+ "language_code": "unknown", # Auto-detect language
95
+ }
96
+ headers = {
97
+ "api-subscription-key": settings.sarvam_api_key,
98
+ }
99
+
100
+ logger.debug("Sending audio to Sarvam AI STT API...")
101
+ async with httpx.AsyncClient(timeout=60.0) as client:
102
+ response = await client.post(
103
+ SARVAM_STT_URL,
104
+ files = files,
105
+ data = form_data,
106
+ headers = headers,
107
+ )
108
+
109
+ # ── Handle API errors ─────────────────────────────────────────────
110
+ if response.status_code != 200:
111
+ error_body = response.text
112
+ logger.error(
113
+ f"Sarvam STT API error | status={response.status_code} | "
114
+ f"body={error_body[:300]}"
115
+ )
116
+ raise RuntimeError(
117
+ f"Sarvam STT API returned HTTP {response.status_code}: {error_body[:200]}"
118
+ )
119
+
120
+ result = response.json()
121
+ logger.debug(f"Sarvam raw response: {str(result)[:300]}")
122
+
123
+ # ── Parse response ────────────────────────────────────────────────
124
+ transcript = (result.get("transcript") or "").strip()
125
+
126
+ if not transcript:
127
+ logger.warning("Sarvam STT returned an empty transcript.")
128
+ raise RuntimeError(
129
+ "No speech detected in the audio. "
130
+ "Please check audio quality or speak closer to the microphone."
131
+ )
132
+
133
+ # ── Normalise detected language ───────────────────────────────────
134
+ raw_lang = (result.get("language_code") or "en").lower().strip()
135
+ detected_language = SARVAM_LANG_MAP.get(raw_lang, "en")
136
+
137
+ logger.info(
138
+ f"STT complete | provider=sarvam | "
139
+ f"raw_lang={raw_lang} | detected_language={detected_language} | "
140
+ f"transcript='{transcript[:80]}'"
141
+ )
142
+
143
+ return {
144
+ "transcript": transcript,
145
+ "confidence": 1.0,
146
+ "detected_language": detected_language,
147
+ "words": [],
148
+ "stt_provider": "sarvam",
149
+ }
150
+
151
+ except (ValueError, RuntimeError):
152
+ raise
153
+ except httpx.TimeoutException as e:
154
+ logger.error(f"Sarvam STT timed out: {str(e)}")
155
+ raise RuntimeError("Sarvam STT request timed out. Please try again.") from e
156
+ except Exception as e:
157
+ logger.error(f"Unexpected error during Sarvam STT: {str(e)}", exc_info=True)
158
+ raise RuntimeError(f"Audio transcription failed: {str(e)}") from e
services/sarvam_tts.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ services/sarvam_tts.py
3
+ -----------------------
4
+ Text-to-Speech service using Sarvam AI Bulbul v3.
5
+ Replaces Deepgram TTS for all languages — English, Hindi, and Tamil.
6
+
7
+ Why Sarvam Bulbul v3?
8
+ - Purpose-built for Indian languages and Indian English accent
9
+ - 30+ natural-sounding voices
10
+ - Handles code-mixed text (e.g. Hinglish) natively
11
+ - Supports en-IN, hi-IN, ta-IN natively
12
+ - Returns base64-encoded WAV audio directly
13
+
14
+ API: POST https://api.sarvam.ai/text-to-speech
15
+ - model: bulbul:v3
16
+ - inputs: list of text strings
17
+ - target_language_code: en-IN / hi-IN / ta-IN
18
+ - speaker: Meera (female, clear) — works well for all 3 languages
19
+ - Response: {"audios": ["<base64_wav>", ...]}
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import base64
25
+ import logging
26
+ import httpx
27
+ from config import settings
28
+
29
+ # ── Module Logger ─────────────────────────────────────────────────────────────
30
+ logger = logging.getLogger(__name__)
31
+
32
+ # ── Sarvam TTS Constants ──────────────────────────────────────────────────────
33
+ SARVAM_TTS_URL = "https://api.sarvam.ai/text-to-speech"
34
+ SARVAM_TTS_MODEL = "bulbul:v3"
35
+
36
+ # ── Language → BCP-47 code mapping ───────────────────────────────────────────
37
+ LANGUAGE_CODE_MAP: dict[str, str] = {
38
+ "en": "en-IN",
39
+ "en-IN": "en-IN",
40
+ "hi": "hi-IN",
41
+ "hi-IN": "hi-IN",
42
+ "ta": "ta-IN",
43
+ "ta-IN": "ta-IN",
44
+ }
45
+ # Alias used by main.py
46
+ LANGUAGE_MAP = LANGUAGE_CODE_MAP
47
+
48
+ # ── Language → Speaker mapping ────────────────────────────────────────────────
49
+ LANGUAGE_SPEAKER_MAP: dict[str, str] = {
50
+ "en-IN": "anushka", # Clear female English (Indian accent)
51
+ "hi-IN": "anushka", # Natural Hindi female voice
52
+ "ta-IN": "anushka", # Natural Tamil female voice
53
+ }
54
+ DEFAULT_SPEAKER = "anushka"
55
+
56
+
57
+ async def synthesize_speech(
58
+ text: str,
59
+ detected_language: str = "en",
60
+ encode_base64: bool = True,
61
+ ) -> dict:
62
+ """
63
+ Convert text to speech using Sarvam AI Bulbul v3.
64
+ Responds in the same language as the detected input language.
65
+
66
+ Args:
67
+ text (str): Text to synthesize. Max 2500 characters (Bulbul v3 limit).
68
+ detected_language (str): Short language code from STT e.g. 'en', 'hi', 'ta'.
69
+ Defaults to 'en'.
70
+ encode_base64 (bool): If True returns base64 string (for JSON transport).
71
+ If False returns raw bytes. Defaults to True.
72
+
73
+ Returns:
74
+ dict: Result containing:
75
+ - "audio" (str | bytes): Base64 string or raw WAV bytes.
76
+ - "voice_model" (str): TTS model used.
77
+ - "language" (str): BCP-47 language code used.
78
+ - "speaker" (str): Speaker voice used.
79
+ - "character_count" (int): Number of characters synthesized.
80
+
81
+ Raises:
82
+ ValueError: If text is empty.
83
+ RuntimeError: If Sarvam TTS API call fails.
84
+ """
85
+ if not text or not text.strip():
86
+ logger.error("synthesize_speech called with empty text.")
87
+ raise ValueError("Text for TTS cannot be empty.")
88
+
89
+ text = text.strip()
90
+
91
+ # Bulbul v3 supports up to 2500 characters
92
+ if len(text) > 2500:
93
+ logger.warning(f"TTS text too long ({len(text)} chars). Truncating to 2500.")
94
+ text = text[:2500]
95
+
96
+ # ── Resolve language code and speaker ─────────────────────────────────
97
+ language_code = LANGUAGE_CODE_MAP.get(detected_language, "en-IN")
98
+ speaker = LANGUAGE_SPEAKER_MAP.get(language_code, DEFAULT_SPEAKER)
99
+
100
+ logger.info(
101
+ f"Starting Sarvam TTS | detected_language={detected_language} | "
102
+ f"language_code={language_code} | speaker={speaker} | "
103
+ f"char_count={len(text)}"
104
+ )
105
+
106
+ try:
107
+ payload = {
108
+ "inputs": [text],
109
+ "target_language_code": language_code,
110
+ "speaker": settings.sarvam_tts_speaker,
111
+ "model": settings.sarvam_tts_model,
112
+ "speech_sample_rate": 24000,
113
+ "pace": 1.0,
114
+ "temperature": 0.6,
115
+ }
116
+ headers = {
117
+ "api-subscription-key": settings.sarvam_api_key,
118
+ "Content-Type": "application/json",
119
+ }
120
+
121
+ logger.debug("Sending text to Sarvam AI Bulbul v3 TTS...")
122
+
123
+ async with httpx.AsyncClient(timeout=60.0) as client:
124
+ response = await client.post(
125
+ SARVAM_TTS_URL,
126
+ json = payload,
127
+ headers = headers,
128
+ )
129
+
130
+ # ── Handle API errors ─────────────────────────────────────────────
131
+ if response.status_code != 200:
132
+ error_body = response.text
133
+ logger.error(
134
+ f"Sarvam TTS API error | status={response.status_code} | "
135
+ f"body={error_body[:300]}"
136
+ )
137
+ raise RuntimeError(
138
+ f"Sarvam TTS API returned HTTP {response.status_code}: {error_body[:200]}"
139
+ )
140
+
141
+ result = response.json()
142
+ logger.debug(f"Sarvam TTS raw response keys: {list(result.keys())}")
143
+
144
+ # ── Extract base64 audio from response ────────────────────────────
145
+ # Sarvam returns: {"audios": ["<base64_wav_string>", ...]}
146
+ audios = result.get("audios", [])
147
+ if not audios or not audios[0]:
148
+ logger.error("Sarvam TTS returned empty audios list.")
149
+ raise RuntimeError("Sarvam TTS returned empty audio. Please retry.")
150
+
151
+ audio_b64: str = audios[0] # Already base64 encoded by Sarvam
152
+
153
+ # ── Decode to raw bytes for size logging ──────────────────────────
154
+ audio_bytes = base64.b64decode(audio_b64)
155
+
156
+ logger.info(
157
+ f"Sarvam TTS successful | audio_size={len(audio_bytes)} bytes | "
158
+ f"language={language_code} | speaker={speaker}"
159
+ )
160
+
161
+ # Return base64 or raw bytes based on caller preference
162
+ audio_output = audio_b64 if encode_base64 else audio_bytes
163
+
164
+ return {
165
+ "audio": audio_output,
166
+ "voice_model": SARVAM_TTS_MODEL,
167
+ "language": language_code,
168
+ "speaker": speaker,
169
+ "character_count": len(text),
170
+ }
171
+
172
+ except (ValueError, RuntimeError):
173
+ raise
174
+ except httpx.TimeoutException as e:
175
+ logger.error(f"Sarvam TTS request timed out: {str(e)}")
176
+ raise RuntimeError("Sarvam TTS request timed out. Please try again.") from e
177
+ except Exception as e:
178
+ logger.error(
179
+ f"Unexpected error during Sarvam TTS: {str(e)}", exc_info=True
180
+ )
181
+ raise RuntimeError(f"Speech synthesis failed: {str(e)}") from e
services/vector_store.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ services/vector_store.py
3
+ -------------------------
4
+ Two-path RAG architecture:
5
+
6
+ PATH A — Account queries (balance, SIP, transactions):
7
+ PAN/ID exact lookup from investors.json → instant (~0ms)
8
+
9
+ PATH B — Knowledge queries (KYC rules, SEBI norms, fund info):
10
+ TF-IDF keyword search over knowledge_base.json → ~5ms (in-process, no API)
11
+
12
+ Why TF-IDF instead of embeddings?
13
+ - Groq has NO embeddings API (404)
14
+ - sentence-transformers = 80MB download, 28s load
15
+ - For 10 policy docs, TF-IDF is fast, accurate, and zero-dependency
16
+ - scikit-learn is already a common Python package
17
+ - Works offline, no API key, no rate limits
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import logging
23
+ import re
24
+ from pathlib import Path
25
+ from typing import Optional
26
+
27
+ logger = logging.getLogger(__name__)
28
+ DATA_PATH = Path(__file__).parent.parent / "data" / "investors.json"
29
+ KB_PATH = Path(__file__).parent.parent / "data" / "knowledge_base.json"
30
+
31
+ try:
32
+ import chromadb
33
+ CHROMA_OK = True
34
+ except ImportError:
35
+ CHROMA_OK = False
36
+
37
+ try:
38
+ from sklearn.feature_extraction.text import TfidfVectorizer
39
+ from sklearn.metrics.pairwise import cosine_similarity
40
+ import numpy as np
41
+ SKLEARN_OK = True
42
+ except ImportError:
43
+ SKLEARN_OK = False
44
+ logger.warning("scikit-learn not installed. pip install scikit-learn")
45
+
46
+ # ── Singleton ─────────────────────────────────────────────────────────────────
47
+ _store: Optional["VectorStore"] = None
48
+
49
+ def get_vector_store() -> "VectorStore":
50
+ global _store
51
+ if _store is None:
52
+ _store = VectorStore()
53
+ return _store
54
+
55
+
56
+ class VectorStore:
57
+ def __init__(self) -> None:
58
+ self._investors: list[dict] = []
59
+ self._kb_docs: list[dict] = []
60
+ self._tfidf_matrix = None
61
+ self._tfidf_vectorizer = None
62
+
63
+ self._load_investors()
64
+ self._load_knowledge_base()
65
+ if SKLEARN_OK and self._kb_docs:
66
+ self._build_tfidf_index()
67
+
68
+ # ── Loaders ───────────────────────────────────────────────────────────────
69
+ def _load_investors(self) -> None:
70
+ if not DATA_PATH.exists():
71
+ logger.warning("investors.json not found. Run: python setup_data.py")
72
+ return
73
+ with open(DATA_PATH) as f:
74
+ self._investors = json.load(f)
75
+ logger.info(f"Loaded {len(self._investors)} investor records (PATH A — exact lookup)")
76
+
77
+ def _load_knowledge_base(self) -> None:
78
+ if not KB_PATH.exists():
79
+ logger.info("knowledge_base.json not found — PATH B disabled")
80
+ return
81
+ with open(KB_PATH) as f:
82
+ self._kb_docs = json.load(f)
83
+ logger.info(f"Loaded {len(self._kb_docs)} KB documents (PATH B — TF-IDF search)")
84
+
85
+ # ── TF-IDF index (built in-memory at startup, takes ~10ms) ───────────────
86
+ def _build_tfidf_index(self) -> None:
87
+ try:
88
+ corpus = [doc["content"] for doc in self._kb_docs]
89
+ self._tfidf_vectorizer = TfidfVectorizer(
90
+ stop_words = "english",
91
+ ngram_range = (1, 2), # unigrams + bigrams
92
+ max_features = 5000,
93
+ )
94
+ self._tfidf_matrix = self._tfidf_vectorizer.fit_transform(corpus)
95
+ logger.info(f"TF-IDF index built | {len(corpus)} docs | "
96
+ f"{self._tfidf_matrix.shape[1]} features | ~0ms query time")
97
+ except Exception as e:
98
+ logger.warning(f"TF-IDF index failed: {e}")
99
+ self._tfidf_matrix = None
100
+
101
+ # ═════════════════════════════════════════════════════════════════════════
102
+ # PATH A — Investor exact lookup (instant)
103
+ # ═════════════════════════════════════════════════════════════════════════
104
+ def get_investor(
105
+ self,
106
+ pan: Optional[str] = None,
107
+ investor_id: Optional[str] = None,
108
+ query: str = "",
109
+ ) -> Optional[dict]:
110
+ """Exact match only — never guesses. Returns None if no identifier."""
111
+ if not self._investors:
112
+ return None
113
+
114
+ if pan:
115
+ for inv in self._investors:
116
+ if inv["pan"] == pan.upper().strip():
117
+ logger.info(f"PATH A: PAN match → {inv['name']}")
118
+ return inv
119
+
120
+ if investor_id:
121
+ for inv in self._investors:
122
+ if inv["investor_id"] == investor_id.upper().strip():
123
+ logger.info(f"PATH A: ID match → {inv['name']}")
124
+ return inv
125
+
126
+ if query:
127
+ q = query.upper()
128
+ for inv in self._investors:
129
+ if inv["pan"] in q or inv["investor_id"] in q:
130
+ logger.info(f"PATH A: keyword match → {inv['name']}")
131
+ return inv
132
+
133
+ return None
134
+
135
+ # ═════════════════════════════════════════════════════════════════════════
136
+ # PATH B — Knowledge base TF-IDF search (~5ms, in-process)
137
+ # ═════════════════════════════════════════════════════════════════════════
138
+ async def search_knowledge(self, query: str, top_k: int = 2) -> str:
139
+ """
140
+ TF-IDF cosine similarity search over knowledge base.
141
+ No API call, no model loading — runs in-process in ~5ms.
142
+ """
143
+ if not SKLEARN_OK or self._tfidf_matrix is None or not query:
144
+ return self._keyword_fallback(query, top_k)
145
+
146
+ try:
147
+ q_vec = self._tfidf_vectorizer.transform([query])
148
+ scores = cosine_similarity(q_vec, self._tfidf_matrix)[0]
149
+ top_idx = scores.argsort()[::-1][:top_k]
150
+
151
+ chunks = []
152
+ for idx in top_idx:
153
+ if scores[idx] > 0.05: # Minimum relevance threshold
154
+ doc = self._kb_docs[idx]
155
+ chunks.append(f"[{doc['title']}]\n{doc['content']}")
156
+ logger.info(f"PATH B: '{doc['title']}' score={scores[idx]:.3f}")
157
+
158
+ if chunks:
159
+ return "\n\n".join(chunks)
160
+
161
+ except Exception as e:
162
+ logger.warning(f"TF-IDF search failed: {e}")
163
+
164
+ return self._keyword_fallback(query, top_k)
165
+
166
+ def _keyword_fallback(self, query: str, top_k: int) -> str:
167
+ """Simple keyword overlap fallback if sklearn unavailable."""
168
+ if not self._kb_docs or not query:
169
+ return ""
170
+ query_words = set(re.findall(r'\w+', query.lower()))
171
+ scored = []
172
+ for doc in self._kb_docs:
173
+ doc_words = set(re.findall(r'\w+', doc["content"].lower()))
174
+ score = len(query_words & doc_words)
175
+ if score > 0:
176
+ scored.append((score, doc))
177
+ scored.sort(reverse=True)
178
+ chunks = [f"[{d['title']}]\n{d['content']}" for _, d in scored[:top_k]]
179
+ return "\n\n".join(chunks)
180
+
181
+ def get_all_investors(self) -> list[dict]:
182
+ return self._investors
setup_data.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ setup_data.py
3
+ --------------
4
+ Generates synthetic investor data and knowledge base.
5
+ Auto-runs on first startup if data files don't exist.
6
+ Can also be run manually: python setup_data.py
7
+ """
8
+ import sys, json
9
+ from pathlib import Path
10
+ sys.path.insert(0, str(Path(__file__).parent))
11
+
12
+ def run():
13
+ data_dir = Path("data")
14
+ data_dir.mkdir(exist_ok=True)
15
+
16
+ investors_path = data_dir / "investors.json"
17
+ kb_path = data_dir / "knowledge_base.json"
18
+
19
+ # ── Investor data ──────────────────────────────────────────────────────
20
+ if not investors_path.exists():
21
+ print("[setup] Generating synthetic investor records...")
22
+ from data.synthetic_investors import generate_investors
23
+ investors = generate_investors(20)
24
+ with open(investors_path, "w") as f:
25
+ json.dump(investors, f, indent=2)
26
+ print(f"[setup] ✅ {len(investors)} investor records → {investors_path}")
27
+ else:
28
+ print(f"[setup] ✅ investors.json already exists — skipping")
29
+
30
+ # ── Knowledge base ─────────────────────────────────────────────────────
31
+ if not kb_path.exists():
32
+ print("[setup] Generating CAMS knowledge base...")
33
+ from data.knowledge_base_generator import KNOWLEDGE_BASE
34
+ with open(kb_path, "w") as f:
35
+ json.dump(KNOWLEDGE_BASE, f, indent=2)
36
+ print(f"[setup] ✅ {len(KNOWLEDGE_BASE)} KB documents → {kb_path}")
37
+ else:
38
+ print(f"[setup] ✅ knowledge_base.json already exists — skipping")
39
+
40
+ print("[setup] Data ready ✅")
41
+
42
+ if __name__ == "__main__":
43
+ run()