File size: 14,238 Bytes
91651eb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 | """
main.py β CAMS Voice & Chat Assistant v3.1
-------------------------------------------
Latency-optimized pipeline. Single LLM call per request.
CHAT timeline:
Retrieval (PATH A exact): ~0ms
LLM (single call): ~0.4s
TTS + Action (parallel): ~1.0s
Total: ~1.5s β
VOICE timeline:
STT: ~1.5s
Retrieval (PATH A): ~0ms
LLM (single call): ~0.4s
TTS + Action (parallel): ~1.0s
Total: ~3.0s β
Key fixes vs previous version:
- Removed double LLM call (was calling analyse_message twice for PATH B)
- KB context retrieved and injected BEFORE single LLM call
- TF-IDF removed β simple keyword search for KB is fast enough
- Persistent HTTP client reused for all Sarvam calls
"""
from __future__ import annotations
import asyncio
import time
import uuid
import logging
from typing import Optional
from contextlib import asynccontextmanager
import httpx
import uvicorn
from fastapi import FastAPI, UploadFile, File, Form, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from config import settings
from schemas import ChatRequest, AssistantResponse
from services.groq_llm import analyse_message
from services.data_retriever import get_investor_context
from services.vector_store import get_vector_store
from action_engine import trigger_action
logging.basicConfig(
level = getattr(logging, settings.log_level, logging.INFO),
format = "%(asctime)s | %(levelname)-8s | %(name)s | %(message)s",
datefmt = "%Y-%m-%d %H:%M:%S",
)
logger = logging.getLogger(__name__)
# ββ Persistent HTTP client ββββββββββββββββββββββββββββββββββββββββββββββββββββ
_http_client: Optional[httpx.AsyncClient] = None
def get_http_client() -> httpx.AsyncClient:
global _http_client
if _http_client is None or _http_client.is_closed:
_http_client = httpx.AsyncClient(
timeout = httpx.Timeout(connect=5.0, read=30.0, write=10.0, pool=5.0),
limits = httpx.Limits(max_connections=20, max_keepalive_connections=10),
)
return _http_client
@asynccontextmanager
async def lifespan(app: FastAPI):
# Auto-generate data files if missing (needed on HF Spaces fresh container)
import importlib.util, os
if not os.path.exists("data/investors.json") or not os.path.exists("data/knowledge_base.json"):
logger.info("Data files missing β running setup_data...")
import setup_data
setup_data.run()
get_http_client()
get_vector_store()
logger.info("Startup complete β HTTP client and vector store ready.")
yield
if _http_client and not _http_client.is_closed:
await _http_client.aclose()
app = FastAPI(title="CAMS Assistant", version="3.1.0", lifespan=lifespan)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], allow_credentials=True,
allow_methods=["*"], allow_headers=["*"],
)
@app.get("/health")
async def health():
return {"status": "ok"}
# ββ STT βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async def _stt(audio_bytes: bytes, mime_type: str) -> dict:
from services.sarvam_stt import SARVAM_STT_URL, SARVAM_LANG_MAP
filename = "audio.wav" if "wav" in mime_type else "audio.webm"
r = await get_http_client().post(
SARVAM_STT_URL,
files = {"file": (filename, audio_bytes, mime_type)},
data = {"model": settings.sarvam_stt_model, "language_code": "unknown"},
headers = {"api-subscription-key": settings.sarvam_api_key},
)
if r.status_code != 200:
raise RuntimeError(f"STT error {r.status_code}: {r.text[:200]}")
data = r.json()
transcript = (data.get("transcript") or "").strip()
if not transcript:
raise RuntimeError("No speech detected β please speak clearly.")
lang = SARVAM_LANG_MAP.get((data.get("language_code") or "en").lower(), "en")
return {"transcript": transcript, "detected_language": lang}
# ββ TTS βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async def _tts(text: str, language: str) -> dict:
from services.sarvam_tts import SARVAM_TTS_URL, LANGUAGE_MAP
r = await get_http_client().post(
SARVAM_TTS_URL,
json = {
"inputs": [text[:400]], # Cap at 400 chars β faster TTS
"target_language_code": LANGUAGE_MAP.get(language, "en-IN"),
"speaker": settings.sarvam_tts_speaker,
"model": settings.sarvam_tts_model,
"speech_sample_rate": 8000, # 8kHz β 3x smaller payload
"pace": 1.1,
},
headers = {"api-subscription-key": settings.sarvam_api_key,
"Content-Type": "application/json"},
)
if r.status_code != 200:
logger.warning(f"TTS error {r.status_code}")
return {"audio": None}
audios = r.json().get("audios") or []
return {"audio": audios[0] if audios else None}
# ββ Context retrieval (single path β no double LLM call) βββββββββββββββββββββ
async def _get_context(
message: str,
investor_id: Optional[str] = None,
conversation_history: Optional[list] = None,
) -> tuple[Optional[dict], str]:
"""
Resolve which investor to fetch data for, in priority order:
1. PAN explicitly in the CURRENT message β always wins (user switching accounts)
2. investor_id passed from frontend session (already verified earlier)
3. PAN found in conversation history (user gave it a few turns ago)
4. Knowledge base search (policy/FAQ queries)
Priority 1 > 2 ensures that when a user types a NEW PAN,
we switch to that investor immediately instead of using the old session PAN.
"""
import re
PAN_RE = re.compile(r"\b[A-Z]{5}[0-9]{4}[A-Z]\b", re.IGNORECASE)
vs = get_vector_store()
# ββ 1. PAN in CURRENT message (highest priority) ββββββββββββββββββββββ
current_pan = None
m = PAN_RE.search(message.upper())
if m:
current_pan = m.group(0)
logger.info(f"PAN in current message: {current_pan}")
# ββ 2. Session investor_id (only if no new PAN in current message) ββββ
resolved_id = current_pan or investor_id or None
# ββ 3. Scan history (only if still nothing resolved) βββββββββββββββββ
if not resolved_id and conversation_history:
for turn in reversed(conversation_history):
text = turn.get("content", "") or ""
m2 = PAN_RE.search(text.upper())
if m2:
resolved_id = m2.group(0)
logger.info(f"PAN from history: {resolved_id}")
break
# ββ PATH A: exact investor lookup βββββββββββββββββββββββββββββββββββββ
if resolved_id:
investor, account_ctx = await get_investor_context(
user_message = message,
extracted_entities = {"investor_id": resolved_id},
)
if account_ctx:
return investor, account_ctx
# ββ PATH B: knowledge base ββββββββββββββββββββββββββββββββββββββββββββ
kb_ctx = await vs.search_knowledge(message, top_k=2)
if kb_ctx:
return None, kb_ctx
return None, ""
# ββ CHAT endpoint βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.post("/api/chat", response_model=AssistantResponse)
async def process_chat(request: ChatRequest) -> AssistantResponse:
session_id = request.session_id or str(uuid.uuid4())
t0 = time.perf_counter()
try:
# ββ Retrieval + LLM + TTS timeline:
# [retrieval ~0ms] β [LLM ~0.4s] β [TTS β₯ Action ~1.0s] = ~1.5s total
t1 = time.perf_counter()
investor, context = await _get_context(
message = request.message,
investor_id = request.investor_id,
conversation_history = request.conversation_history or [],
)
logger.info(f"[CHAT] retrieval={time.perf_counter()-t1:.3f}s ctx={'account' if investor else ('kb' if context else 'none')}")
t2 = time.perf_counter()
analysis = await analyse_message(
user_message = request.message,
language = request.language or "en",
investor_id = request.investor_id or None,
conversation_history = request.conversation_history or [],
investor_context = context or None,
)
logger.info(f"[CHAT] llm={time.perf_counter()-t2:.2f}s intent={analysis.intent}")
t3 = time.perf_counter()
action_result, tts_result = await asyncio.gather(
trigger_action(analysis),
_tts(analysis.response_text, request.language or "en"),
)
logger.info(f"[CHAT] tts+action={time.perf_counter()-t3:.2f}s | TOTAL={time.perf_counter()-t0:.2f}s")
return AssistantResponse(
session_id = session_id,
transcribed_text = None,
detected_language = request.language or "en",
intent = analysis.intent,
sentiment = analysis.sentiment,
entities = analysis.entities,
response_text = analysis.response_text,
confidence = analysis.confidence,
requires_escalation = analysis.requires_escalation,
action_result = action_result,
audio_url = tts_result.get("audio"),
)
except HTTPException:
raise
except Exception as e:
logger.error(f"[CHAT] {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
# ββ VOICE endpoint ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.post("/api/voice", response_model=AssistantResponse)
async def process_voice(
audio_file: UploadFile = File(...),
session_id: str = Form(default=""),
investor_id: str = Form(default=""),
) -> AssistantResponse:
if not session_id:
session_id = str(uuid.uuid4())
t0 = time.perf_counter()
supported = {
"audio/wav","audio/wave","audio/x-wav","audio/mpeg",
"audio/mp3","audio/webm","audio/ogg","application/octet-stream",
}
if audio_file.content_type not in supported:
raise HTTPException(400, f"Unsupported: {audio_file.content_type}")
try:
audio_bytes = await audio_file.read()
if not audio_bytes:
raise HTTPException(400, "Empty audio file.")
# STT (unavoidable ~1.5s)
t1 = time.perf_counter()
stt = await _stt(audio_bytes, audio_file.content_type or "audio/wav")
transcript, lang = stt["transcript"], stt["detected_language"]
logger.info(f"[VOICE] stt={time.perf_counter()-t1:.2f}s lang={lang} '{transcript[:50]}'")
# Retrieval (instant for PATH A, ~5ms for PATH B)
t2 = time.perf_counter()
investor, context = await _get_context(
message = transcript,
investor_id = investor_id or None,
conversation_history = [], # Voice history tracked via sessionInvestorId on frontend
)
logger.info(f"[VOICE] retrieval={time.perf_counter()-t2:.3f}s ctx={'account' if investor else ('kb' if context else 'none')}")
# Single LLM call with full context
t3 = time.perf_counter()
analysis = await analyse_message(
user_message = transcript,
language = lang,
investor_id = investor_id or None,
conversation_history = [],
investor_context = context or None,
)
logger.info(f"[VOICE] llm={time.perf_counter()-t3:.2f}s intent={analysis.intent}")
# TTS + Action in parallel
t4 = time.perf_counter()
action_result, tts_result = await asyncio.gather(
trigger_action(analysis),
_tts(analysis.response_text, lang),
)
logger.info(f"[VOICE] tts+action={time.perf_counter()-t4:.2f}s | TOTAL={time.perf_counter()-t0:.2f}s β
")
return AssistantResponse(
session_id = session_id,
transcribed_text = transcript,
detected_language = lang,
intent = analysis.intent,
sentiment = analysis.sentiment,
entities = analysis.entities,
response_text = analysis.response_text,
confidence = analysis.confidence,
requires_escalation = analysis.requires_escalation,
action_result = action_result,
audio_url = tts_result.get("audio"),
)
except HTTPException:
raise
except Exception as e:
logger.error(f"[VOICE] {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
import os
port = int(os.environ.get("PORT", settings.app_port))
uvicorn.run(
"main:app",
host = settings.app_host,
port = port,
reload = False,
log_level = "warning",
workers = 1,
)
|