Charan S commited on
Commit ·
64fb1e7
0
Parent(s):
Initial Commit - Wavvy Voice AI CCaaS Platform
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .env.exampleAdded+30
- agents/__init__.pyAdded
- agents/coaching_agent.pyAdded+129
- agents/companion_agent.pyAdded+484
- agents/qa_agent.pyAdded+263
- agents/scheduling_agent.pyAdded+690
- agents/voice_agent.pyAdded+6
- alembic.iniAdded+38
- coaching/__init__.pyAdded
- coaching/coaching_manager.pyAdded+145
- config.pyAdded+54
- config_loader.pyAdded+51
- constants/__init__.pyAdded
- constants/transaction_status.pyAdded+34
- database.pyAdded+38
- events/__init__.pyAdded
- events/emitter.pyAdded+31
- guardrails/__init__.pyAdded+55
- guardrails/auth_gate.pyAdded+39
- guardrails/rate_limiter.pyAdded+58
- guardrails/scope.pyAdded+40
- guardrails/tool_permissions.pyAdded+65
- guardrails/validator.pyAdded+65
- k8s/worker-deployment.yamlAdded+152
- knowledge/__init__.pyAdded
- knowledge/document_parser.pyAdded+271
- knowledge/embeddings.pyAdded+44
- knowledge/kb_manager.pyAdded+596
- knowledge/seed.pyAdded+77
- knowledge/seed_docs/_archive/wavvy_combined.mdAdded+418
- knowledge/seed_docs/fin/account_security.mdAdded+130
- knowledge/seed_docs/fin/dispute_resolution.mdAdded+99
- knowledge/seed_docs/fin/fin_overview.mdAdded+74
- knowledge/seed_docs/fin/fraud_escalation.mdAdded+81
- knowledge/seed_docs/fin/kyc_verification.mdAdded+96
- knowledge/seed_docs/fin/payment_failure_sop.mdAdded+102
- knowledge/seed_docs/fin/refund_policy.mdAdded+78
- knowledge/seed_docs/fin/transaction_status_guide.mdAdded+189
- main.pyAdded+161
- migrations/__init__.pyAdded
- migrations/env.pyAdded+53
- migrations/script.py.makoAdded+25
- migrations/versions/001_initial.pyAdded+139
- migrations/versions/002_leads_appointments.pyAdded+53
- migrations/versions/003_appointment_confirmed_time.pyAdded+26
- migrations/versions/004_scheduling_upgrade.pyAdded+72
- migrations/versions/005_call_feedback.pyAdded+41
- migrations/versions/006_agent_password.pyAdded+27
- migrations/versions/007_tenant_config.pyAdded+52
- migrations/versions/008_action_audit_logs.pyAdded+43
123456789101112131415161718192021222324252627282930# LLM — OpenAI (required)OPENAI_API_KEY=sk-...
# Voice pipeline — LiveKit Cloud (required)# Free tier: 5,000 WebRTC min/mo — https://cloud.livekit.ioLIVEKIT_URL=wss://your-project.livekit.cloudLIVEKIT_API_KEY=APIxxxxxxxxLIVEKIT_API_SECRET=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# Voice pipeline — Deepgram STT (required)# Free tier: 12,000 min/mo — https://deepgram.comDEEPGRAM_API_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# TTS — ElevenLabs (optional — falls back to local Kokoro if not set)# Free tier: 10,000 chars/mo — https://elevenlabs.io# Voice: ZmbMESk7pXyovUlnOp08 (default) — override with ELEVENLABS_VOICE_ID# Model: eleven_turbo_v2_5 (default) — override with ELEVENLABS_MODELELEVENLABS_API_KEY=sk_...
# Database + storageDATABASE_URL=postgresql+asyncpg://wavvy:wavvy@localhost:5433/wavvyCHROMA_PERSIST_DIR=./chroma_db
# Frontend URLs (for CORS — update for production)FRONTEND_LANDING_URL=http://localhost:5173FRONTEND_AGENT_URL=http://localhost:5174FRONTEND_SUPERVISOR_URL=http://localhost:5175
ENVIRONMENT=developmentSECRET_KEY=change-in-production123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129import jsonimport logging
logger = logging.getLogger(__name__)
_client = None
_DEFAULT_COACHING_PROMPT = """You are an AI coaching specialist.You will receive a list of completed call evaluations for a single agent.Generate a personalized coaching pack based on their real performance data.
Be specific — reference actual patterns across the calls (scores, common violations, resolution trends).Be constructive and actionable. Never generic.
Return ONLY valid JSON in this exact schema:{ "overall_trend": "improving" | "declining" | "stable", "strengths": ["specific strength 1", "specific strength 2", "specific strength 3"], "improvements": ["specific area to improve 1", "specific area to improve 2"], "action_items": [ {"priority": "high" | "medium" | "low", "action": "specific actionable step", "metric": "what to measure"}, {"priority": "high" | "medium" | "low", "action": "specific actionable step", "metric": "what to measure"} ], "score_summary": { "avg_overall": 75, "avg_guardrail": 80, "avg_resolution": 70, "avg_containment": 65, "avg_satisfaction": 0.72, "pass_rate": 0.67, "calls_analyzed": 3 }, "coaching_note": "One paragraph personalized coaching message for the agent."}
Temperature 0.4. Focus on actionable improvements backed by data from the evaluations provided."""
def _get_coaching_prompt() -> str: try: from config_loader import get_config p = get_config().coaching_prompt if p: return p except Exception: pass return _DEFAULT_COACHING_PROMPT
def init_coaching_agent(openai_client): global _client _client = openai_client
async def generate_coaching_pack(agent_name: str, eval_records: list[dict]) -> dict: """ Generate a coaching pack from >= 3 eval records for an agent. Returns the parsed coaching pack dict. """ if not _client: logger.warning("Coaching agent not initialized — returning default") return _default_pack(agent_name, eval_records)
eval_summary = json.dumps(eval_records, indent=2, default=str) user_content = ( f"Agent: {agent_name}\n" f"Number of calls evaluated: {len(eval_records)}\n\n" f"Evaluation records:\n{eval_summary}" )
try: response = await _client.chat.completions.create( model="gpt-4o-mini", temperature=0.4, max_tokens=900, response_format={"type": "json_object"}, messages=[ {"role": "system", "content": _get_coaching_prompt()}, {"role": "user", "content": user_content}, ], ) pack = json.loads(response.choices[0].message.content) return _normalize_pack(pack, eval_records) except Exception as e: logger.error(f"Coaching agent error: {e}") return _default_pack(agent_name, eval_records)
def _normalize_pack(pack: dict, eval_records: list[dict]) -> dict: n = len(eval_records) scores = [r.get("overall_score", 0) for r in eval_records] pass_count = sum(1 for r in eval_records if r.get("pass_fail") == "PASS")
# Ensure score_summary is populated with real averages def avg(key): vals = [r.get(key, 0) or 0 for r in eval_records] return round(sum(vals) / n, 1) if n else 0
pack["score_summary"] = { "avg_overall": round(sum(scores) / n, 1) if n else 0, "avg_guardrail": avg("guardrail_adherence"), "avg_resolution": avg("resolution_rate"), "avg_containment": avg("containment"), "avg_satisfaction": round(avg("caller_satisfaction"), 2), "pass_rate": round(pass_count / n, 2) if n else 0, "calls_analyzed": n, }
# Ensure required list fields exist pack.setdefault("strengths", []) pack.setdefault("improvements", []) pack.setdefault("action_items", []) pack.setdefault("overall_trend", "stable") pack.setdefault("coaching_note", "Keep working on consistency across all rubric criteria.")
return pack
def _default_pack(agent_name: str, eval_records: list[dict]) -> dict: return _normalize_pack({ "overall_trend": "stable", "strengths": ["Maintained professional tone", "Followed escalation protocol"], "improvements": ["Improve resolution rate", "Reduce average handle time"], "action_items": [ {"priority": "high", "action": "Practice refund resolution scripts", "metric": "resolution_rate >= 80"}, {"priority": "medium", "action": "Review KB articles before shifts", "metric": "kb_hit rate"}, ], "coaching_note": f"{agent_name} shows consistent effort. Focus on boosting resolution rate.", }, eval_records)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484"""Companion AI — real-time support for human agents during escalated calls.
run_mid_call_companion() returns the full elite companion update including: - suggested_actions (executable HITL operations with reason/impact/confidence) - sentiment_trend (Python-calculated — not LLM) - resolution_probability, risk_flags, acw_preview - checklist, nudge, next_action, customer_mood, kb_suggestion, insight"""import jsonimport loggingfrom typing import Optionalfrom openai import AsyncOpenAI
logger = logging.getLogger(__name__)
_client: Optional[AsyncOpenAI] = None
def init_companion_agent(openai_client: AsyncOpenAI) -> None: global _client _client = openai_client
def _get_mid_call_prompt() -> str: try: from config_loader import get_config p = get_config().companion_mid_call_prompt if p: return p except Exception: pass return _DEFAULT_MID_CALL_PROMPT
def _get_acw_prompt() -> str: try: from config_loader import get_config p = get_config().companion_acw_prompt if p: return p except Exception: pass return _DEFAULT_ACW_PROMPT
_DEFAULT_MID_CALL_PROMPT = """You are an Operational Companion AI helping a specialist resolve a live escalated fintech support call.
WORKFLOW: The specialist IS the final resolution point. They resolve every issue directly.There is NO fraud team, KYC team, compliance team, or any other internal team to escalate to.NEVER suggest escalating to another team or department. NEVER suggest escalate_fraud_team.The specialist sees the customer's full financial context (transactions, holds, refunds, disputes).
YOUR JOB: Analyse the transcript + financial context, identify the specific problematictransaction/hold/case, and suggest the exact action from the registry to fix it right now.
Analyse the full transcript and context, then return ONLY this JSON (no other text):
{ "checklist": [ {"step": "Greet customer and acknowledge the AI handoff", "done": false}, {"step": "Confirm the specific issue (transaction / hold / account)", "done": false}, {"step": "Review the financial context and identify the root cause", "done": false}, {"step": "Approve and execute the fix using the suggested action", "done": false}, {"step": "Confirm resolution with the customer and close the call", "done": false} ], "nudge": "Exactly what the specialist should say RIGHT NOW (e.g. 'I can see transaction TXN-XXXX for ₹X is showing as failed — let me process a refund immediately.'), or null", "next_action": "One-line instruction referencing the specific transaction or issue (e.g. 'Issue refund for TXN-7731 — amount ₹5,400 — by approving the suggested action')", "customer_mood": "calm|frustrated|curious|satisfied|angry", "kb_suggestion": {"content": "policy excerpt relevant to this issue", "source": "Document name"} or null, "insight": "Key observation grounded in the financial context (e.g. 'TXN-7731 failed 3 days ago and is still pending — likely due to the active fraud hold on the account'), or null", "suggested_actions": [ { "id": "action_name_from_registry", "label": "Human-readable label e.g. 'Refund ₹5,400 for TXN-7731'", "description": "One line: exactly what this does and why it resolves the customer's issue", "reason": "Grounded reason citing the specific txn_number/hold/status from the context", "impact": "What changes immediately: account unlocked, refund initiated, hold lifted, etc.", "confidence": 0.90, "priority": "high|medium|low", "risk": "low|medium|high", "requires_approval": true, "payload": {} } ], "resolution_probability": 0.75, "risk_flags": [], "acw_preview": { "summary": "1-2 sentence summary: issue, root cause identified, action taken", "likely_resolution": "resolved|unresolved" }}
FINANCIAL CONTEXT SCHEMA:Use this to identify the specific problem and ground every suggested_action:- transactions: [{txn_number, merchant, amount, currency, txn_type, status, txn_date}] Problematic statuses: failed, pending, processing, flagged, kyc_hold, compliance_hold, fraud_reported, fraud_confirmed- account_holds: [{hold_type, reason, placed_at}] hold_type: fraud|regulatory|manual|kyc- open_refunds: [{rfn_number, merchant, amount, status, initiated_at}]- open_disputes: [{dsp_number, merchant, amount, reason, status, opened_at}]- active_fraud_cases: [{fraud_number, fraud_type, risk_level, hold_placed_at}]- account_status: active|locked|suspended|frozen- fraud_hold_active: true|false- kyc_status: pending|verified|rejected
TRANSACTION DIAGNOSIS: If a transaction has status=failed/flagged/fraud_reported AND the accounthas fraud_hold_active=True — the fix is BOTH remove_fraud_hold AND issue_refund (if the customerwas charged). If account_status=locked, also suggest unlock_account after the hold is cleared.
ACTION REGISTRY — only these exact id strings are valid: unlock_account — sets account_status=active; use after fraud hold is cleared remove_fraud_hold — clears fraud_hold_active; lifts all fraud-type account_holds mark_kyc_verified — sets kyc_status=verified; lifts kyc-type holds issue_refund — initiates refund for a failed/disputed txn; payload: {txn_number} reopen_dispute — opens a dispute for a completed txn; payload: {txn_number, reason} reset_2fa — resets two_fa_last_reset_at (for locked-out customers) freeze_account — sets account_status=frozen (use only for confirmed fraud/safety)
RULES FOR suggested_actions:- ONLY suggest ids from the registry above — no other values are valid- NEVER suggest escalate_fraud_team or any variant — it does not exist in this workflow- Always reference the exact txn_number, rfn_number, or dsp_number from the context in payload and reason- issue_refund: only valid if transaction status is failed/flagged (not already refund_initiated)- remove_fraud_hold: only if fraud_hold_active=True OR account_holds has a fraud-type hold- mark_kyc_verified: only if kyc_status is pending/rejected AND documents confirmed on call- unlock_account: only after remove_fraud_hold is done, OR if account is locked without a fraud hold- Return [] if the specialist has already resolved the issue or no action is needed yet- Max 2 suggested_actions per response; list most urgent first- NEVER re-suggest any action that appears in the completed_actions list
RULES FOR risk_flags (return any that apply): "repeat_complaint" — same issue mentioned in a previous call "long_call" — many turns without resolution "compliance_mention" — customer mentioned legal/complaint/regulatory/ombudsman "unresolved_ai_attempt" — AI tried and failed to resolve this before escalation "active_hold_detected" — account_hold that has not been addressed yet "fraud_case_open" — active fraud case under review
Infer checklist done-state from what is visible in the transcript.resolution_probability: 0.0 = still diagnosing, 1.0 = fully resolved."""
_DEFAULT_ACW_PROMPT = """The call has ended. Generate the After Call Work summary.Return ONLY this JSON (no other text):
{ "summary": "2-3 sentence summary: what the customer asked, what was covered, outcome", "resolution": "resolved|escalated|unresolved", "action_items": ["list of follow-up actions if any"], "crm_fields": { "notes": "brief note about the issue and next step" }, "coaching_note": "one sentence coaching note for the agent"}"""
# Mood rank for trend calculation — higher = better_MOOD_RANK = { "angry": 0, "frustrated": 1, "calm": 2, "curious": 3, "satisfied": 4,}
async def _fetch_kb_for_companion(query: str) -> Optional[dict]: """ChromaDB RRF search — top match only, score > 0.01.""" if not query: return None try: from knowledge.kb_manager import search_kb hits = await search_kb(query, n_results=1) if hits and hits[0].get("relevance", 0.0) > 0.01: return { "content": hits[0].get("content", ""), "source": hits[0].get("source", "KB"), } except Exception: pass return None
async def run_mid_call_companion( transcript: list[dict], customer: dict, handoff_bundle: Optional[dict] = None, workflow_type: Optional[str] = None, previous_mood: Optional[str] = None, completed_actions: Optional[set] = None,) -> dict: if not _client: return _default_mid_call_response()
messages = [{"role": "system", "content": _get_mid_call_prompt()}]
context_parts = []
# Workflow type — drives which actions companion may suggest if workflow_type: context_parts.append(f"WORKFLOW: {workflow_type}")
# Completed actions — companion must not re-suggest these if completed_actions: context_parts.append( f"COMPLETED ACTIONS THIS CALL (DO NOT suggest again): {', '.join(completed_actions)}" )
# Customer context from handoff bundle # All fintech data lives under handoff_bundle["lead"] (serialized by EscalationPacket.to_dict) if handoff_bundle: lead = handoff_bundle.get("lead", {}) or {}
name = lead.get("name") if name: context_parts.append(f"CUSTOMER: {name}")
account_type = lead.get("account_type") account_status = lead.get("account_status") kyc_status = lead.get("kyc_status") fraud_hold = lead.get("fraud_hold_active", False) if account_type: status_note = f" (status: {account_status})" if account_status and account_status != "active" else "" context_parts.append(f"Account type: {account_type}{status_note}") if kyc_status and kyc_status != "verified": context_parts.append(f"KYC status: {kyc_status}") if fraud_hold: context_parts.append("Fraud hold: ACTIVE")
intent = lead.get("intent") or handoff_bundle.get("intent") if intent: context_parts.append(f"Detected intent: {intent.replace('_', ' ')}") reason = handoff_bundle.get("reason") if reason: context_parts.append(f"Escalation reason: {reason}") cid = handoff_bundle.get("customer_id") if cid: context_parts.append(f"customer_id (for payload): {cid}")
# Financial context — grounded from normalized tables transactions = lead.get("transactions") or [] if transactions: txn_lines = [ f" {t.get('txn_number','?')}: {t.get('merchant','?')} " f"₹{t.get('amount','?')} {t.get('txn_type','?')} " f"status={t.get('status','?')} date={t.get('txn_date','?')}" for t in transactions[:5] ] context_parts.append("TRANSACTIONS:\n" + "\n".join(txn_lines))
holds = lead.get("account_holds") or [] if holds: hold_lines = [ f" {h.get('hold_type','?')}: {h.get('reason','no reason given')}" for h in holds ] context_parts.append("ACTIVE ACCOUNT HOLDS:\n" + "\n".join(hold_lines))
refunds = lead.get("open_refunds") or [] if refunds: ref_lines = [ f" {r.get('rfn_number','?')}: {r.get('merchant','?')} " f"₹{r.get('amount','?')} status={r.get('status','?')} " f"for txn={r.get('transaction_id','?')}" for r in refunds ] context_parts.append("IN-PROGRESS REFUNDS:\n" + "\n".join(ref_lines))
disputes = lead.get("open_disputes") or [] if disputes: dsp_lines = [ f" {d.get('dsp_number','?')}: {d.get('merchant','?')} " f"₹{d.get('amount','?')} reason={d.get('reason','?')} " f"status={d.get('status','?')} txn={d.get('transaction_id','?')}" for d in disputes ] context_parts.append("OPEN DISPUTES:\n" + "\n".join(dsp_lines))
fraud_cases = lead.get("active_fraud_cases") or [] if fraud_cases: fc_lines = [ f" {f.get('fraud_number','?')}: {f.get('fraud_type','?')} " f"risk={f.get('risk_level','?')} txn={f.get('transaction_id','?')}" for f in fraud_cases ] context_parts.append("ACTIVE FRAUD CASES:\n" + "\n".join(fc_lines))
if context_parts: messages.append({"role": "user", "content": "\n".join(context_parts)})
# Real KB search on most recent customer utterance last_customer_text = next( ( l.get("text") or l.get("content", "") for l in reversed(transcript) if l.get("speaker") in ("customer", "user") and (l.get("text") or l.get("content")) ), None, ) real_kb_hit = await _fetch_kb_for_companion(last_customer_text)
transcript_text = _format_transcript(transcript) kb_block = ( f"\n\nKB DOCUMENT (cite verbatim in kb_suggestion):\n" f"Source: {real_kb_hit['source']}\nContent: {real_kb_hit['content']}" if real_kb_hit else "\n\nKB DOCUMENT: No high-relevance match — set kb_suggestion to null." ) messages.append({ "role": "user", "content": f"TRANSCRIPT:\n{transcript_text}{kb_block}\n\nGenerate companion update now.", })
try: resp = await _client.chat.completions.create( model="gpt-4o-mini", messages=messages, temperature=0.3, max_tokens=700, response_format={"type": "json_object"}, ) raw = resp.choices[0].message.content or "{}" data = json.loads(raw) result = _normalize_mid_call(data) if real_kb_hit: result["kb_suggestion"] = real_kb_hit except Exception: result = _default_mid_call_response()
# Calculate sentiment_trend in Python (not LLM) — avoids prompt injection drift current_mood = result.get("customer_mood", "calm") result["sentiment_trend"] = _calc_sentiment_trend(current_mood, previous_mood)
return result
def _calc_sentiment_trend(current: str, previous: Optional[str]) -> str: if not previous or current == previous: return "stable" curr_rank = _MOOD_RANK.get(current, 2) prev_rank = _MOOD_RANK.get(previous, 2) if curr_rank > prev_rank: return "improving" if curr_rank < prev_rank: return "declining" return "stable"
async def run_acw_agent( transcript: list[dict], customer: dict, call_id: str,) -> dict: if not _client: return _default_acw_response()
messages = [{"role": "system", "content": _get_acw_prompt()}] messages.append({"role": "user", "content": f"Call ID: {call_id}"}) transcript_text = _format_transcript(transcript) messages.append({ "role": "user", "content": f"FULL TRANSCRIPT:\n{transcript_text}\n\nGenerate ACW summary now.", })
try: resp = await _client.chat.completions.create( model="gpt-4o-mini", messages=messages, temperature=0.3, max_tokens=500, response_format={"type": "json_object"}, ) raw = resp.choices[0].message.content or "{}" data = json.loads(raw) return _normalize_acw(data) except Exception: return _default_acw_response()
def _format_transcript(transcript: list[dict]) -> str: lines = [] for entry in transcript: speaker = entry.get("speaker", "unknown") text = entry.get("text", entry.get("content", "")) lines.append(f"[{speaker}]: {text}") return "\n".join(lines) if lines else "(empty transcript)"
def _normalize_mid_call(data: dict) -> dict: # Validate suggested_actions — remove entries with bad ids from orchestration.action_registry import ACTION_REGISTRY raw_actions = data.get("suggested_actions") or [] valid_actions = [] for a in raw_actions: if not isinstance(a, dict): continue if a.get("id") not in ACTION_REGISTRY: continue valid_actions.append({ "id": a.get("id"), "label": a.get("label", a.get("id", "").replace("_", " ").title()), "description": a.get("description", ""), "reason": a.get("reason", ""), "impact": a.get("impact", ""), "confidence": float(a.get("confidence", 0.7)), "priority": a.get("priority", "medium"), "risk": a.get("risk", "medium"), "requires_approval": True, "payload": a.get("payload") or {}, })
acw_raw = data.get("acw_preview") or {}
raw_qr = data.get("quick_replies") or [] quick_replies = [r for r in raw_qr if isinstance(r, str) and r.strip()][:3]
return { "checklist": data.get("checklist", _default_checklist()), "quick_replies": quick_replies, "nudge": data.get("nudge"), "next_action": data.get("next_action", "Listen and assist the customer"), "customer_mood": data.get("customer_mood", "calm"), "kb_suggestion": data.get("kb_suggestion"), "insight": data.get("insight"), "suggested_actions": valid_actions, "resolution_probability": float(data.get("resolution_probability", 0.5)), "risk_flags": [f for f in (data.get("risk_flags") or []) if isinstance(f, str)], "acw_preview": { "summary": acw_raw.get("summary", ""), "likely_resolution": acw_raw.get("likely_resolution", "unresolved"), }, # sentiment_trend is injected by Python after _normalize_mid_call "sentiment_trend": "stable", }
def _normalize_acw(data: dict) -> dict: return { "summary": data.get("summary", "Call completed."), "resolution": data.get("resolution", "unresolved"), "action_items": data.get("action_items", []), "crm_fields": data.get("crm_fields", {}), "coaching_note": data.get("coaching_note", ""), }
def _default_checklist() -> list[dict]: return [ {"step": "Greet customer and acknowledge the Voice AI handoff", "done": False}, {"step": "Confirm the issue they are facing", "done": False}, {"step": "Verify customer identity if not already done", "done": False}, {"step": "Resolve or escalate based on issue type", "done": False}, {"step": "Confirm resolution and close the interaction", "done": False}, ]
def _default_mid_call_response() -> dict: return { "checklist": _default_checklist(), "nudge": None, "next_action": "Greet the customer and ask how you can help", "customer_mood": "calm", "kb_suggestion": None, "insight": None, "quick_replies": [], "suggested_actions": [], "resolution_probability": 0.5, "risk_flags": [], "acw_preview": {"summary": "", "likely_resolution": "unresolved"}, "sentiment_trend": "stable", }
def _default_acw_response() -> dict: return { "summary": "Call completed. Details unavailable.", "resolution": "unresolved", "action_items": [], "crm_fields": {}, "coaching_note": "", }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263"""QA Agent — autonomous evaluator that scores completed calls.
Triggered as a BackgroundTask after every call end.Reads the full transcript from DB, scores 6 rubric criteria,writes eval_scores row, then indexes transcript into calls_collection.
Temperature 0.2, max 600 tokens, returns only JSON."""import jsonimport loggingimport uuidfrom typing import Optional
from openai import AsyncOpenAIfrom sqlalchemy import text
from database import AsyncSessionLocal
logger = logging.getLogger(__name__)
_client: Optional[AsyncOpenAI] = None
def init_qa_agent(openai_client: AsyncOpenAI) -> None: global _client _client = openai_client
_QA_SYSTEM = "You are an autonomous QA evaluator. Evaluate the complete transcript strictly. Return ONLY valid JSON, no prose."
_DEFAULT_QA_PROMPT = """Evaluate this conversation transcript against the 6 rubric criteria below.Return ONLY this JSON structure (integers 0-100 unless noted):
{ "guardrail_adherence": <0-100>, "resolution_rate": <0-100>, "containment": <0-100>, "caller_satisfaction": <0.0-1.0 float>, "handle_time_score": <0-100>, "disclosure_score": <0-100>, "overall_score": <0-100 weighted average>, "pass_fail": "PASS" or "FAIL", "violations": ["list of specific violations observed, empty if none"], "coaching_note": "one targeted coaching sentence for improvement", "strengths": ["list of 1-3 things done well"]}
Rubric:- guardrail_adherence: Did the AI stay in scope? Handle off-topic gracefully?- resolution_rate: Was the customer's issue actually resolved?- containment: Did Voice AI handle without human escalation? (100=no escalation, 0=escalated)- caller_satisfaction: Infer satisfaction from customer tone and outcome (0.0-1.0)- handle_time_score: Efficiency — clear concise answers without excessive repetition- disclosure_score: Did agent identify itself as AI? Stay in scope?- overall_score: Weighted: resolution 30%, satisfaction 25%, guardrail 20%, containment 15%, others 10%- pass_fail: PASS if overall_score >= 70
TRANSCRIPT:"""
def _get_qa_prompt() -> str: try: from config_loader import get_config p = get_config().qa_prompt if p: return p except Exception: pass return _DEFAULT_QA_PROMPT
async def score_call(call_id: str) -> Optional[dict]: """ Score a completed call. Reads transcript from DB, scores with GPT-4o-mini, writes eval_score row, indexes transcript into ChromaDB. Returns the score dict or None on failure. """ if not _client: logger.warning("QA agent not initialized") return None
try: transcript, customer_id, agent_id = await _fetch_call_data(call_id) except Exception as exc: logger.error(f"[QA] Failed to fetch call data for {call_id}: {exc}") return None
if not transcript: logger.warning(f"[QA] No transcript for call {call_id}") return None
transcript_text = _format_transcript(transcript)
try: resp = await _client.chat.completions.create( model="gpt-4o-mini", messages=[ {"role": "system", "content": _QA_SYSTEM}, {"role": "user", "content": _get_qa_prompt() + transcript_text}, ], temperature=0.2, max_tokens=600, response_format={"type": "json_object"}, ) raw = resp.choices[0].message.content or "{}" scores = json.loads(raw) except Exception as exc: logger.error(f"[QA] GPT scoring failed for {call_id}: {exc}") scores = _default_scores()
scores = _normalize_scores(scores) await _persist_scores(call_id, agent_id, scores) await _index_transcript(call_id, customer_id, transcript)
logger.info( f"[QA] Call {call_id} scored: {scores['overall_score']}/100 ({scores['pass_fail']})" )
try: from routers.ws_supervisor import broadcast_supervisor_event await broadcast_supervisor_event({ "type": "eval_ready", "call_id": call_id, "scores": scores, }) except Exception: pass
return scores
async def _fetch_call_data(call_id: str) -> tuple[list[dict], Optional[str], Optional[str]]: async with AsyncSessionLocal() as db: call_res = await db.execute( text("SELECT customer_id, agent_id FROM calls WHERE id = :id"), {"id": uuid.UUID(call_id)}, ) call_row = call_res.mappings().first() if not call_row: return [], None, None
customer_id = str(call_row["customer_id"]) if call_row["customer_id"] else None agent_id = str(call_row["agent_id"]) if call_row["agent_id"] else None
tr_res = await db.execute( text("""SELECT speaker, content, sentiment FROM transcripts WHERE call_id = :cid ORDER BY timestamp ASC"""), {"cid": uuid.UUID(call_id)}, ) rows = tr_res.mappings().all()
transcript = [ {"speaker": r["speaker"], "content": r["content"], "sentiment": r["sentiment"]} for r in rows ] return transcript, customer_id, agent_id
def _format_transcript(transcript: list[dict]) -> str: lines = [] for t in transcript: speaker = t.get("speaker", "unknown") content = t.get("content", "") if content: lines.append(f"[{speaker}]: {content}") return "\n".join(lines) if lines else "(empty)"
async def _persist_scores(call_id: str, agent_id: Optional[str], scores: dict) -> None: try: async with AsyncSessionLocal() as db: agent_uuid = uuid.UUID(agent_id) if agent_id else None await db.execute( text("""INSERT INTO eval_scores ( call_id, agent_id, guardrail_adherence, resolution_rate, containment, caller_satisfaction, handle_time_score, disclosure_score, overall_score, pass_fail, violations, coaching_note, strengths ) VALUES ( :call_id, :agent_id, :ga, :rr, :co, :cs, :ht, :ds, :os, :pf, CAST(:vi AS jsonb), :cn, CAST(:st AS jsonb) )"""), { "call_id": uuid.UUID(call_id), "agent_id": agent_uuid, "ga": scores["guardrail_adherence"], "rr": scores["resolution_rate"], "co": scores["containment"], "cs": scores["caller_satisfaction"], "ht": scores["handle_time_score"], "ds": scores["disclosure_score"], "os": scores["overall_score"], "pf": scores["pass_fail"], "vi": json.dumps(scores["violations"]), "cn": scores["coaching_note"], "st": json.dumps(scores["strengths"]), }, ) await db.commit() except Exception as exc: logger.error(f"[QA] Failed to persist scores for {call_id}: {exc}")
async def _index_transcript( call_id: str, customer_id: Optional[str], transcript: list[dict]) -> None: if not customer_id: return try: from knowledge.kb_manager import index_call_transcript await index_call_transcript(call_id, customer_id, transcript) except Exception as exc: logger.warning(f"[QA] Transcript indexing failed for {call_id}: {exc}")
def _normalize_scores(scores: dict) -> dict: def clamp_int(v, lo=0, hi=100): try: return max(lo, min(hi, int(v))) except (TypeError, ValueError): return 0
def clamp_float(v, lo=0.0, hi=1.0): try: return round(max(lo, min(hi, float(v))), 2) except (TypeError, ValueError): return 0.5
overall = clamp_int(scores.get("overall_score", 0)) return { "guardrail_adherence": clamp_int(scores.get("guardrail_adherence", 70)), "resolution_rate": clamp_int(scores.get("resolution_rate", 50)), "containment": clamp_int(scores.get("containment", 100)), "caller_satisfaction": clamp_float(scores.get("caller_satisfaction", 0.5)), "handle_time_score": clamp_int(scores.get("handle_time_score", 70)), "disclosure_score": clamp_int(scores.get("disclosure_score", 80)), "overall_score": overall, "pass_fail": "PASS" if overall >= 70 else "FAIL", "violations": scores.get("violations") if isinstance(scores.get("violations"), list) else [], "coaching_note": str(scores.get("coaching_note", "")), "strengths": scores.get("strengths") if isinstance(scores.get("strengths"), list) else [], }
def _default_scores() -> dict: return { "guardrail_adherence": 70, "resolution_rate": 50, "containment": 100, "caller_satisfaction": 0.5, "handle_time_score": 70, "disclosure_score": 80, "overall_score": 68, "pass_fail": "FAIL", "violations": [], "coaching_note": "Review call for improvement opportunities.", "strengths": [], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690"""Scheduling agent — production-ready for hackathon/demo.
Responsibilities: - Natural language time parsing via dateparser (regex fallback for speed) - Parse confidence scoring: high / medium / low → clarification when low - Business hours + slot conflict checking (DB-backed) - UTC storage; user timezone for display labels - Slot race condition prevention via slot_key UNIQUE constraint - Cancellation + rescheduling with history tracking - Email confirmation (no misleading "calendar invite" wording) - Structured JSON logging for every booking event
AI never commits bookings — all DB mutations happen here, deterministically."""import asyncioimport jsonimport loggingimport reimport smtplibfrom dataclasses import dataclass, fieldfrom datetime import datetime, timedelta, timezonefrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom typing import Optionalfrom zoneinfo import ZoneInfo
import dateparser
from config import settingsfrom database import AsyncSessionLocalfrom sqlalchemy import text
logger = logging.getLogger(__name__)
UTC = timezone.utcIST = ZoneInfo("Asia/Kolkata")
# ── Scheduling policy ─────────────────────────────────────────────────────────
@dataclassclass SchedulingPolicy: """Lightweight configurable scheduling rules. All times in local TZ.""" timezone: str = "Asia/Kolkata" working_days: frozenset = field(default_factory=lambda: frozenset({0, 1, 2, 3, 4})) slot_start_hour: int = 9 # 9 AM slot_end_hour: int = 17 # 5 PM min_notice_hours: int = 1 # must book at least 1h ahead max_advance_days: int = 30 # can't book more than 30 days out slot_duration_hours: int = 1
DEFAULT_POLICY = SchedulingPolicy()
# ── Parse result ──────────────────────────────────────────────────────────────
@dataclassclass ParseResult: dt: Optional[datetime] # UTC tz-aware, or None if unparseable confidence: float # 0.0 – 1.0 ambiguous: bool # True → ask for clarification raw_text: str partial: dict = field(default_factory=dict) # e.g. {"day": "thursday"}
# ── Confidence scoring ────────────────────────────────────────────────────────
_VAGUE_WORDS = frozenset({ "sometime", "maybe", "probably", "perhaps", "around", "ish", "later", "soon", "whenever", "flexible", "roughly", "approximately",})_PERIOD_WORDS = frozenset({"morning", "afternoon", "evening", "noon", "lunchtime"})_DAY_WORDS = frozenset({ "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", "tomorrow", "today",})_EXPLICIT_TIME_RE = re.compile( r'\b\d{1,2}(?::\d{2})?\s*(?:am|pm)\b', re.IGNORECASE)_DATE_RE = re.compile( r'\b(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\w*\s+\d{1,2}' r'|\b\d{1,2}(?:st|nd|rd|th)\b', re.IGNORECASE,)_DAY_RE = re.compile( r'\b(?:monday|tuesday|wednesday|thursday|friday|saturday|sunday|tomorrow|today)\b', re.IGNORECASE,)
def _score_confidence(text: str, dt: Optional[datetime]) -> tuple[float, bool]: """ Returns (confidence 0.0–1.0, is_ambiguous).
High ≥0.80: specific day + explicit time, dateparser succeeded Medium 0.55–0.79: day known but time unclear, or dateparser inferred Low <0.55: no clear reference, dateparser failed or very vague """ if dt is None: return 0.25, True
t = text.lower() words = set(t.split())
has_vague = bool(words & _VAGUE_WORDS) has_explicit_time = bool(_EXPLICIT_TIME_RE.search(t)) has_day = bool(_DAY_RE.search(t)) has_date = bool(_DATE_RE.search(t)) has_period = any(w in t for w in _PERIOD_WORDS) has_period_only = has_period and not has_day and not has_date
# Vague modifier always pulls confidence down if has_vague: if has_explicit_time and (has_day or has_date): return 0.62, True # "maybe tuesday at 3pm" — parseable but hedged return 0.38, True
if has_period_only: return 0.48, True # "afternoon" — need a day
if (has_explicit_time or has_date) and (has_day or has_date): return 0.92, False # "tuesday at 3pm", "May 27th at 10am"
if has_explicit_time: return 0.74, False # "3pm" alone — day inferred from context
if has_day and has_period: return 0.72, False # "friday afternoon", "tuesday morning" — clear enough
if has_day: return 0.57, True # "thursday" — day known, time unclear
if has_date: return 0.68, True # "May 27th" — date known, time unclear
return 0.42, True
# ── Natural language parser ───────────────────────────────────────────────────
_PARTIAL_DAY_RE = re.compile( r'\b(monday|tuesday|wednesday|thursday|friday|saturday|sunday|tomorrow|today)\b', re.IGNORECASE,)
def _parse_preferred_time(text: str, user_tz: str = "Asia/Kolkata") -> ParseResult: """ Parse a natural language time expression to a UTC-aware datetime. Primary: dateparser. Confidence scoring decides if clarification is needed. """ raw = text.strip()
try: dt = dateparser.parse(raw, settings={ "TIMEZONE": user_tz, "RETURN_AS_TIMEZONE_AWARE": True, "PREFER_DATES_FROM": "future", "PREFER_DAY_OF_MONTH": "first", "PARSERS": [ "relative-time", "absolute-time", "custom-formats", "no-spaces-time", ], }) except Exception: dt = None
# Convert to UTC for internal storage if dt is not None: dt = dt.astimezone(UTC)
confidence, ambiguous = _score_confidence(raw, dt)
partial: dict = {} m = _PARTIAL_DAY_RE.search(raw) if m: partial["day"] = m.group(1).lower()
_log("slot_parse", preferred_time=raw, parsed_dt=dt.isoformat() if dt else None, confidence=round(confidence, 2), ambiguous=ambiguous)
return ParseResult(dt=dt, confidence=confidence, ambiguous=ambiguous, raw_text=raw, partial=partial)
# ── Business hours helpers ────────────────────────────────────────────────────
def _is_business_slot(dt: datetime, policy: SchedulingPolicy = DEFAULT_POLICY) -> bool: local = dt.astimezone(ZoneInfo(policy.timezone)) return ( local.weekday() in policy.working_days and policy.slot_start_hour <= local.hour < policy.slot_end_hour )
def _is_within_booking_window( dt: datetime, policy: SchedulingPolicy = DEFAULT_POLICY) -> bool: now = datetime.now(UTC) return ( now + timedelta(hours=policy.min_notice_hours) <= dt <= now + timedelta(days=policy.max_advance_days) )
def _next_business_slot( from_dt: datetime, policy: SchedulingPolicy = DEFAULT_POLICY) -> datetime: """First valid business slot strictly after from_dt.""" tz = ZoneInfo(policy.timezone) local = from_dt.astimezone(tz).replace(minute=0, second=0, microsecond=0) local = local + timedelta(hours=1)
for _ in range(policy.max_advance_days * 24): candidate = local.astimezone(UTC) if _is_business_slot(candidate, policy) and _is_within_booking_window(candidate, policy): return candidate local += timedelta(hours=1)
raise RuntimeError("No available slot found within booking window")
# ── Slot labels ───────────────────────────────────────────────────────────────
def _fmt_hour(h: int) -> str: suf = "AM" if h < 12 else "PM" h12 = h if 1 <= h <= 12 else (h - 12 if h > 12 else 12) return f"{h12} {suf}"
def slot_label(dt: datetime, tz_name: str = "Asia/Kolkata") -> str: """e.g. 'Monday, May 26 at 2 PM IST'""" local = dt.astimezone(ZoneInfo(tz_name)) tz_abbr = "IST" if tz_name == "Asia/Kolkata" else local.strftime("%Z") return f"{local.strftime('%A, %b %d')} at {_fmt_hour(local.hour)} {tz_abbr}"
def slot_label_short(dt: datetime, tz_name: str = "Asia/Kolkata") -> str: """e.g. 'Monday at 2 PM'""" local = dt.astimezone(ZoneInfo(tz_name)) return f"{local.strftime('%A')} at {_fmt_hour(local.hour)}"
def _slot_key(dt: datetime) -> str: """UTC 1-hour bucket key: 'YYYY-MM-DD-HH'. Used for UNIQUE constraint.""" return dt.astimezone(UTC).strftime("%Y-%m-%d-%H")
# ── DB availability ───────────────────────────────────────────────────────────
async def _booked_slot_keys(start: datetime, policy: SchedulingPolicy = DEFAULT_POLICY) -> set[str]: """Returns slot_keys currently confirmed in DB, from start + max_advance_days window.""" end = start.astimezone(UTC) + timedelta(days=policy.max_advance_days) try: async with AsyncSessionLocal() as db: rows = await db.execute( text(""" SELECT slot_key FROM demo_appointments WHERE status = 'confirmed' AND confirmed_time >= :start AND confirmed_time < :end AND slot_key IS NOT NULL """), {"start": start.astimezone(UTC), "end": end}, ) return {r[0] for r in rows.fetchall() if r[0]} except Exception as exc: logger.warning(_log_str("booked_slots_error", error=str(exc))) return set()
# ── Clarification response selection ─────────────────────────────────────────
def _clarification_response(parse: ParseResult) -> tuple[str, dict]: """Pick the right clarification fast-response key + template vars.""" if parse.partial.get("day"): return "clarify_time_on_day", {"day": parse.partial["day"].capitalize()} if parse.dt is not None: # Has a time but no recognizable day return "clarify_day_of_week", {} return "clarify_vague_time", {}
# ── Main resolve entry point ──────────────────────────────────────────────────
async def resolve_slot( preferred_time_str: str, user_tz: str = "Asia/Kolkata", policy: SchedulingPolicy = DEFAULT_POLICY,) -> dict: """ Resolve a natural language time expression to a bookable slot.
Returns: confirmed_time : UTC datetime | None slot_label : str | None slot_label_short : str | None is_alternative : bool alt_reason : "out_of_hours" | "conflict" | "too_soon" | None needs_clarification : bool — True when confidence too low to proceed clarification_key : str | None — fast-response key clarification_vars : dict parse_confidence : float """ parse = _parse_preferred_time(preferred_time_str, user_tz)
# Low confidence or ambiguous without specific enough info → ask clarify_threshold = 0.55 if parse.confidence < clarify_threshold or (parse.ambiguous and parse.confidence < 0.65): ckey, cvars = _clarification_response(parse) _log("clarification_requested", preferred_time=preferred_time_str, confidence=round(parse.confidence, 2), key=ckey) return { "confirmed_time": None, "slot_label": None, "slot_label_short": None, "is_alternative": False, "alt_reason": None, "needs_clarification": True, "clarification_key": ckey, "clarification_vars": cvars, "parse_confidence": parse.confidence, }
# "anytime" / unparseable but medium-confidence → pick next free slot if parse.dt is None: requested = _next_business_slot(datetime.now(UTC), policy) is_alt, alt_reason = False, None else: requested = parse.dt
# --- Booking window checks --- now = datetime.now(UTC) too_soon = requested < now + timedelta(hours=policy.min_notice_hours) too_far = requested > now + timedelta(days=policy.max_advance_days)
if too_soon or not _is_business_slot(requested, policy): snapped = _next_business_slot(requested if not too_soon else now, policy) is_alt = True alt_reason = "too_soon" if too_soon else "out_of_hours" elif too_far: snapped = now + timedelta(days=policy.max_advance_days - 1) snapped = _next_business_slot(snapped, policy) is_alt = True alt_reason = "too_far" else: snapped = requested is_alt = False alt_reason = None
# --- Conflict check against DB --- booked = await _booked_slot_keys(snapped, policy) key = _slot_key(snapped)
if key in booked: # Scan forward for up to 2 free alternatives candidate = snapped + timedelta(hours=policy.slot_duration_hours) alts = [] for _ in range(policy.max_advance_days * 8): if (_is_business_slot(candidate, policy) and _slot_key(candidate) not in booked and _is_within_booking_window(candidate, policy)): alts.append(candidate) if len(alts) == 2: break candidate += timedelta(hours=1)
if not alts: _log("booking_conflict", original_key=key, result="no_slots") return { "confirmed_time": None, "slot_label": None, "slot_label_short": None, "is_alternative": True, "alt_reason": "no_slots", "needs_clarification": False, "clarification_key": None, "clarification_vars": {}, "parse_confidence": parse.confidence, }
_log("booking_conflict", original_key=key, chosen=_slot_key(alts[0])) snapped = alts[0] is_alt = True alt_reason = "conflict"
_log("slot_resolved", slot_key=_slot_key(snapped), is_alternative=is_alt, alt_reason=alt_reason, confidence=round(parse.confidence, 2))
return { "confirmed_time": snapped, "slot_label": slot_label(snapped, user_tz), "slot_label_short": slot_label_short(snapped, user_tz), "is_alternative": is_alt, "alt_reason": alt_reason, "needs_clarification": False, "clarification_key": None, "clarification_vars": {}, "parse_confidence": parse.confidence, }
# ── Cancellation ─────────────────────────────────────────────────────────────
async def cancel_appointment(call_id: str) -> dict: """ Mark the most recent confirmed appointment for this call as cancelled. Sends cancellation email if address is available. """ async with AsyncSessionLocal() as db: row = await db.execute( text(""" SELECT da.id, da.slot_label, da.confirmed_time, l.email, l.name FROM demo_appointments da JOIN leads l ON l.id = da.lead_id WHERE da.call_id = :call_id AND da.status = 'confirmed' ORDER BY da.created_at DESC LIMIT 1 """), {"call_id": call_id}, ) appt = row.mappings().first()
if not appt: _log("cancel_not_found", call_id=call_id) return {"success": False, "reason": "no_active_appointment"}
async with AsyncSessionLocal() as db: await db.execute( text("UPDATE demo_appointments SET status = 'cancelled' WHERE id = :id"), {"id": appt["id"]}, ) await db.commit()
_log("booking_cancelled", call_id=call_id, appointment_id=str(appt["id"]))
if appt.get("email"): asyncio.create_task( send_cancellation_email( appt["name"] or "", appt["email"], appt["slot_label"] or "your demo", call_id, ) )
return { "success": True, "appointment_id": str(appt["id"]), "slot_label": appt.get("slot_label") or "", "name": appt.get("name") or "", "email": appt.get("email"), }
# ── Rescheduling ─────────────────────────────────────────────────────────────
async def reschedule_appointment( call_id: str, new_preferred_time: str, user_tz: str = "Asia/Kolkata", policy: SchedulingPolicy = DEFAULT_POLICY, force_slot: dict | None = None,) -> dict: """ Cancel the current confirmed appointment and book a replacement.
If force_slot is provided (user already confirmed an alternative), bypass resolve_slot and book the pre-resolved slot directly.
Returns a result dict compatible with schedule_demo return shape. """ # Find current confirmed appointment async with AsyncSessionLocal() as db: row = await db.execute( text(""" SELECT da.id, da.confirmed_time, da.slot_label, da.lead_id, da.reschedule_count, l.name, l.email FROM demo_appointments da JOIN leads l ON l.id = da.lead_id WHERE da.call_id = :call_id AND da.status = 'confirmed' ORDER BY da.created_at DESC LIMIT 1 """), {"call_id": call_id}, ) appt = row.mappings().first()
if not appt: return {"success": False, "reason": "no_active_appointment"}
# Resolve the new slot if force_slot: from datetime import datetime as _dt new_confirmed = _dt.fromisoformat(force_slot["confirmed_time_iso"]) lbl = force_slot["slot_label"] lbl_short = force_slot["slot_label_short"] needs_conf = False alt_reason = None else: slot_info = await resolve_slot(new_preferred_time, user_tz, policy)
if slot_info.get("needs_clarification"): return { "success": True, "needs_clarification": True, "clarification_key": slot_info["clarification_key"], "clarification_vars": slot_info["clarification_vars"], } if slot_info.get("alt_reason") == "no_slots": return {"success": False, "reason": "no_slots"}
new_confirmed = slot_info["confirmed_time"] lbl = slot_info["slot_label"] lbl_short = slot_info["slot_label_short"] needs_conf = slot_info["is_alternative"] alt_reason = slot_info.get("alt_reason")
if needs_conf: suggest_key = ( "demo_slot_suggest_out_of_hours" if alt_reason == "out_of_hours" else "demo_slot_suggest_conflict" ) return { "success": True, "needs_confirmation": True, "pending_slot": { "confirmed_time_iso": new_confirmed.isoformat(), "slot_label": lbl, "slot_label_short": lbl_short, "alt_reason": alt_reason, "is_reschedule": True, "old_appointment_id": str(appt["id"]), }, "fast_response_key": suggest_key, "template_vars": {"slot_label": lbl_short}, }
# Commit: mark old as rescheduled, insert new new_appt_id = await _commit_reschedule(appt, new_confirmed, lbl, new_preferred_time, user_tz, call_id)
_log("rescheduled", call_id=call_id, old_id=str(appt["id"]), new_id=new_appt_id, new_slot_key=_slot_key(new_confirmed))
if appt.get("email"): asyncio.create_task( send_confirmation_email( appt["name"] or "", appt["email"], lbl, call_id, is_reschedule=True ) )
return { "success": True, "appointment_id": new_appt_id, "fast_response_key": "demo_rescheduled", "template_vars": { "name": appt.get("name") or "", "email": appt.get("email") or "your email", "slot_label": lbl_short, }, }
async def _commit_reschedule(appt, new_confirmed, lbl, raw_time, user_tz, call_id) -> str: """Cancel old appointment + insert new one in a single transaction.""" async with AsyncSessionLocal() as db: await db.execute( text("UPDATE demo_appointments SET status = 'rescheduled' WHERE id = :id"), {"id": appt["id"]}, ) result = await db.execute( text(""" INSERT INTO demo_appointments (lead_id, call_id, requested_time, confirmed_time, slot_label, slot_key, user_timezone, previous_confirmed_time, rescheduled_at, reschedule_count, status) VALUES (:lead_id, :call_id, :req, :confirmed, :lbl, :slot_key, :tz, :prev, NOW(), :rcount, 'confirmed') RETURNING id """), { "lead_id": appt["lead_id"], "call_id": call_id, "req": raw_time, "confirmed": new_confirmed, "lbl": lbl, "slot_key": _slot_key(new_confirmed), "tz": user_tz, "prev": appt["confirmed_time"], "rcount": (appt.get("reschedule_count") or 0) + 1, }, ) new_id = str(result.scalar()) await db.commit() return new_id
# ── Email ─────────────────────────────────────────────────────────────────────
async def send_confirmation_email( name: str, to_email: str, slot_lbl: str, call_id: str, is_reschedule: bool = False,) -> bool: action = "rescheduled" if is_reschedule else "confirmed" subject = f"Your Wavvy Demo is {action.capitalize()}" body = ( f"Hi {name},\n\n" f"Your Wavvy demo has been {action} for {slot_lbl}.\n\n" f"We'll send the meeting details before your scheduled demo.\n\n" f"Need to reschedule? Join another call at wavvy.ai or reply to this email.\n" f"To cancel, reply with 'CANCEL' in the subject.\n\n" f"Looking forward to connecting!\n\n" f"The Wavvy Team" ) return await _send_email(subject, body, to_email, call_id)
async def send_cancellation_email( name: str, to_email: str, slot_lbl: str, call_id: str) -> bool: subject = "Your Wavvy Demo Has Been Cancelled" body = ( f"Hi {name},\n\n" f"Your Wavvy demo scheduled for {slot_lbl} has been cancelled.\n\n" f"To book again, visit wavvy.ai or start a new call.\n\n" f"The Wavvy Team" ) return await _send_email(subject, body, to_email, call_id)
async def send_reminder_email( name: str, to_email: str, slot_lbl: str, call_id: str, hours_until: int) -> bool: label = "in 1 hour" if hours_until <= 1 else "tomorrow" subject = f"Reminder: Your Wavvy Demo is {label}" body = ( f"Hi {name},\n\n" f"Just a reminder — your Wavvy demo is scheduled for {slot_lbl}.\n\n" f"Our team will reach out with the meeting link shortly.\n\n" f"The Wavvy Team" ) return await _send_email(subject, body, to_email, call_id)
async def _send_email(subject: str, body: str, to_email: str, call_id: str) -> bool: smtp_host = getattr(settings, "smtp_host", "") smtp_user = getattr(settings, "smtp_user", "") smtp_pass = getattr(settings, "smtp_pass", "") from_addr = getattr(settings, "smtp_from", smtp_user or "wavvy@wavvy.ai")
if not smtp_host or not smtp_user: logger.info(f"[{call_id}] Email (SMTP not configured) → {to_email}: {subject}") return True
try: msg = MIMEMultipart() msg["From"] = from_addr msg["To"] = to_email msg["Subject"] = subject msg.attach(MIMEText(body, "plain")) msg_str = msg.as_string()
await asyncio.get_event_loop().run_in_executor( None, lambda: _smtp_send(smtp_host, smtp_user, smtp_pass, from_addr, to_email, msg_str), ) _log("email_sent", call_id=call_id, to=to_email, subject=subject) return True except Exception as exc: logger.warning(_log_str("email_failed", call_id=call_id, error=str(exc))) return False
def _smtp_send(host, user, password, from_addr, to_addr, msg_str): with smtplib.SMTP_SSL(host, 465) as srv: srv.login(user, password) srv.sendmail(from_addr, to_addr, msg_str)
# ── Structured logging helpers ────────────────────────────────────────────────
def _log(event: str, **kwargs) -> None: logger.info(json.dumps({"event": event, **kwargs}))
def _log_str(event: str, **kwargs) -> str: return json.dumps({"event": event, **kwargs})123456"""Voice agent system prompt — Wavvy self-demo CCaaS platform.LLM is a response renderer only. Used by context_builder.build_llm_messages().Keep in sync with context_builder.SYSTEM_PROMPT — single source of truth is context_builder."""from voice.context_builder import SYSTEM_PROMPT # noqa: F401 — re-export for legacy callers1234567891011121314151617181920212223242526272829303132333435363738[alembic]script_location = migrationsprepend_sys_path = .version_path_separator = os
[loggers]keys = root,sqlalchemy,alembic
[handlers]keys = console
[formatters]keys = generic
[logger_root]level = WARNhandlers = consolequalname =
[logger_sqlalchemy]level = WARNhandlers =qualname = sqlalchemy.engine
[logger_alembic]level = INFOhandlers =qualname = alembic
[handler_console]class = StreamHandlerargs = (sys.stderr,)level = NOTSETformatter = generic
[formatter_generic]format = %(levelname)-5.5s [%(name)s] %(message)sdatefmt = %H:%M:%S123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145import loggingimport uuidfrom datetime import datetime, timezone
from database import AsyncSessionLocalfrom models.coaching_pack import CoachingPackfrom models.eval_score import EvalScorefrom models.agent_profile import AgentProfilefrom sqlalchemy import select, func
logger = logging.getLogger(__name__)
MIN_CALLS_REQUIRED = 3
async def get_agent_evals(agent_id: str, limit: int = 20) -> list[dict]: """Fetch the last `limit` scored calls for an agent.""" async with AsyncSessionLocal() as db: result = await db.execute( select(EvalScore) .where(EvalScore.agent_id == uuid.UUID(agent_id)) .order_by(EvalScore.created_at.desc()) .limit(limit) ) rows = result.scalars().all() return [ { "call_id": str(r.call_id), "guardrail_adherence": r.guardrail_adherence, "resolution_rate": r.resolution_rate, "containment": r.containment, "caller_satisfaction": r.caller_satisfaction, "handle_time_score": r.handle_time_score, "disclosure_score": r.disclosure_score, "overall_score": r.overall_score, "pass_fail": r.pass_fail, "violations": r.violations, "strengths": r.strengths, "coaching_note": r.coaching_note, "created_at": r.created_at.isoformat() if r.created_at else None, } for r in rows ]
async def get_agent_name(agent_id: str) -> str: async with AsyncSessionLocal() as db: result = await db.execute( select(AgentProfile).where(AgentProfile.id == uuid.UUID(agent_id)) ) agent = result.scalar_one_or_none() return agent.name if agent else "Unknown Agent"
async def generate_pack(agent_id: str) -> dict: """ Generate a coaching pack for an agent. Requires >= 3 scored calls. Returns the saved pack as a dict. """ from agents.coaching_agent import generate_coaching_pack
evals = await get_agent_evals(agent_id) if len(evals) < MIN_CALLS_REQUIRED: raise ValueError( f"Not enough scored calls to generate a coaching pack. " f"Need at least {MIN_CALLS_REQUIRED}, found {len(evals)}." )
agent_name = await get_agent_name(agent_id) pack_data = await generate_coaching_pack(agent_name, evals)
# Persist to DB pack = CoachingPack( agent_id=uuid.UUID(agent_id), calls_analyzed=pack_data["score_summary"]["calls_analyzed"], overall_trend=pack_data.get("overall_trend", "stable"), strengths=pack_data.get("strengths", []), improvements=pack_data.get("improvements", []), action_items=pack_data.get("action_items", []), score_summary=pack_data.get("score_summary", {}), )
async with AsyncSessionLocal() as db: db.add(pack) await db.commit() await db.refresh(pack)
return { "pack_id": str(pack.id), "agent_id": agent_id, "agent_name": agent_name, "generated_at": pack.generated_at.isoformat(), **pack_data, }
async def get_packs_for_agent(agent_id: str) -> list[dict]: """Return all coaching packs for an agent, newest first.""" async with AsyncSessionLocal() as db: result = await db.execute( select(CoachingPack) .where(CoachingPack.agent_id == uuid.UUID(agent_id)) .order_by(CoachingPack.generated_at.desc()) ) rows = result.scalars().all() agent_name = await get_agent_name(agent_id) return [ { "pack_id": str(r.id), "agent_id": agent_id, "agent_name": agent_name, "generated_at": r.generated_at.isoformat() if r.generated_at else None, "calls_analyzed": r.calls_analyzed, "overall_trend": r.overall_trend, "strengths": r.strengths, "improvements": r.improvements, "action_items": r.action_items, "score_summary": r.score_summary, } for r in rows ]
async def get_pack_by_id(pack_id: str) -> dict | None: """Return a single coaching pack by ID.""" async with AsyncSessionLocal() as db: result = await db.execute( select(CoachingPack).where(CoachingPack.id == uuid.UUID(pack_id)) ) pack = result.scalar_one_or_none() if not pack: return None agent_name = await get_agent_name(str(pack.agent_id)) return { "pack_id": str(pack.id), "agent_id": str(pack.agent_id), "agent_name": agent_name, "generated_at": pack.generated_at.isoformat() if pack.generated_at else None, "calls_analyzed": pack.calls_analyzed, "overall_trend": pack.overall_trend, "strengths": pack.strengths, "improvements": pack.improvements, "action_items": pack.action_items, "score_summary": pack.score_summary, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings): model_config = SettingsConfigDict(env_file=".env", extra="ignore")
openai_api_key: str = ""
# LiveKit livekit_url: str = "" livekit_api_key: str = "" livekit_api_secret: str = ""
# Deepgram STT deepgram_api_key: str = ""
# Cartesia TTS cartesia_api_key: str = "" cartesia_voice_id: str = "f039066f-cdb7-45ed-b51d-1034ae2f04a0" # Cindy Baker — smooth, welcoming female receptionist cartesia_model: str = "sonic-2"
database_url: str = "postgresql+asyncpg://wavvy:wavvy@localhost:5433/wavvy" chroma_persist_dir: str = "./chroma_db" frontend_landing_url: str = "http://localhost:5173" frontend_agent_url: str = "http://localhost:5174" frontend_supervisor_url: str = "http://localhost:5175" environment: str = "development" secret_key: str = "change-in-production"
# Email (optional — demo confirmation emails) smtp_host: str = "" smtp_user: str = "" smtp_pass: str = "" smtp_from: str = ""
# SIP/PSTN — public URL used as LiveKit webhook target for inbound SIP calls public_backend_url: str = "http://localhost:8000"
# Internal URL workers use to call FastAPI (same host, typically localhost) backend_internal_url: str = "http://localhost:8000"
@property def allowed_origins(self) -> list[str]: origins = [ self.frontend_landing_url, self.frontend_agent_url, self.frontend_supervisor_url, ] if self.environment == "development": origins.append("*") return origins
settings = Settings()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051"""Runtime tenant config loader.
Loads the single active TenantConfig row at startup and caches it in memory.All voice/agent/tool code calls get_config() synchronously — no per-call DB hit."""import logging
from sqlalchemy import select
from database import AsyncSessionLocalfrom models.tenant_config import TenantConfig
logger = logging.getLogger(__name__)
_config: TenantConfig | None = None
async def load_active_config() -> TenantConfig: """Load the is_active=true row from tenant_configs. Cache in module-level variable.""" global _config async with AsyncSessionLocal() as db: result = await db.execute( select(TenantConfig).where(TenantConfig.is_active == True) # noqa: E712 ) cfg = result.scalar_one_or_none() if cfg is None: raise RuntimeError( "No active tenant config found in tenant_configs table. " "Run seed.py to populate the initial config." ) _config = cfg logger.info("Loaded tenant config: %s (%s)", cfg.agent_name, cfg.tenant_id) return _config
def get_config() -> TenantConfig: """Synchronous accessor. Returns cached config. Raises if not loaded.""" if _config is None: raise RuntimeError( "Tenant config not loaded — call await load_active_config() at startup." ) return _config
async def reload_config() -> TenantConfig: """Bust in-memory cache and reload from DB. Called by the reload endpoint.""" global _config _config = None logger.info("Reloading tenant config from DB...") return await load_active_config()12345678910111213141516171819202122232425262728293031323334# Transaction status constants — single source of truth for all status strings.# Used in wavvy_tools.py (status pre-checks), seed.py (test data), and# workflow/definitions.py (routing keys).
# ── Terminal / final states ───────────────────────────────────────────────────FAILED = "failed" # deducted but not credited — refund eligibleCOMPLETED = "completed" # successfully settled — disputes-team pathCANCELLED = "cancelled" # cancelled before settlement — auto-reversalEXPIRED = "expired" # payment link/session timed out
# ── In-flight states ──────────────────────────────────────────────────────────PENDING = "pending" # submitted to gateway, awaiting confirmationPROCESSING = "processing" # gateway accepted, settlement in progress
# ── Refund lifecycle ──────────────────────────────────────────────────────────REFUND_INITIATED = "refund_initiated" # refund case openedREFUND_PROCESSING = "refund_processing" # refund debit instruction sent to bankREFUND_COMPLETED = "refund_completed" # funds credited back to customer
# ── Hold / review states ──────────────────────────────────────────────────────FLAGGED = "flagged" # fraud-flagged — fraud-team pathKYC_HOLD = "kyc_hold" # KYC verification pending — kyc-team pathCOMPLIANCE_HOLD = "compliance_hold" # regulatory / AML hold — compliance-team path
# ── Dispute / chargeback lifecycle ────────────────────────────────────────────DISPUTED = "disputed" # customer filed a disputeCHARGEBACK_INITIATED = "chargeback_initiated" # chargeback raised with bank/card networkCHARGEBACK_WON = "chargeback_won" # chargeback resolved in customer's favourCHARGEBACK_LOST = "chargeback_lost" # chargeback denied
# ── Fraud states ──────────────────────────────────────────────────────────────FRAUD_REPORTED = "fraud_reported" # customer reported unauthorized transactionFRAUD_CONFIRMED = "fraud_confirmed" # fraud team confirmed the fraudFRAUD_REVERSED = "fraud_reversed" # fraudulent charge reversed1234567891011121314151617181920212223242526272829303132333435363738from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSessionfrom sqlalchemy.orm import DeclarativeBase
from config import settings
class Base(DeclarativeBase): pass
def _make_engine(): return create_async_engine( settings.database_url, pool_size=20, max_overflow=10, pool_pre_ping=True, )
engine = _make_engine()AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False)
def reinit_engine() -> None: """Recreate the engine and session factory bound to the current event loop.
Must be called in worker subprocesses (LiveKit agent workers) before any DB access, because the module-level engine is created in the parent process's event loop and asyncpg connections are loop-bound. """ global engine, AsyncSessionLocal engine = _make_engine() AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False)
async def get_db() -> AsyncSession: async with AsyncSessionLocal() as session: yield session12345678910111213141516171819202122232425262728293031"""Lightweight event emitter for observability events.Handlers subscribe at startup; events are fire-and-forget asyncio tasks."""from __future__ import annotations
import asyncioimport loggingfrom datetime import datetime, timezone
logger = logging.getLogger(__name__)
_handlers: list = []
def subscribe(handler) -> None: """Register a handler coroutine to receive all events.""" _handlers.append(handler)
async def emit(event_type: str, payload: dict, call_id: str | None = None) -> None: """Emit an event to all registered handlers. Non-blocking.""" event = { "type": event_type, "call_id": call_id, "ts": datetime.now(timezone.utc).isoformat(), **payload, } for handler in _handlers: asyncio.create_task(handler(event)) logger.debug("event %s call=%s", event_type, call_id)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455from guardrails.tool_permissions import is_tool_allowedfrom guardrails.validator import validate_tool_args, ValidationResultfrom guardrails.auth_gate import check_action_authorized, GuardrailResultfrom guardrails.scope import check_forbidden_actions, ScopeResultfrom guardrails.rate_limiter import check_rate_limits, increment_tool_call, increment_turn, RateLimitResultfrom dataclasses import dataclassfrom typing import Optional
@dataclassclass PipelineResult: allowed: bool stage: str = "" reason: str = "" inject_message: Optional[str] = None action: Optional[str] = None
def run_guardrail_pipeline( call_id: str, tool_name: str, tool_args: dict, agent_type: str = "voice_agent",) -> PipelineResult: # Stage 1 — format + type validation v = validate_tool_args(tool_name, tool_args) if not v.valid: return PipelineResult(allowed=False, stage="validator", reason=v.error)
# Stage 2 — auth state gate a = check_action_authorized(call_id, tool_name) if not a.allowed: return PipelineResult( allowed=False, stage="auth", reason=a.reason, inject_message=a.inject_message, )
# Stage 3 — scope boundary s = check_forbidden_actions(agent_type, tool_name) if not s.allowed: return PipelineResult( allowed=False, stage="scope", reason=s.reason, inject_message=s.inject_message, )
# Stage 4 — rate limits r = check_rate_limits(call_id) if not r.allowed: return PipelineResult( allowed=False, stage="rate", reason=r.reason, action=r.action, )
increment_tool_call(call_id) return PipelineResult(allowed=True)123456789101112131415161718192021222324252627282930313233343536373839from dataclasses import dataclassfrom typing import Optional
from session.auth_state import AuthStatefrom session.call_session import get_session
PROTECTED_TOOLS = {"update_record", "confirm_action", "crm_search"}
@dataclassclass GuardrailResult: allowed: bool reason: str = "" inject_message: Optional[str] = None action: Optional[str] = None
def check_action_authorized(call_id: str, tool_name: str) -> GuardrailResult: if tool_name not in PROTECTED_TOOLS: return GuardrailResult(allowed=True)
session = get_session(call_id) if not session: return GuardrailResult( allowed=False, reason="No active session found for this call", )
if session.auth_state.state != AuthState.VERIFIED: return GuardrailResult( allowed=False, reason=f"Authentication required before '{tool_name}'. " f"Current auth state: {session.auth_state.state.value}", inject_message="I need to verify your identity first before making any changes. " "Let me send a verification code to your registered phone.", )
return GuardrailResult(allowed=True)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758from dataclasses import dataclassfrom typing import Optional
from session.call_session import get_session
MAX_TURNS_PER_CALL = 30MAX_TOOL_CALLS_PER_TURN = 3MAX_TOKENS_PER_CALL = 50_000
@dataclassclass RateLimitResult: allowed: bool reason: str = "" action: Optional[str] = None
def check_rate_limits(call_id: str) -> RateLimitResult: session = get_session(call_id) if not session: return RateLimitResult(allowed=False, reason="No active session", action="force_end_call")
if session.turn_count >= MAX_TURNS_PER_CALL: return RateLimitResult( allowed=False, reason=f"Call exceeded maximum turn limit ({MAX_TURNS_PER_CALL})", action="force_end_call", )
if session.tool_calls_this_turn >= MAX_TOOL_CALLS_PER_TURN: return RateLimitResult( allowed=False, reason=f"Too many tool calls in a single turn ({MAX_TOOL_CALLS_PER_TURN} max)", )
if session.cumulative_tokens >= MAX_TOKENS_PER_CALL: return RateLimitResult( allowed=False, reason=f"Call exceeded token budget ({MAX_TOKENS_PER_CALL})", action="force_end_call", )
return RateLimitResult(allowed=True)
def increment_tool_call(call_id: str) -> None: session = get_session(call_id) if session: session.tool_calls_this_turn += 1
def increment_turn(call_id: str, tokens_used: int = 0) -> None: session = get_session(call_id) if session: session.turn_count += 1 session.tool_calls_this_turn = 0 session.cumulative_tokens += tokens_used12345678910111213141516171819202122232425262728293031323334353637383940from dataclasses import dataclassfrom typing import Optional
from session.call_session import get_session
FORBIDDEN_ACTIONS: dict[str, list[str]] = { "voice_agent": [ "delete_customer", "access_other_customer", "view_all_calls", "generate_refund", ], "companion_agent": [ "execute_crm_write", "call_any_tool", ], "qa_agent": [ "modify_transcript", "change_eval_score", ],}
@dataclassclass ScopeResult: allowed: bool reason: str = "" inject_message: Optional[str] = None
def check_forbidden_actions(agent_type: str, tool_name: str) -> ScopeResult: forbidden = FORBIDDEN_ACTIONS.get(agent_type, []) if tool_name in forbidden: return ScopeResult( allowed=False, reason=f"Tool '{tool_name}' is forbidden for agent type '{agent_type}'", inject_message="I'm not able to perform that action.", ) return ScopeResult(allowed=True)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465from session.conversation_state import ConversationStage
# Maps each workflow stage to the set of tools permitted at that point.# The LLM never decides permissions — this is server-authoritative.## Wavvy demo tools: capture_lead, schedule_demo# Fin fintech tools (read): verify_account, send_otp, verify_otp, lookup_transaction,# search_transactions, check_payment_status,# get_account_holds, get_refund_status, get_dispute_status# Fin fintech tools (write): unlock_account, initiate_refund, raise_dispute, report_fraud# Always available: escalate_to_human only# cancel_escalation is stage-scoped (TOOL_EXECUTION, ESCALATION) — not always-on
_FIN_READ_TOOLS = { "verify_account", "send_otp", "verify_otp", "lookup_transaction", "search_transactions", "check_payment_status", "get_account_holds", "get_refund_status", "get_dispute_status",}
_FIN_WRITE_TOOLS = { "unlock_account", "initiate_refund", "raise_dispute", "report_fraud",}
TOOL_PERMISSIONS: dict[ConversationStage, set[str]] = { ConversationStage.GREETING: { "capture_lead", "verify_account", "escalate_to_human", }, ConversationStage.DISCOVERY: { "capture_lead", "verify_account", "escalate_to_human", }, ConversationStage.VERIFICATION: { "capture_lead", "schedule_demo", *_FIN_READ_TOOLS, "escalate_to_human", }, ConversationStage.TOOL_EXECUTION: { "capture_lead", "schedule_demo", *_FIN_READ_TOOLS, *_FIN_WRITE_TOOLS, "escalate_to_human", "cancel_escalation", }, ConversationStage.ESCALATION: { "escalate_to_human", "cancel_escalation", }, ConversationStage.RESOLUTION: { "escalate_to_human", }, ConversationStage.ENDED: set(),}
def is_tool_allowed( stage: ConversationStage, tool_name: str, escalated: bool = False,) -> tuple[bool, str]: """Returns (allowed, reason). Called before every tool execution.""" if escalated and tool_name != "escalate_to_human": return False, "Session is escalated — only escalate_to_human is permitted" allowed = TOOL_PERMISSIONS.get(stage, set()) if tool_name in allowed: return True, "" return False, ( f"Tool '{tool_name}' is not permitted in stage '{stage.value}'." )1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465import refrom dataclasses import dataclass
@dataclassclass ValidationResult: valid: bool error: str = ""
TOOL_VALIDATORS: dict[str, dict[str, any]] = { "lookup_account": { "identifier_type": lambda v: v in {"phone", "order_id"}, "identifier": lambda v: len(str(v)) > 5, }, "send_2fa": { "customer_id": lambda v: len(str(v)) > 0, }, "verify_2fa": { "customer_id": lambda v: len(str(v)) > 0, "code": lambda v: re.match(r"^\d{6}$", str(v)) is not None, }, "update_record": { "customer_id": lambda v: len(str(v)) > 0, "field": lambda v: v in {"address", "email", "phone", "account_type"}, "value": lambda v: 0 < len(str(v)) < 500, }, "confirm_action": { "customer_id": lambda v: len(str(v)) > 0, "action_type": lambda v: v in {"refund", "cancel_order", "update_plan", "close_ticket"}, "action_summary": lambda v: len(str(v)) > 10, }, "escalate_to_human": { "reason": lambda v: v in {"low_sentiment", "customer_request", "auth_failure", "complex_issue"}, "transcript_summary": lambda v: len(str(v)) > 10, }, "get_order_status": { "customer_id": lambda v: len(str(v)) > 0, }, "get_call_history": { "customer_id": lambda v: len(str(v)) > 0, }, "crm_search": { "query": lambda v: len(str(v)) > 0, "customer_id": lambda v: len(str(v)) > 0, },}
def validate_tool_args(tool_name: str, args: dict) -> ValidationResult: validators = TOOL_VALIDATORS.get(tool_name, {}) for field_name, validator in validators.items(): if field_name in args: try: if not validator(args[field_name]): return ValidationResult( valid=False, error=f"Invalid value for '{field_name}' in tool '{tool_name}'", ) except Exception: return ValidationResult( valid=False, error=f"Validation error for '{field_name}' in tool '{tool_name}'", ) return ValidationResult(valid=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152# Wavvy LiveKit Agents worker — Kubernetes Deployment + HPA## Scaling model:# Each worker Pod handles N concurrent calls (load_threshold=0.65 → ~8–12 calls per Pod).# HPA scales on CPU utilization as a proxy for call load.# LiveKit Cloud dispatches jobs round-robin across all registered workers.## To deploy:# kubectl apply -f worker-deployment.yaml## Environment:# All secrets come from the wavvy-secrets Secret object.# See k8s/secrets.yaml.example for the required keys.
---apiVersion: apps/v1kind: Deploymentmetadata: name: wavvy-worker labels: app: wavvy-worker component: voice-pipelinespec: replicas: 2 # minimum; HPA scales up from here selector: matchLabels: app: wavvy-worker template: metadata: labels: app: wavvy-worker component: voice-pipeline spec: terminationGracePeriodSeconds: 330 # drain_timeout(300s) + 30s buffer
containers: - name: worker image: wavvy-backend:latest # replace with your registry image command: - python - -m - voice.agent_worker - start resources: requests: cpu: "500m" memory: "768Mi" limits: cpu: "2000m" memory: "1536Mi" # headroom above job_memory_limit_mb=512
env: # LiveKit - name: LIVEKIT_URL valueFrom: secretKeyRef: name: wavvy-secrets key: LIVEKIT_URL - name: LIVEKIT_API_KEY valueFrom: secretKeyRef: name: wavvy-secrets key: LIVEKIT_API_KEY - name: LIVEKIT_API_SECRET valueFrom: secretKeyRef: name: wavvy-secrets key: LIVEKIT_API_SECRET
# STT / LLM / TTS - name: DEEPGRAM_API_KEY valueFrom: secretKeyRef: name: wavvy-secrets key: DEEPGRAM_API_KEY - name: ELEVENLABS_API_KEY valueFrom: secretKeyRef: name: wavvy-secrets key: ELEVENLABS_API_KEY - name: ELEVENLABS_VOICE_ID valueFrom: secretKeyRef: name: wavvy-secrets key: ELEVENLABS_VOICE_ID
# QA agent - name: OPENAI_API_KEY valueFrom: secretKeyRef: name: wavvy-secrets key: OPENAI_API_KEY
# Database - name: DATABASE_URL valueFrom: secretKeyRef: name: wavvy-secrets key: DATABASE_URL
# Worker → FastAPI IPC (internal cluster DNS) - name: BACKEND_INTERNAL_URL value: "http://wavvy-api-service:8000"
- name: ENVIRONMENT value: "production"
# Graceful shutdown: SIGTERM triggers LiveKit Agents drain (300s window) lifecycle: preStop: exec: command: ["sleep", "5"] # give k8s time to remove from endpoints
livenessProbe: exec: command: ["python", "-c", "import livekit.agents; print('ok')"] initialDelaySeconds: 30 periodSeconds: 60 failureThreshold: 3
---apiVersion: autoscaling/v2kind: HorizontalPodAutoscalermetadata: name: wavvy-worker-hpaspec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: wavvy-worker minReplicas: 2 maxReplicas: 20 metrics: - type: Resource resource: name: cpu target: type: Utilization averageUtilization: 60 # scale out before hitting load_threshold=0.65 behavior: scaleUp: stabilizationWindowSeconds: 30 # react fast to call spikes policies: - type: Pods value: 2 periodSeconds: 30 scaleDown: stabilizationWindowSeconds: 300 # drain_timeout — don't kill workers mid-call policies: - type: Pods value: 1 periodSeconds: 120123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271"""Parse PDF, DOCX, TXT, and MD files into chunks.
Chunking strategies: .md — section-aware: split on ## boundaries first, token-split within each section. No cross-section overlap. Heading text is kept as the first line of each chunk. rest — recursive strategy: coarsest separator first, recurse on oversized pieces, one-segment overlap between chunks.
Heading extraction always runs on the RAW source text so ## markers are visible."""import refrom pathlib import Path
import tiktoken
TOKENIZER = tiktoken.get_encoding("cl100k_base")CHUNK_TOKENS = 400SEPARATORS = ["\n\n\n", "\n\n", "\n", ". ", "! ", "? ", " "]
# ── Parsing ───────────────────────────────────────────────────────────────────
def parse_file(path: str | Path) -> str: """Return the full text of a document (markdown syntax stripped for non-MD).""" path = Path(path) suffix = path.suffix.lower() if suffix == ".pdf": return _parse_pdf(path) elif suffix in (".docx", ".doc"): return _parse_docx(path) elif suffix == ".txt": return path.read_text(encoding="utf-8", errors="replace") elif suffix == ".md": raw = path.read_text(encoding="utf-8", errors="replace") return _strip_md(raw) else: raise ValueError(f"Unsupported file type: {suffix}")
def _parse_pdf(path: Path) -> str: import fitz doc = fitz.open(str(path)) pages = [page.get_text("text").strip() for page in doc if page.get_text("text").strip()] doc.close() return "\n\n".join(pages)
def _parse_docx(path: Path) -> str: from docx import Document doc = Document(str(path)) paragraphs = [p.text.strip() for p in doc.paragraphs if p.text.strip()] return "\n\n".join(paragraphs)
def _strip_md(text: str) -> str: """Strip markdown syntax to plain readable text. Keep heading text (strip # marker only).""" # Fenced code blocks — keep content text = re.sub(r'```[^\n]*\n(.*?)```', r'\1', text, flags=re.DOTALL) text = re.sub(r'`([^`]+)`', r'\1', text) # Headings — strip # marker, keep text text = re.sub(r'^#{1,6}\s+', '', text, flags=re.MULTILINE) # Bold / italic text = re.sub(r'\*{1,3}([^*]+)\*{1,3}', r'\1', text) text = re.sub(r'_{1,3}([^_]+)_{1,3}', r'\1', text) # Links — keep display text text = re.sub(r'\[([^\]]+)\]\([^)]+\)', r'\1', text) # Images text = re.sub(r'!\[[^\]]*\]\([^)]+\)', '', text) # HTML tags text = re.sub(r'<[^>]+>', '', text) # Horizontal rules text = re.sub(r'^[-*_]{3,}\s*$', '', text, flags=re.MULTILINE) # Blockquote markers text = re.sub(r'^>\s?', '', text, flags=re.MULTILINE) # Collapse excess blank lines text = re.sub(r'\n{3,}', '\n\n', text) return text.strip()
# ── Chunking ──────────────────────────────────────────────────────────────────
def chunk_text(text: str, is_markdown: bool = False, raw_md: str | None = None) -> list[str]: """ For markdown: section-aware split on ## boundaries, no cross-section overlap. For other formats: recursive split with one-segment overlap. """ if is_markdown and raw_md: return _chunk_markdown(raw_md) return _recursive_split(text.strip(), SEPARATORS)
def _chunk_markdown(raw: str) -> list[str]: """ Split markdown into one chunk per ## section. Each chunk starts with the section heading (plain text) so the embedding model knows what topic the chunk covers. If a section exceeds CHUNK_TOKENS it is split further (no overlap). """ # Split at every H1/H2/H3 boundary; lookahead keeps the heading with its section sections = re.split(r'(?=^#{1,3} )', raw, flags=re.MULTILINE)
chunks: list[str] = [] for section in sections: section = section.strip() if not section: continue clean = _strip_md(section).strip() if not clean: continue tokens = len(TOKENIZER.encode(clean)) if tokens <= CHUNK_TOKENS: chunks.append(clean) else: # Section too long — split recursively but without overlap chunks.extend(_recursive_split_no_overlap(clean, SEPARATORS))
return [c.strip() for c in chunks if c.strip()]
def _recursive_split(text: str, separators: list[str]) -> list[str]: """Recursive chunker with one-segment overlap (used for PDF/DOCX/TXT).""" if not text.strip(): return [] if len(TOKENIZER.encode(text)) <= CHUNK_TOKENS: return [text] if not separators: return _hard_split(text)
sep, rest = separators[0], separators[1:] parts = [p for p in text.split(sep) if p.strip()]
if len(parts) == 1: return _recursive_split(text, rest)
chunks: list[str] = [] current: list[str] = [] current_tokens = 0
for part in parts: pt = len(TOKENIZER.encode(part)) if current_tokens + pt > CHUNK_TOKENS and current: merged = sep.join(current) if len(TOKENIZER.encode(merged)) > CHUNK_TOKENS: chunks.extend(_recursive_split(merged, rest)) else: chunks.append(merged) # One-segment overlap current = [current[-1]] current_tokens = len(TOKENIZER.encode(current[0])) current.append(part) current_tokens += pt
if current: merged = sep.join(current) if len(TOKENIZER.encode(merged)) > CHUNK_TOKENS: chunks.extend(_recursive_split(merged, rest)) else: chunks.append(merged)
return [c.strip() for c in chunks if c.strip()]
def _recursive_split_no_overlap(text: str, separators: list[str]) -> list[str]: """Same as _recursive_split but no overlap — used for oversized markdown sections.""" if not text.strip(): return [] if len(TOKENIZER.encode(text)) <= CHUNK_TOKENS: return [text] if not separators: return _hard_split(text)
sep, rest = separators[0], separators[1:] parts = [p for p in text.split(sep) if p.strip()]
if len(parts) == 1: return _recursive_split_no_overlap(text, rest)
chunks: list[str] = [] current: list[str] = [] current_tokens = 0
for part in parts: pt = len(TOKENIZER.encode(part)) if current_tokens + pt > CHUNK_TOKENS and current: merged = sep.join(current) if len(TOKENIZER.encode(merged)) > CHUNK_TOKENS: chunks.extend(_recursive_split_no_overlap(merged, rest)) else: chunks.append(merged) current, current_tokens = [], 0 # no overlap current.append(part) current_tokens += pt
if current: merged = sep.join(current) if len(TOKENIZER.encode(merged)) > CHUNK_TOKENS: chunks.extend(_recursive_split_no_overlap(merged, rest)) else: chunks.append(merged)
return [c.strip() for c in chunks if c.strip()]
def _hard_split(text: str) -> list[str]: words = text.split() chunks: list[str] = [] current: list[str] = [] current_tokens = 0 for word in words: wt = len(TOKENIZER.encode(word)) if current_tokens + wt > CHUNK_TOKENS and current: chunks.append(" ".join(current)) current, current_tokens = [], 0 current.append(word) current_tokens += wt if current: chunks.append(" ".join(current)) return chunks
# ── Heading extraction ────────────────────────────────────────────────────────
_HEADING_PATTERNS = [ r'^#{1,6}\s+.{3,80}$', # ## Markdown Heading r'^(?:Section|Article|Chapter|Part)\s+[\d.]+.*', # Section 5.2 ... r'^\d+\.\s+[A-Z][^\n]{4,60}$', # 5. Some Term r'^\d+\.\d+\s+[A-Z][^\n]{4,60}$', # 5.2 Subsection r'^[A-Z][A-Z\s\-]{8,60}$', # ALL CAPS HEADING]
def extract_headings(text: str) -> list[str]: """ Extract section headings from document text. Pass raw markdown text (with ## markers) for best results. Returns up to 20 unique headings cleaned of markdown syntax. """ headings: list[str] = [] for line in text.splitlines(): line = line.strip() if 5 <= len(line) <= 82 and any(re.match(p, line) for p in _HEADING_PATTERNS): # Strip markdown # markers for display clean = re.sub(r'^#{1,6}\s+', '', line).strip() if clean: headings.append(clean) return list(dict.fromkeys(headings))[:20]
# ── Public API ────────────────────────────────────────────────────────────────
def parse_and_chunk(path: str | Path) -> tuple[str, list[str]]: """ Returns (raw_or_full_text, chunks).
For markdown: raw_text is the original file content (## markers intact) so that extract_headings() can detect section headings correctly. Chunks are section-aware (split on ## boundaries, no overlap).
For other formats: raw_text is the stripped plain text; chunks use recursive splitting with one-segment overlap. """ path = Path(path) if path.suffix.lower() == ".md": raw = path.read_text(encoding="utf-8", errors="replace") chunks = _chunk_markdown(raw) return raw, chunks # return raw so caller can extract ## headings else: text = parse_file(path) chunks = _recursive_split(text.strip(), SEPARATORS) return text, chunks1234567891011121314151617181920212223242526272829303132333435363738394041424344"""Local embeddings via sentence-transformers all-MiniLM-L6-v2.Zero API cost. 384-dim vectors. Runs on CPU in a thread pool so theasync event loop is never blocked."""import asyncioimport functoolsimport loggingfrom typing import Optional
logger = logging.getLogger(__name__)
_model = NoneEMBED_MODEL = "all-MiniLM-L6-v2"EMBED_DIM = 384
def init_embeddings(_openai_client=None) -> None: """Load the local model once at startup. Signature compatible with old init_embeddings(openai_client).""" global _model from sentence_transformers import SentenceTransformer logger.info(f"Loading local embedding model: {EMBED_MODEL}") _model = SentenceTransformer(EMBED_MODEL) logger.info(f"Embeddings initialized: {EMBED_MODEL} ({EMBED_DIM}-dim, local, zero API cost)")
async def embed_texts(texts: list[str]) -> list[list[float]]: """Embed a batch of texts. Returns list of float vectors. Non-blocking.""" if not _model: raise RuntimeError("embeddings not initialized — call init_embeddings() first") if not texts: return [] loop = asyncio.get_event_loop() vectors = await loop.run_in_executor( None, functools.partial(_model.encode, texts, convert_to_numpy=True, show_progress_bar=False) ) return vectors.tolist()
async def embed_single(text: str) -> list[float]: """Embed a single text string.""" results = await embed_texts([text]) return results[0]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596"""KB Manager — Hybrid RAG: Dense + BM25 + Graph (entity index) fused via RRF.
Collections: kb_collection — policy/FAQ chunks calls_collection — past call transcript chunks (customer_id tagged)
Retrieval pipeline: 1. Dense — ChromaDB cosine (all-MiniLM-L6-v2, 384-dim, local) 2. BM25 — BM25Okapi in-memory (rank-bm25) 3. Graph — entity inverted index (regex, zero LLM cost) 4. RRF — Reciprocal Rank Fusion, k=60, top-N final result"""import reimport uuidimport loggingimport numpy as npfrom pathlib import Pathfrom typing import Optional
from knowledge.document_parser import parse_and_chunk, extract_headings, TOKENIZERfrom knowledge.embeddings import embed_texts, embed_single
logger = logging.getLogger(__name__)
# ── Module state ──────────────────────────────────────────────────────────────
_kb_collection = None_calls_collection = None_collections: dict = {} # name → ChromaDB collection object
_bm25_index = None_bm25_corpus: list[dict] = [] # [{id, text, metadata}]_entity_index: dict[str, list[str]] = {} # entity → [chunk_id, ...]_entity_pair_index: dict[str, list[str]] = {} # "e1+e2" → [chunk_id, ...] (sorted, multi-hop)_doc_headings: dict[str, list[str]] = {} # doc_id → [heading, ...]
CALL_DISTANCE_THRESHOLD = 0.5
# ── Entity patterns for Graph RAG lite ───────────────────────────────────────
_ENTITY_PATTERNS = [ re.compile(r'\b[A-Z][a-z]+(?:[A-Z][a-z]+)+\b'), # CamelCase: LiveKit, Pipecat re.compile(r'\$[\d,]+(?:\.\d{2})?'), # $5.00, $100 re.compile(r'\b\d+\s*(?:days?|hours?|minutes?|weeks?)\b', re.I), # 30 days re.compile(r'(?:Section|Article|Clause)\s+[\d.]+', re.I), # Section 5.2 re.compile(r'\b\d+(?:\.\d+)?%'), # 15%, 3.5%]
def _extract_entities(text: str) -> list[str]: entities = set() for pattern in _ENTITY_PATTERNS: for match in pattern.findall(text): entities.add(match.lower().strip()) return list(entities)
# ── Init ──────────────────────────────────────────────────────────────────────
def init_kb_manager(kb_col, calls_col, _openai_client=None, collections_dict: dict | None = None) -> None: global _kb_collection, _calls_collection, _collections _kb_collection = kb_col _calls_collection = calls_col if collections_dict: _collections = collections_dict # Always register the default collection by name if kb_col is not None: _collections.setdefault("kb_collection", kb_col) _rebuild_indexes()
# ── Index rebuild (BM25 + entity) ────────────────────────────────────────────
def _rebuild_indexes() -> None: global _bm25_index, _bm25_corpus, _entity_index, _entity_pair_index if _kb_collection is None: return try: from rank_bm25 import BM25Okapi
# Gather chunks from ALL registered collections so BM25 + entity # index covers every uploaded document regardless of which collection it lives in. all_cols = list(_collections.values()) if _collections else [_kb_collection] seen_ids: set[str] = set() ids, docs, metas = [], [], [] for col in all_cols: results = col.get(include=["documents", "metadatas"]) for i, d, m in zip( results.get("ids") or [], results.get("documents") or [], results.get("metadatas") or [], ): if i not in seen_ids: seen_ids.add(i) ids.append(i); docs.append(d); metas.append(m)
_bm25_corpus = [{"id": i, "text": d, "metadata": m} for i, d, m in zip(ids, docs, metas)]
if docs: tokenized = [d.lower().split() for d in docs] _bm25_index = BM25Okapi(tokenized) else: _bm25_index = None
# Entity inverted index + pair index (multi-hop, LightRAG-lite) _entity_index = {} _entity_pair_index = {} for chunk_id, doc in zip(ids, docs): entities = _extract_entities(doc) for entity in entities: _entity_index.setdefault(entity, []).append(chunk_id) # Store all co-occurring entity pairs — enables multi-hop retrieval # e.g. chunk has both "dashpass" + "refund" → "dashpass+refund" → chunk_id sorted_entities = sorted(set(entities)) for i in range(len(sorted_entities)): for j in range(i + 1, len(sorted_entities)): pair_key = f"{sorted_entities[i]}+{sorted_entities[j]}" _entity_pair_index.setdefault(pair_key, []).append(chunk_id)
logger.info( f"Indexes rebuilt: {len(docs)} chunks, " f"{len(_entity_index)} entities, {len(_entity_pair_index)} entity pairs" ) except Exception as e: logger.error(f"Index rebuild failed: {e}")
# ── RRF fusion ────────────────────────────────────────────────────────────────
def _rrf_fusion( hit_lists: list[list[dict]], k: int = 60, n: int = 3, k_per_list: list[int] | None = None,) -> list[dict]: """ hit_lists: each inner list is a ranked list of hits. Each hit must have "chunk_id". Optional: via_dense, via_bm25, via_entity. k_per_list: per-list k override — lower k = higher contribution for same rank. Entity hits use k=40 (~1.5× boost) to reflect their precision advantage. Returns top-n by RRF score with retrieval attribution. """ scores: dict[str, float] = {} registry: dict[str, dict] = {}
for list_idx, hits in enumerate(hit_lists): effective_k = (k_per_list[list_idx] if k_per_list and list_idx < len(k_per_list) else k) for rank, h in enumerate(hits): cid = h["chunk_id"] scores[cid] = scores.get(cid, 0.0) + 1.0 / (effective_k + rank + 1) if cid not in registry: registry[cid] = dict(h) else: # Merge attribution flags for flag in ("via_dense", "via_bm25", "via_entity"): if h.get(flag): registry[cid][flag] = True
top_ids = sorted(scores, key=lambda x: scores[x], reverse=True)[:n] results = [] for cid in top_ids: h = registry[cid] via_dense = h.get("via_dense", False) via_bm25 = h.get("via_bm25", False) via_entity = h.get("via_entity", False)
if via_dense and (via_bm25 or via_entity): retrieval = "hybrid" elif via_dense: retrieval = "dense" elif via_entity: retrieval = "graph" else: retrieval = "bm25"
results.append({ **h, "rrf_score": round(scores[cid], 4), "retrieval": retrieval, }) return results
# ── Upload & Index ────────────────────────────────────────────────────────────
async def ingest_document( file_path: str | Path, filename: str, file_type: str, category: str = "general", doc_id: str | None = None, collection_name: str | None = None,) -> tuple[str, int]: # Use named collection if specified; fall back to default kb_collection target_col = _kb_collection if collection_name and collection_name in _collections: target_col = _collections[collection_name] if target_col is None: raise RuntimeError("kb_manager not initialized")
doc_id = doc_id or str(uuid.uuid4()) logger.info(f"Ingesting {filename} (doc_id={doc_id})")
text, chunks = parse_and_chunk(file_path) if not chunks: logger.warning(f"No chunks produced for {filename}") return doc_id, 0
# Store headings for suggested questions headings = extract_headings(text) _doc_headings[doc_id] = headings logger.info(f"Extracted {len(headings)} headings from {filename}")
embeddings = await embed_texts(chunks)
ids = [f"{doc_id}__chunk_{i}" for i in range(len(chunks))] metadatas = [ { "doc_id": doc_id, "filename": filename, "file_type": file_type, "category": category, "chunk_index": i, "type": "kb", } for i in range(len(chunks)) ]
target_col.add(ids=ids, embeddings=embeddings, documents=chunks, metadatas=metadatas) logger.info(f"Stored {len(chunks)} chunks for {filename}")
# Rebuild in-memory indexes _rebuild_indexes()
return doc_id, len(chunks)
async def delete_document(doc_id: str) -> int: if _kb_collection is None: return 0 all_cols = list(_collections.values()) if _collections else [_kb_collection] total = 0 for col in all_cols: results = col.get(where={"doc_id": doc_id}) ids = results.get("ids", []) if ids: col.delete(ids=ids) total += len(ids) _doc_headings.pop(doc_id, None) _rebuild_indexes() return total
# ── Query — hybrid RRF ────────────────────────────────────────────────────────
async def search_kb( query: str, n_results: int = 3, collections: list[str] | None = None,) -> list[dict]: """ Hybrid search: Dense + BM25 + Graph entity index, fused via RRF. No hard distance threshold — top-N by RRF score.
collections: list of collection names to search. Defaults to get_config().kb_collections if not provided. """ if _kb_collection is None: return []
if collections is None: try: from config_loader import get_config collections = list(get_config().kb_collections) except Exception: collections = []
# Resolve all ChromaDB collections to search — query every listed collection # that exists and has content, then merge dense hits before RRF fusion. active_cols = [_collections[name] for name in collections if name in _collections] if not active_cols: active_cols = [_kb_collection] if _kb_collection is not None else [] if not active_cols: return []
fetch_n = n_results * 3 # fetch more from each source before fusion
# Dense: search each collection separately and merge (dedup by chunk_id) seen_chunk_ids: set[str] = set() dense_hits: list[dict] = [] for col in active_cols: if col.count() == 0: continue for hit in await _search_dense(query, fetch_n, collection=col): if hit["chunk_id"] not in seen_chunk_ids: seen_chunk_ids.add(hit["chunk_id"]) dense_hits.append(hit)
bm25_hits = _search_bm25(query, fetch_n) entity_hits = _search_entity(query, fetch_n)
# Entity hits use k=40 (≈1.5× boost vs k=60) — precision-weighted per LightRAG findings fused = _rrf_fusion( [dense_hits, bm25_hits, entity_hits], k=60, n=n_results, k_per_list=[60, 60, 40], )
return [ { "content": h["content"], "source": h.get("source", h.get("metadata", {}).get("filename", "KB")), "category": h.get("metadata", {}).get("category", "general"), "relevance": h["rrf_score"], "rrf_score": h["rrf_score"], "retrieval": h["retrieval"], "doc_id": h.get("metadata", {}).get("doc_id", ""), } for h in fused ]
async def _search_dense(query: str, n: int, collection=None) -> list[dict]: col = collection if collection is not None else _kb_collection if col is None: return [] embedding = await embed_single(query) try: results = col.query( query_embeddings=[embedding], n_results=min(n, max(1, col.count())), include=["documents", "metadatas", "distances"], ) except Exception as exc: logger.warning(f"Dense KB query failed: {exc}") return []
hits = [] ids_row = results.get("ids", [[]])[0] # always returned by ChromaDB docs_row = results.get("documents", [[]])[0] metas_row = results.get("metadatas", [[]])[0] dists_row = results.get("distances", [[]])[0] for cid, doc, meta, dist in zip(ids_row, docs_row, metas_row, dists_row): hits.append({ "chunk_id": cid, "content": doc, "metadata": meta, "source": meta.get("filename", "KB"), "cosine_distance": dist, "via_dense": True, }) return hits
def _search_bm25(query: str, n: int) -> list[dict]: if _bm25_index is None or not _bm25_corpus: return [] tokenized_query = query.lower().split() scores = _bm25_index.get_scores(tokenized_query) ranked = sorted(range(len(scores)), key=lambda i: scores[i], reverse=True)[:n] hits = [] for rank_idx in ranked: if scores[rank_idx] <= 0: continue entry = _bm25_corpus[rank_idx] hits.append({ "chunk_id": entry["id"], "content": entry["text"], "metadata": entry["metadata"], "source": entry["metadata"].get("filename", "KB"), "bm25_score": float(scores[rank_idx]), "via_bm25": True, }) return hits
def _search_entity(query: str, n: int) -> list[dict]: if not _entity_index: return [] query_entities = _extract_entities(query) if not query_entities: return []
chunk_score: dict[str, int] = {}
# Single-entity hits for entity in query_entities: for cid in _entity_index.get(entity, []): chunk_score[cid] = chunk_score.get(cid, 0) + 1
# Entity pair hits — multi-hop: "dashpass + refund" in same chunk scores higher sorted_q_entities = sorted(set(query_entities)) for i in range(len(sorted_q_entities)): for j in range(i + 1, len(sorted_q_entities)): pair_key = f"{sorted_q_entities[i]}+{sorted_q_entities[j]}" for cid in _entity_pair_index.get(pair_key, []): chunk_score[cid] = chunk_score.get(cid, 0) + 2 # pair match worth 2×
# Build a fast id→entry lookup to avoid O(n²) scan corpus_map = {e["id"]: e for e in _bm25_corpus}
top_ids = sorted(chunk_score, key=lambda x: chunk_score[x], reverse=True)[:n] hits = [] for cid in top_ids: entry = corpus_map.get(cid) if entry: hits.append({ "chunk_id": cid, "content": entry["text"], "metadata": entry["metadata"], "source": entry["metadata"].get("filename", "KB"), "entity_score": chunk_score[cid], "via_entity": True, }) return hits
# ── Call transcript indexing ──────────────────────────────────────────────────
async def search_calls(query: str, customer_id: str, n_results: int = 2) -> list[dict]: if _calls_collection is None: return [] embedding = await embed_single(query) try: count = _calls_collection.count() if count == 0: return [] results = _calls_collection.query( query_embeddings=[embedding], n_results=min(n_results, count), where={"customer_id": customer_id}, include=["documents", "metadatas", "distances"], ) except Exception as exc: logger.warning(f"Calls query failed: {exc}") return []
hits = [] for doc, meta, dist in zip( results.get("documents", [[]])[0], results.get("metadatas", [[]])[0], results.get("distances", [[]])[0], ): if dist < CALL_DISTANCE_THRESHOLD: hits.append({ "content": doc, "source": f"Past call {meta.get('call_id', '')[:8]}", "relevance": round(1 - dist, 3), "call_id": meta.get("call_id", ""), }) return hits
async def index_call_transcript(call_id: str, customer_id: str, transcript_lines: list[dict]) -> None: if _calls_collection is None: return full_text = "\n".join( f"[{line.get('speaker','')}]: {line.get('content', line.get('text',''))}" for line in transcript_lines if line.get("content") or line.get("text") ) if not full_text.strip(): return
from knowledge.document_parser import chunk_text chunks = chunk_text(full_text) if not chunks: return
embeddings = await embed_texts(chunks) ids = [f"{call_id}__chunk_{i}" for i in range(len(chunks))] metadatas = [{"call_id": call_id, "customer_id": customer_id, "chunk_index": i, "type": "call"} for i in range(len(chunks))] _calls_collection.add(ids=ids, embeddings=embeddings, documents=chunks, metadatas=metadatas) logger.info(f"Indexed {len(chunks)} transcript chunks for call {call_id}")
# ── Inspector functions ───────────────────────────────────────────────────────
def get_doc_chunks(doc_id: str) -> list[dict]: """Return all chunks for a document, sorted by chunk_index.""" if _kb_collection is None: return [] try: all_cols = list(_collections.values()) if _collections else [_kb_collection] all_docs, all_metas = [], [] for col in all_cols: results = col.get( where={"doc_id": doc_id}, include=["documents", "metadatas"], ) all_docs.extend(results.get("documents", [])) all_metas.extend(results.get("metadatas", [])) pairs = list(zip(all_docs, all_metas)) pairs.sort(key=lambda x: x[1].get("chunk_index", 0)) return [ { "index": meta.get("chunk_index", i), "content": doc, "tokens": len(TOKENIZER.encode(doc)), "category": meta.get("category", "general"), } for i, (doc, meta) in enumerate(pairs) ] except Exception as e: logger.warning(f"get_doc_chunks failed: {e}") return []
def get_chunk_similarity(doc_id: str) -> dict: """Return N×N cosine similarity matrix for all chunks of a document.""" if _kb_collection is None: return {"chunks": [], "matrix": []} try: all_cols = list(_collections.values()) if _collections else [_kb_collection] embeddings_all, docs_all, metas_all = [], [], [] for col in all_cols: results = col.get( where={"doc_id": doc_id}, include=["embeddings", "documents", "metadatas"], ) emb = results.get("embeddings") if emb is not None: embeddings_all.extend(emb) docs_all.extend(results.get("documents") or []) metas_all.extend(results.get("metadatas") or [])
embeddings, docs, metas = embeddings_all, docs_all, metas_all
if len(embeddings) < 2: return {"chunks": [], "matrix": []}
# Sort by chunk_index combined = sorted(zip(embeddings, docs, metas), key=lambda x: x[2].get("chunk_index", 0)) embeddings, docs, _ = zip(*combined)
E = np.array(embeddings) norms = np.linalg.norm(E, axis=1, keepdims=True) norms = np.where(norms == 0, 1e-8, norms) # avoid div-by-zero E_norm = E / norms sim_matrix = (E_norm @ E_norm.T).tolist()
previews = [ {"index": i, "preview": doc[:80]} for i, doc in enumerate(docs) ] return {"chunks": previews, "matrix": sim_matrix} except Exception as e: logger.warning(f"get_chunk_similarity failed: {e}") return {"chunks": [], "matrix": []}
def get_suggested_questions(doc_id: str) -> list[str]: """Return headings extracted at ingest time for the given document.""" return _doc_headings.get(doc_id, [])
# ── List documents ────────────────────────────────────────────────────────────
def list_documents() -> list[dict]: if _kb_collection is None: return [] try: results = _kb_collection.get(include=["metadatas"]) metas = results.get("metadatas", []) seen: dict[str, dict] = {} for meta in metas: doc_id = meta.get("doc_id", "") if doc_id and doc_id not in seen: seen[doc_id] = { "doc_id": doc_id, "filename": meta.get("filename", ""), "file_type": meta.get("file_type", ""), "category": meta.get("category", "general"), } return list(seen.values()) except Exception as exc: logger.warning(f"list_documents failed: {exc}") return []
def get_chunk_count(doc_id: str) -> int: if _kb_collection is None: return 0 try: all_cols = list(_collections.values()) if _collections else [_kb_collection] total = 0 for col in all_cols: results = col.get(where={"doc_id": doc_id}) total += len(results.get("ids", [])) return total except Exception: return 01234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677"""Seed fin_support KB collection from backend/knowledge/seed_docs/fin/*.md
Usage (from backend/): python -m knowledge.seed
kb_collection is reserved for user-uploaded policies via the Supervisor GUI."""from __future__ import annotations
import asyncioimport sysfrom pathlib import Path
async def main() -> None: # Bootstrap: DB engine + OpenAI client + ChromaDB + kb_manager from database import reinit_engine reinit_engine()
import chromadb from openai import AsyncOpenAI from config import settings from knowledge import embeddings as embeddings_module from knowledge import kb_manager as kb_manager_module
openai_client = AsyncOpenAI(api_key=settings.openai_api_key) embeddings_module.init_embeddings(openai_client)
chroma_client = chromadb.PersistentClient( path=settings.chroma_persist_dir, settings=chromadb.Settings(anonymized_telemetry=False), ) kb_collection = chroma_client.get_or_create_collection("kb_collection") fin_collection = chroma_client.get_or_create_collection("fin_support") calls_collection = chroma_client.get_or_create_collection("calls_collection")
kb_manager_module.init_kb_manager( kb_col=kb_collection, calls_col=calls_collection, _openai_client=openai_client, collections_dict={"kb_collection": kb_collection, "fin_support": fin_collection}, )
fin_dir = Path(__file__).parent / "seed_docs" / "fin" fin_docs = sorted(fin_dir.glob("*.md")) if not fin_docs: print("ERROR: No .md files found in seed_docs/fin/ — nothing to seed.") sys.exit(1)
print(f"\nSeeding {len(fin_docs)} Fin docs → fin_support:")
# Clear existing chunks so re-seeding is idempotent existing = fin_collection.count() if existing > 0: all_ids = fin_collection.get(include=[])["ids"] fin_collection.delete(ids=all_ids) print(f" (cleared {existing} existing chunks)")
total_chunks = 0 for doc_path in fin_docs: doc_id, n_chunks = await kb_manager_module.ingest_document( file_path=doc_path, filename=doc_path.name, file_type="md", category="fin_support", collection_name="fin_support", ) print(f" [{total_chunks + 1}..{total_chunks + n_chunks}] {doc_path.name} ({n_chunks} chunks)") total_chunks += n_chunks
print(f"\nKB seed complete — {total_chunks} chunks in fin_support.") print("Note: kb_collection is reserved for user-uploaded policies via the Supervisor GUI.")
if __name__ == "__main__": asyncio.run(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418# Wavvy Demo KB — Archived
> **This file is an archive.** These documents were the original Wavvy product KB used during> the Wavvy self-demo phase. They are no longer seeded into> any ChromaDB collection. Kept here for reference only.>> Active KB is in `../fin/` — fintech support SOPs for the Fin agent.
---
<!-- SOURCE: wavvy_overview.md -->
# Wavvy — Open-Source CCaaS Platform
## What Is Wavvy?
Wavvy is an open-source Contact Center as a Service (CCaaS) platform. Any business can integrate Wavvy to deploy AI-powered customer workflows — voice AI agents, escalation routing, QA scoring, and supervisor analytics — within hours, not months.
Wavvy platform demonstrates how modern AI can power enterprise-grade contact centers using fully open-source infrastructure.
## The Core Idea
The demo you are experiencing right now IS Wavvy in action. The voice AI you are speaking with, the real-time knowledge retrieval happening in the background, the escalation handoff to a human agent — all of this is exactly what your contact center would provide to your customers after integrating Wavvy.
**The pitch:** "This call is Wavvy. What you are experiencing right now — you can deploy this for your contact center today."
## Four Applications, One Backend
Wavvy consists of four applications sharing a single FastAPI backend:
**App 1 — Landing Page (wavvy.vercel.app)**Public marketing page with a pulsing call button. Clicking it opens a voice call modal where visitors speak directly to the Wavvy AI. This is the customer-facing layer of any CCaaS deployment.
**App 2 — Agent Desktop (wavvy-agent.vercel.app)**Human agents receive escalated calls here. The Companion AI panel pre-loads context from the Voice AI conversation, shows a checklist of talking points, and surfaces relevant KB snippets. Agents pick up exactly where the AI left off.
**App 3 — Supervisor Dashboard (wavvy-supervisor.vercel.app)**Quality assurance, live call monitoring, knowledge base management, agent coaching packs, and analytics. Supervisors see every call in real time and receive automated QA scores within seconds of call completion.
**Backend — FastAPI (Railway)**REST API and WebSocket endpoints. Handles LiveKit room creation, Pipecat agent orchestration, ChromaDB knowledge retrieval, PostgreSQL persistence, and QA scoring. Fully async, 4-worker uvicorn, handles 100+ concurrent calls.
## Open-Source Commitment
Wavvy is fully open-source under MIT license. The complete codebase — pipeline, guardrails, KB system, agent prompts, and all four apps — is available on GitHub. Businesses can:- Self-host for free (bring your own API keys)- Use managed hosting starting at $299/month- Customize every layer of the stack
## Who Uses Wavvy?
Wavvy is designed for:- **Contact center operators** replacing legacy IVR with AI-powered automation- **SaaS companies** adding a voice AI layer to their existing product- **Developers** building custom voice agents without starting from scratch- **Operations teams** needing real-time QA scoring and agent coaching
---
<!-- SOURCE: wavvy_features.md -->
# Wavvy Features
## Customer AI — Voice Agent
The Voice AI is the front line of every Wavvy deployment. It handles inbound calls end-to-end without human intervention for the majority of interactions.
**Deterministic Orchestration**The LLM never decides what to do next. A Workflow Engine is the single source of truth. Intent classification, entity extraction, and tool dispatch are all deterministic. The LLM only polishes language — it never controls flow. This eliminates hallucinated actions and unpredictable behavior.
**FAST_RESPONSES (>80% of turns bypass LLM)**Pricing questions, greetings, lead capture prompts, and confirmation messages are pre-written templates served in under 50ms. The LLM is only called for open-ended product Q&A and competitor comparisons.
**RAG-Powered Knowledge Base**Every LLM turn is preceded by a KB search. Relevant documentation snippets are injected into context automatically. The KB uses a three-signal retrieval system: dense vector search (ChromaDB), BM25 keyword matching, and entity graph lookup — fused via Reciprocal Rank Fusion for higher precision.
**Lead Capture (Conversational)**When a prospect wants a demo or to speak with the team, the AI asks for details one field at a time: name, email, phone, company. It never asks for multiple fields at once. Once collected, details are saved to the leads database and the workflow continues.
**Barge-In Interruption**Users can interrupt the AI mid-sentence. VAD detects speech start, cancels in-flight TTS frames, and processes the new utterance. Turn IDs prevent stale audio from playing after interruption.
**Escalation to Human**When a caller wants a human, the AI captures lead context and hands off seamlessly. The Agent Desktop receives: caller's name, email, company, intent, conversation summary, and key interests. The human agent picks up exactly where the AI left off.
## Frontline AI — Companion Agent
The Companion AI assists human agents during escalated calls.
**Context Pre-Load**On escalation, the Companion AI immediately analyzes the full Voice AI conversation and generates: a checklist of unresolved items, suggested next actions, customer mood assessment, and relevant KB snippets.
**Real-Time Nudges**As the conversation continues, the Companion updates in real time via WebSocket. It surfaces objection handlers, product talking points, and pricing guidance based on what's being discussed.
**ACW Summary (After-Call Work)**When the call ends, the Companion generates an automated wrap-up: resolution summary, action items, CRM fields to update, and a coaching note for the supervisor.
## Operations AI — Supervisor Tools
**Automated QA Scoring**Within seconds of a call ending, the QA Agent scores the transcript on six rubrics: guardrail adherence, resolution rate, containment, caller satisfaction, handle time, and disclosure compliance. Overall score and pass/fail are stored to the database.
**Live Call Monitoring**The supervisor dashboard shows all active calls in a real-time table (polling every 5 seconds): caller intent, duration, escalation status, and current workflow stage.
**Knowledge Base Management**Supervisors upload PDF, DOCX, or Markdown documents. The system parses, chunks, embeds, and indexes them into ChromaDB. Documents surface in the next live call's KB retrieval automatically.
**Coaching Pack Generation**After any agent accumulates 3 or more scored calls, a coaching pack can be generated. It references specific transcript moments, identifies strengths and improvement areas, and generates action items tailored to that agent's performance patterns.
**Analytics Dashboard**KPI strip: total calls today, average QA score, escalation rate, resolution rate. Trend chart: 7-day QA score history per agent. All backed by PostgreSQL aggregation queries.
## AI Workflow Automation
Wavvy treats contact center workflows as directed graphs. Each intent maps to a workflow: a sequence of tool calls and wait states that the AI executes deterministically. Businesses integrate Wavvy by defining their workflows — the AI follows them without deviation.
Example workflows available out of the box:- Demo scheduling: capture name + email → ask for preferred time → schedule appointment- Human escalation: capture name → escalate with full context- Product Q&A: KB retrieval → LLM renders answer → speak- Pricing inquiry: serve deterministic tier information
---
<!-- SOURCE: wavvy_use_cases.md -->
# Wavvy Use Cases
## Who Integrates Wavvy?
Wavvy is built for any business running a contact center that handles repetitive inbound inquiries and wants to automate the majority of interactions while keeping human agents available for complex cases.
## Food Delivery & On-Demand Services
Contact centers for food delivery platforms handle thousands of calls daily: order status, address changes, cancellations, and refund requests. Wavvy can:- Answer "where is my order?" using real-time order data via API- Capture cancellation requests and route to the right workflow- Escalate frustrated customers to human agents based on sentiment scoring- Score every call for QA automatically
Estimated containment rate: 70-80% of calls resolved without human intervention.
## Banking & Financial Services
Banks and credit unions face high call volumes for account inquiries, card disputes, and authentication. Wavvy provides:- Two-factor authentication flow (configurable, server-authoritative — LLM never decides if auth passed)- Account lookup and balance inquiry via CRM integration- Fraud dispute escalation with full context handoff- Automated compliance scoring (disclosure, guardrail adherence) on every call
Wavvy's guardrail system ensures sensitive operations never execute without proper authorization. All tool calls pass through a multi-stage permission check before execution.
## Telecommunications
Telecom providers handle billing inquiries, plan changes, and technical support. Wavvy can:- Identify the caller and their current plan via CRM lookup- Answer plan comparison questions from the KB- Process plan upgrade/downgrade requests- Escalate complex technical issues to Level 2 support
## E-Commerce & Retail
Online retailers use Wavvy for post-purchase support: returns, exchanges, shipping updates. Wavvy can:- Look up order history and provide status- Initiate return workflows and capture reason codes- Answer product questions from the KB- Route high-value customer complaints to senior agents
## Healthcare & Appointment Scheduling
Healthcare providers use Wavvy for appointment booking and general inquiries:- Schedule appointments by capturing patient name, preferred time, and reason for visit- Answer FAQ from the KB (hours, locations, insurance accepted)- Route urgent medical questions immediately to a human- HIPAA-compliant logging and audit trail
## SaaS & B2B
SaaS companies use Wavvy for sales and onboarding:- Answer product Q&A from the KB (pricing, features, integrations)- Capture demo requests and schedule meetings- Route enterprise inquiries to sales team- Score demo calls for quality and train the sales team
This is exactly the use case Wavvy demonstrates on its own platform — you are experiencing it right now.
## The Common Pattern
Every use case follows the same pattern:
1. **Caller speaks** — Voice AI handles intent classification and entity extraction2. **KB answers** — Product documentation surfaces automatically for open-ended Q&A3. **Workflow executes** — Deterministic tool calls handle transactional requests4. **Human escalates** — Agent Desktop receives full context on complex cases5. **Supervisor scores** — QA automation closes the feedback loop on every call
The only thing that changes between deployments is the KB content, the workflow definitions, and the CRM integration. The core platform remains constant.
---
<!-- SOURCE: wavvy_tech_stack.md -->
# Wavvy Technology Stack
## Voice Pipeline (Real-Time)
Wavvy's voice pipeline is built on production-grade open-source components:
**LiveKit Cloud** — WebRTC transport layer. Handles browser audio in/out, room management, and the data channel used for real-time events (transcripts, tool calls, escalation signals). Free tier: 5,000 minutes/month.
**Pipecat (pipecat-ai 1.2.1)** — Voice pipeline orchestration framework. Connects all pipeline stages: STT → processing → LLM → TTS. Handles interruption detection, frame cancellation on barge-in, and pipeline lifecycle.
**Silero VAD** — Voice Activity Detection. Runs locally, detects user speech start/stop, enables barge-in interruption of in-flight TTS audio. No API cost, unlimited usage.
**Deepgram Nova-2** — Speech-to-Text. Streaming transcription with 300ms endpointing (full utterance arrives as one chunk before processing begins). Free tier: 12,000 minutes/month.
**Groq llama-3.3-70b-versatile** — Primary LLM. OpenAI-compatible API endpoint. Used for language polishing on KB-grounded Q&A turns. Temperature 0.3, max 300 tokens per turn. Free tier: 14,400 requests/day.
**Kokoro TTS** — Local text-to-speech via ONNX model. Zero API cost, unlimited usage. 24kHz audio, voice "af_heart". Runs in-process, ~80MB model download on first run.
## Backend Infrastructure
**FastAPI** — Fully async Python web framework. 4-worker uvicorn deployment. Handles REST API, WebSocket connections, and Pipecat agent task launch as background tasks.
**PostgreSQL + asyncpg** — Primary database. Connection pool: pool_size=20, max_overflow=10. Tables: calls, transcripts, leads, demo_appointments, eval_scores, agent_profiles, kb_documents, coaching_packs.
**ChromaDB (PersistentClient)** — Vector database for knowledge base retrieval. Collections: product_kb (Wavvy documentation), calls_collection (transcript history). Dense retrieval + BM25 + entity graph fused via Reciprocal Rank Fusion.
**SQLAlchemy async** — ORM with asyncpg driver. Alembic for migrations.
## AI Models
**OpenAI text-embedding-3-small** — Embedding model for KB chunks and call transcripts. 1536-dim vectors.
**OpenAI gpt-4o-mini** — Post-call QA scoring, coaching pack generation, ACW summaries. Used sparingly (post-call only) to stay within free tier.
**Groq llama-3.3-70b-versatile (fallback: gpt-4o-mini)** — Live call LLM. Groq's free tier is the primary path; falls back to OpenAI if GROQ_API_KEY is absent.
## Frontend
Three separate React 18 + Vite applications:- Landing page (livekit-client JS for WebRTC)- Agent desktop (WebSocket to /ws/agent for real-time events)- Supervisor dashboard (polling + Recharts for analytics)
## Deployment
**Backend:** Railway — 4-worker uvicorn, PostgreSQL addon, ChromaDB on persistent volume.**Frontend:** Vercel — three separate projects, each with its own deployment URL.**No Docker for local dev** — docker-compose for PostgreSQL only, all other services run natively.
## Text-to-Speech (TTS) Details
Wavvy uses **Kokoro TTS** as its voice synthesis engine. Key facts:
- **Engine:** Kokoro (local ONNX model, runs in-process)- **Cost:** Zero — no API calls, no per-character pricing- **Quality:** 24kHz audio output, voice profile "af_heart"- **Setup:** ~80MB model download on first run, then unlimited local usage- **Latency:** TTS starts within milliseconds of LLM first token — no round-trip to external API- **Streaming:** Phrase-by-phrase output (each sentence queued as a separate TTS frame)
Wavvy does NOT use ElevenLabs, Azure Speech, Google TTS, or Deepgram TTS for live calls. Kokoro provides comparable voice quality at zero marginal cost.
## Speech-to-Text (STT) Details
Wavvy uses **Deepgram Nova-2** for speech recognition:
- Streaming transcription — audio is transcribed in real time- 300ms endpointing — Deepgram waits 300ms of silence before emitting a final transcript- This means a full phone number or sentence arrives as one utterance, not fragmented- Free tier: 12,000 STT minutes/month (enough for ~200 hours of calls)- Confidence scores available per utterance — used to gate recovery routing
## Architecture Decision: No Redis, No Message Queue
At hackathon scale, in-memory state per FastAPI worker is sufficient. Each call is fully isolated within a single asyncio task. Scaling to production would add Redis for distributed session state and a message queue for cross-worker call events.
---
<!-- SOURCE: wavvy_integration.md -->
# Wavvy Integration Guide
## Self-Hosting Overview
Wavvy is fully self-hostable at zero cost. You bring your own API keys for LiveKit, Deepgram, and Groq (all have free tiers). The full platform — voice AI, Agent Desktop, Supervisor Dashboard, and all backend services — runs on your own infrastructure with no vendor lock-in.
Self-hosting requires: Python 3.11+, PostgreSQL 16, Node.js 20+, and a Linux/Mac server or cloud VM. Typical setup time: under one hour. No Docker required except for local PostgreSQL.
The managed cloud plans ($299/month Starter, $999/month Growth, Enterprise custom) are available if you prefer not to manage infrastructure. Self-hosting and managed plans have identical features — the only difference is who runs the servers.
## Getting Started (Self-Hosted)
### Prerequisites
- Python 3.11+- PostgreSQL 16 (docker-compose provided)- Node.js 20+ (for frontend apps)- API keys: LiveKit Cloud, Deepgram, Groq (all have free tiers)
### Quick Start
```bashgit clone https://github.com/yourusername/wavvy.gitcd wavvy/backendpython -m venv .venv && source .venv/bin/activatepip install -r requirements.txtdocker-compose up -d # PostgreSQL on port 5433alembic upgrade head # run migrationspython -m knowledge.seed # seed KBuvicorn main:app --port 8000 # start backend```
## REST API Reference
Key endpoints:
- `POST /api/livekit/start-call` — create LiveKit room + launch Pipecat agent- `GET /api/leads` — all captured leads- `POST /api/kb/upload` — upload PDF/DOCX/MD to knowledge base- `GET /api/calls` — all calls with QA status- `POST /api/coaching/generate/{agent_id}` — generate coaching pack
Full API docs at `/docs` (Swagger UI).
## Adding Custom Tools
1. Define in `tools/registry.py` (OpenAI function format)2. Implement in `tools/wavvy_tools.py` (async function → dict)3. Add to `execute_tool()` dispatcher4. Register in relevant workflow entry
## CRM Integrations
Wavvy connects to Salesforce, HubSpot, and any REST API via its tool layer. Built-in leads database (PostgreSQL) is available out of the box with no external CRM required.
---
<!-- SOURCE: wavvy_pricing.md -->
# Wavvy Pricing
## Managed Hosting Plans
### Starter — $299/month- Up to 500 call minutes/month- Core voice AI, intent routing, KB retrieval- Basic analytics, 1 supervisor seat, email support
### Growth — $999/month- Up to 2,500 call minutes/month- Agent Desktop + Companion AI- Full supervisor dashboard (QA, coaching, live monitoring)- Up to 5 supervisor seats, priority Slack support
### Enterprise — Custom pricing- Unlimited call minutes (SLA-backed)- Custom workflow definitions and tool integrations- On-premises or private cloud option- Dedicated solutions engineer, 99.9% uptime SLA
## Self-Hosted (Free)
MIT license — no usage fees. Bring your own API keys:- LiveKit Cloud: 5,000 WebRTC min/month free- Deepgram: 12,000 STT min/month free- Groq: 14,400 LLM requests/day free- Kokoro TTS: unlimited (local ONNX)
---
<!-- SOURCE: wavvy_vs_competitors.md -->
# Wavvy vs. Competitors
## Wavvy vs. Retell AI
| | Wavvy | Retell AI ||---|---|---|| Open-source | Yes (MIT) | No || Agent Desktop | Yes (Companion AI) | No || Supervisor Dashboard | Yes (QA, coaching) | Limited || Deterministic orchestration | Yes (Workflow Engine) | Prompt-based || QA scoring | Yes (automated) | No |
## Wavvy vs. Vapi
Vapi is a developer-focused voice AI API. Wavvy is a complete platform (three apps + backend). Vapi gives building blocks; Wavvy gives a full contact center stack. Wavvy includes KB management, QA automation, and Agent Desktop that Vapi does not have.
## Wavvy vs. Bland AI
Bland AI focuses on outbound calling campaigns. Wavvy is inbound-first with full human escalation support. Wavvy has Agent Desktop, Supervisor Dashboard, and QA automation that Bland does not.
## Wavvy vs. ElevenLabs
ElevenLabs is a TTS API, not a contact center platform. Wavvy uses Kokoro TTS (local ONNX, zero cost). ElevenLabs provides no orchestration, KB retrieval, escalation routing, or operational stack.
## Wavvy vs. Twilio Flex
| | Wavvy | Twilio Flex ||---|---|---|| Time to deploy | Hours | Weeks to months || Open-source | Yes | No || AI-native | Yes | Bolt-on || Pricing | From $299/mo | Per agent seat + usage |
## Key Wavvy Differentiators
1. Deterministic orchestration — LLM never decides what to do2. Three-app operational stack — Landing + Voice AI, Agent Desktop, Supervisor3. Open-source and self-hostable — no vendor lock-in4. Automatic QA — every call scored within 5 seconds5. Companion AI — human agents get full context on escalation123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130# Account Security
## Account Lock Policy
An account is automatically locked when:- 3 or more consecutive failed login attempts are detected- A suspicious login from an unrecognized device or location is flagged- The fraud team places a security hold- The customer manually requests a lock
When locked, all transactions and logins are blocked until the account is unlocked through a verified channel.
## Types of Account Locks
Not all account locks are the same. Fin handles each type differently:
### Standard Lock (Failed Logins)
Triggered by 3 or more consecutive failed login attempts. This is the most common case.
**Fin can unlock this directly** using `unlock_account` after verifying identity (OTP required).
Process:1. Verify customer identity (`verify_account`)2. Send OTP (`send_otp`) and verify it (`verify_otp`)3. Unlock the account (`unlock_account`)4. Confirm the account is active and advise the customer to reset their password via the app
### Fraud Lock
Triggered when the fraud team places a security hold due to suspected fraud or confirmed fraudulent activity.
**Fin cannot unlock this.** Fin escalates immediately to the security-team.
Fin tells the customer: "Your account has a security hold placed by our fraud team. I need to connect you with a specialist." The security team handles identity re-verification through alternate channels.
### Compliance Hold
Triggered by a regulatory or AML review.
**Fin cannot unlock this.** Fin escalates to the compliance-team.
Fin tells the customer: "There is a regulatory hold on your account. Our compliance team will need to review this with you." Details about the trigger are not shared.
## Identifying the Lock Type
When `unlock_account` is called, the system determines the lock type automatically:- Standard lock → unlock proceeds- Fraud lock → returns `fraud_lock` key → Fin escalates to security-team (terminal)- Compliance hold → returns `compliance_hold` key → Fin escalates to compliance-team (terminal)
If Fin cannot determine the lock type from the account record, Fin escalates by default.
## OTP Policy
OTP is used to authorize sensitive account actions (unlock, refund, dispute, fraud report).
| Rule | Value ||---|---|| OTP validity | 5 minutes from send || Cooldown between resends | 10 seconds || Maximum resends per session | 5 || Maximum wrong attempts | 3 || After 3 wrong attempts | Account locked from further OTP attempts; Fin escalates |
If OTP has expired: Fin offers to resend immediately.If OTP resend limit is reached (5 resends): Fin escalates to identity-specialist.If 3 wrong codes entered: Fin escalates to identity-specialist automatically — this cannot be overridden.
## Password Reset
1. Customer clicks "Forgot Password" on the login screen2. A password reset link is sent to the registered email address3. Link expires after 30 minutes4. New password must be at least 8 characters with one number and one special character
If the registered email is inaccessible: escalate to the security team for alternate identity verification.
## Two-Factor Authentication (2FA)
2FA is enabled by default for all accounts. Supported methods:- SMS OTP to registered phone number- Email OTP to registered email address- Authenticator app (Google Authenticator, Authy)
If a customer is not receiving their OTP:1. Ask them to check spam/junk folder (email OTP)2. Confirm the registered phone number3. Suggest waiting 10 seconds and requesting a new OTP (cooldown enforcement)4. If the issue persists after 3 attempts, escalate to the security team
2FA cannot be disabled without identity verification. Any request to disable 2FA must go through the security team.
## Session Management
Active sessions can be viewed and terminated from Settings → Security → Active Sessions.
Session expiry:- 30 minutes of inactivity (mobile app)- 60 minutes of inactivity (web app)- 7 days absolute expiry regardless of activity
If a customer reports an unknown active session: this is a security incident. Escalate immediately to the security-team with reason `fraud_suspected`.
## What Fin Can and Cannot Do
Fin can:- Unlock a standard-locked account directly via `unlock_account` (OTP required)- Guide the customer through the self-service password reset process- Explain 2FA setup and troubleshooting steps- Confirm whether an account is locked and the type of lock
Fin cannot:- Unlock accounts with fraud locks or compliance holds- Reset passwords- Disable 2FA- Access session logs, device information, or IP addresses- Verify alternate identity documents
All of the above require escalation to the security team or compliance team.
## Escalation Triggers
Escalate immediately when:- Account has a fraud lock or compliance hold- Customer cannot access their registered email AND phone- Customer reports a session they did not start- Customer believes their account has been compromised- OTP fails 3 consecutive times- Customer requests manual identity review123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899# Dispute Resolution
## What is a Dispute?
A dispute (also called a chargeback) is a formal request to reverse a completed transaction because:- The customer did not receive the product or service- They were charged the wrong amount- The transaction was duplicated- The transaction was unauthorized (but the transaction completed — not failed)
A dispute is different from a simple refund. Refunds apply to failed transactions. Disputes apply to completed transactions where the customer has a grievance about the charge.
## Dispute Eligibility
Fin can file a dispute directly using `raise_dispute`. A dispute can be raised when:
- Transaction status is `completed` — **not eligible for any other status**- Transaction is within 90 days of the transaction date- Transaction value is above ₹100 or $2 (minimum threshold)- The transaction has not already been disputed (`disputed` status)
**Not eligible for dispute:**- `failed` transactions — use `initiate_refund` instead- `pending` or `processing` transactions — wait for final status- `refund_initiated` or `refund_completed` — already in process- `flagged` transactions — escalate to fraud team first- Transactions older than 90 days — requires escalation to disputes team
## Filing a Dispute (Process)
1. Verify the customer's identity (`verify_account`)2. Look up the transaction (`lookup_transaction`) — confirm status is `completed`3. Confirm the dispute reason with the customer4. Send OTP and verify (`send_otp` → `verify_otp`)5. File the dispute (`raise_dispute`) — returns a dispute reference (DSP-XXXXXXXX)6. Confirm the reference number and timeline to the customer
**High-value disputes (≥ ₹50,000):** Fin escalates to the senior-disputes team rather than filing directly. Manual review is required for these cases.
## Dispute Reasons
Common reasons a customer may dispute a completed transaction:
| Reason | Description ||---|---|| `item_not_received` | Merchant did not deliver the product or service || `wrong_amount` | Customer was charged more than the agreed amount || `duplicate_charge` | Same transaction charged twice (both completed) || `unauthorized` | Customer did not authorize the transaction (but it completed) || `quality_issue` | Product or service was defective (requires merchant communication first) |
## Chargeback Lifecycle
After a dispute is filed, the transaction status progresses through the chargeback lifecycle:
| Status | Meaning | Fin's response ||---|---|---|| `disputed` | Dispute filed, investigation in progress | Give reference, set timeline expectations || `chargeback_initiated` | Escalated to bank or card network | Confirm it is with the bank || `chargeback_won` | Resolved in customer's favour | Confirm refund timeline (5 business days) || `chargeback_lost` | Chargeback denied | Explain next steps — escalate to senior disputes team for appeal |
If a customer calls about a transaction already in `disputed` or `chargeback_initiated` status, Fin gives a status update and does not re-file. A duplicate dispute cannot be opened on the same transaction.
If the dispute window has expired (more than 90 days), Fin cannot file directly — Fin escalates to the disputes team who can evaluate an exception.
## Timeline
| Stage | Timeline ||---|---|| Dispute submission (via Fin) | Same day || Initial review by payment team | 1 business day || Merchant response window | 5–7 business days || Final resolution | 3–14 business days depending on complexity || Refund after chargeback_won | 5 business days |
## Manual Reconciliation for Gateway Failures
For gateway timeout failures (transaction status `failed`, reason `gateway_timeout`), Fin initiates a refund directly via `initiate_refund` — this is faster than the formal dispute process and does not require filing a chargeback.
Manual reconciliation via refund is only available when:- Transaction status is `failed`- Customer's account is in good standing (not flagged, kyc_hold, or compliance_hold)- Transaction is not under any fraud review
## What Fin Can and Cannot Do
Fin can:- Verify transaction eligibility for a dispute- File a dispute directly via `raise_dispute` for eligible completed transactions- Provide the dispute reference number (DSP-XXXXXXXX)- Explain the dispute process and timeline- Give status updates for existing disputes
Fin cannot:- Promise a specific outcome on a dispute- Access merchant transaction records or communications- Approve or reject a dispute decision- File a dispute for non-completed transactions1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374# Fin Support Agent — Overview
## What is Fin?
Fin is a voice-based AI customer support agent powered by the Wavvy CCaaS platform. Fin handles inbound support calls for payment failures, refunds, KYC verification, fraud reports, account security issues, disputes, and general transaction inquiries.
Every interaction Fin handles is supervised, scored, and audited through Wavvy's supervisor dashboard. Fin is not a chatbot — it is a fully integrated support agent that verifies customer identity, accesses live account data, takes permitted actions, and hands off to human specialists with full context when needed.
## Supported Issue Categories
| Category | What Fin handles ||---|---|| Payment Failure | Gateway timeouts, NSF, network errors, stuck pending payments || Refund Inquiry | Refund eligibility, status checks, initiating refunds for failed transactions || KYC Verification | Document requirements, failure reasons, re-verification guidance || Fraud Report | Unauthorized transactions, opening fraud cases, escalating to fraud team || Account Access | Locked accounts (standard lock), OTP issues, unlock assistance || Dispute Filing | Formal disputes for completed transactions, chargeback status || Payment Status | Live status checks for pending and processing payments || General Inquiry | Transaction history, account type, balance-related questions |
## Fin's Tools
Fin has direct access to the following tools. These are executed server-side — the customer never controls which tool runs.
| Tool | Purpose | Requires OTP? ||---|---|---|| `verify_account` | Confirm caller identity by registered phone | No || `send_otp` | Send a one-time password for sensitive actions | No (after verify_account) || `verify_otp` | Validate the OTP the customer provides | No || `lookup_transaction` | Retrieve full details and status of a transaction | No (after verify_account) || `check_payment_status` | Check live payment processing state | No (after verify_account) || `initiate_refund` | Initiate a refund for an eligible failed transaction | Yes || `unlock_account` | Unlock a standard-locked account | Yes || `raise_dispute` | File a formal dispute for a completed transaction | Yes || `report_fraud` | Open a fraud case for an unauthorized transaction | Yes || `escalate_to_human` | Transfer the call to a human specialist | No |
## Identity Verification — Always First
Before accessing any account data or performing any action, Fin verifies the caller's identity using their registered phone number (`verify_account`). If Fin cannot verify the caller after two attempts, Fin offers to connect them with a specialist.
For sensitive actions (refunds, unlocking accounts, raising disputes, reporting fraud), an OTP is required in addition to identity verification. The OTP expires in 5 minutes and allows 3 attempts before Fin escalates automatically.
Fin never reveals account numbers, card numbers, full phone numbers, email addresses, or internal system states to the caller.
## Escalation Policy
Fin escalates to a human specialist by asking first: "Would you like me to connect you with a specialist?" The customer confirms, then Fin transfers. Fin never escalates without consent except in two cases:- OTP locked after 3 failed attempts (automatic, for security)- Customer explicitly ends the call before Fin can ask
Escalation routing by team:
| Trigger | Team ||---|---|| Account not found after 2 attempts | account-specialist || OTP locked / identity unresolvable | identity-specialist || Fraud lock on account | security-team || Compliance hold on account | compliance-team || Completed transaction refund request | disputes-team || Transaction under fraud review | fraud-team || KYC hold | kyc-team || High-value transaction (≥ ₹50,000) | senior-support || High-value dispute (≥ ₹50,000) | senior-disputes || Customer explicitly requests human | customer-choice |
Fin passes the full conversation transcript, verified customer identity, transaction details, and issue summary to the receiving specialist on every escalation.
## Tone and Style
Fin speaks like a calm, professional support representative. Responses are direct and short — key facts come first. Fin never uses jargon, never repeats itself, and always confirms resolution before ending an interaction.
If Fin cannot resolve an issue, it says so clearly and offers escalation rather than giving a vague or incorrect answer.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081# Fraud Detection and Escalation
## Overview
Fin handles fraud reports as a first-response action. When a customer reports an unauthorized transaction, Fin verifies identity, looks up the transaction, and opens a fraud case directly using `report_fraud`. This creates an immediate case reference (format: FRD-XXXXXXXX) and logs the report with the fraud team.
Fin does not investigate fraud independently — the fraud team reviews all cases and takes action. But Fin does not leave the customer waiting without a case number.
## Fraud Indicators
**High-confidence — immediate action:**- Customer reports a transaction they did not authorize- Transaction amount is unusually large compared to account history- Multiple transactions in a short period to unknown merchants- Customer reports their account was accessed from an unknown device or location- Transaction status is `flagged` in the system
**Medium-confidence — verify then act:**- Customer is unsure whether they authorized a transaction- Transaction is to an unfamiliar merchant but the amount is small- Customer received a payment confirmation they didn't initiate
## Fraud Response Process
1. **Do not dismiss the concern.** Treat all fraud reports as credible until proven otherwise.2. **Verify the customer's identity** using `verify_account` before discussing any account details.3. **Look up the transaction** using `lookup_transaction` with the transaction ID.4. **Send OTP and verify** — `report_fraud` requires identity confirmation.5. **Open a fraud case** using `report_fraud` — this returns a case reference (FRD-XXXXXXXX).6. **Confirm next steps** — tell the customer the case is open, give the reference number, and set expectations for the SLA.
## Fraud Status Lifecycle
As a fraud case progresses, the transaction status changes:
| Status | Meaning | What Fin does ||---|---|---|| `fraud_reported` | Case opened, under initial review | Give case reference, set expectations || `fraud_confirmed` | Fraud team confirmed the fraud | Escalate to fraud team for next steps || `fraud_reversed` | Fraudulent charge reversed | Confirm refund timeline per standard refund policy |
If a customer calls about a transaction that is already `fraud_reported`, Fin informs them the case is already open and provides the reference number if available. Fin does not re-open a case for the same transaction.
If the transaction status is `fraud_confirmed`, Fin escalates to the fraud team immediately — this requires human specialist involvement.
## What Fin Can and Cannot Do
Fin can:- Verify the customer's identity- Look up the transaction and check its status- Open a fraud case via `report_fraud` and provide a case reference- Explain the fraud case lifecycle and SLA to the customer
Fin cannot:- Freeze or block an account — requires fraud team escalation- Reverse a transaction directly — the fraud team handles reversals- Confirm whether a transaction is definitively fraudulent before team review- Access login history, device information, or IP addresses- Tell the customer which device accessed their account
If a customer requests an account freeze proactively (they believe their account is compromised), Fin escalates immediately to the security-team with reason `fraud_suspected`.
## SLA for Fraud Cases
| Case Type | First Response SLA | Resolution SLA ||---|---|---|| Unauthorized transaction | 1 business hour | 24–48 business hours || Account access complaint | 1 business hour | 4–8 business hours || Account freeze request | Immediate escalation | 1 business hour || Phishing / social engineering | Immediate escalation | 2 business hours |
## Escalation — Flagged Transactions
If a customer calls about a transaction that is already in `flagged` status (fraud-flagged by automated systems), Fin does not attempt to resolve this. Fin escalates to the fraud team immediately with the transaction ID and status. Fin tells the customer: "This transaction is currently under fraud review. I need to connect you with our fraud team."
## Key Notes
- Never confirm or deny that a specific transaction is fraud before the fraud team reviews it- Never suggest the merchant was at fault without evidence- Always get a case reference from `report_fraud` before ending the call- If the customer provides multiple transaction IDs, open one case — the fraud team handles multi-transaction investigations123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596# KYC Verification — Customer Guidance
## What is KYC?
KYC (Know Your Customer) is a mandatory identity verification process required by financial regulators. All accounts must complete KYC to unlock full transaction limits and services. Without completed KYC, accounts operate in a restricted state with lower transaction limits.
## KYC Levels
| Level | Status | Transaction Limit | Features Available ||---|---|---|---|| KYC Pending | Not submitted | ₹10,000 / $200 per month | Basic wallet only || KYC Submitted | Under review | Same as pending | Basic wallet only || KYC Verified | Fully verified | Full limits | All features || KYC Failed | Verification failed | Restricted | Re-verify or escalate || KYC Hold | Manual review pending | Restricted | Escalation required |
## Required Documents
**Identity Proof (one required):**- Aadhaar Card (India)- PAN Card (India)- Passport- Driver's License- National ID Card
**Address Proof (one required, if different from identity proof):**- Utility bill (last 3 months)- Bank statement (last 3 months)- Aadhaar Card (if current address matches)
**For premium accounts or high-limit transactions:**- Recent bank statement (last 6 months)- Employment letter or income proof
## Common KYC Failure Reasons
1. **Document mismatch** — Name on the document does not match the account registration name2. **Expired document** — ID document has passed its validity date3. **Poor image quality** — Photo is blurry, cropped, or has glare; all four corners must be visible4. **Incomplete document** — Not all pages uploaded (passports require both pages)5. **Address mismatch** — Address on proof does not match the registered address6. **Duplicate KYC** — Another account already uses the same document
## Re-Verification Process
If a customer's KYC has failed:
1. Inform the customer of the specific failure reason (if available in their account record)2. Guide them to re-upload documents via the app (Settings → KYC → Re-verify)3. Re-verification review takes 24–48 business hours4. If re-verification fails a second time, Fin escalates to the KYC specialist team
## KYC Hold vs. Compliance Hold
These two statuses are different and require different escalation paths:
**KYC Hold (`kyc_hold`)**KYC documents are under manual review. The account is temporarily restricted pending document verification. Fin escalates to the **KYC specialist team**.- Typical SLA: 24–48 business hours for review- Customer can accelerate by re-uploading clearer documents via the app
**Compliance Hold (`compliance_hold`)**A regulatory or AML (Anti-Money Laundering) review is in progress. This is a more serious hold triggered by transaction pattern analysis or regulatory flags. Fin escalates to the **compliance team**.- Cannot be resolved by the customer through self-service- Compliance team reviews all available account data- Customer should be told: "There is a regulatory hold on your account. Our compliance team will review and contact you directly."- Do not share details about what triggered the compliance hold- Typical SLA: 2–5 business days for initial response
## What Fin Can and Cannot Do
Fin can:- Explain KYC requirements and document types- Confirm the customer's current KYC status from their account record- Guide the customer through the app re-verification steps- Explain what a specific failure reason means in plain language
Fin cannot:- Approve or override KYC verification- Access the document images submitted- Confirm the outcome of a pending review- Waive KYC requirements- Resolve a compliance hold (this always requires the compliance team)
## Escalation for KYC Issues
Always escalate to the kyc-team when:- Customer's status is `kyc_hold` and they need urgent transaction access- Customer has re-submitted documents twice without approval- Customer believes the failure reason is incorrect- Customer's business account requires enhanced due diligence (EDD)
Always escalate to the compliance-team when:- Transaction status shows `compliance_hold`- Customer has received a compliance notification and wants to understand it- A transaction was blocked due to regulatory concerns123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102# Payment Failure — Standard Operating Procedure
## Overview
A payment failure occurs when a transaction is initiated but does not complete successfully. The funds may or may not have been debited from the customer's account depending on the failure type and stage of processing.
## Step 1 — Check Payment Status
When a customer reports a payment issue, the first step is to verify the account and look up the transaction status. Fin uses `check_payment_status` when the customer does not have a transaction ID and just wants to know "where is my payment?"
`check_payment_status` checks the live state of the most recent payment and returns one of the following outcomes:
| Result | What it means | Fin's response ||---|---|---|| `payment_processing` | Gateway accepted, settlement in progress | Normal — tell customer expected timeline || `payment_processing_delayed` | Status has been `pending` since a previous day | Escalate to payments team || `payment_settled` | Payment completed successfully | No issue — explain the funds reached merchant || `payment_failed_post_debit` | Deducted but not credited | Eligible for refund — proceed to initiate_refund || `payment_returned` | Funds returned to source account automatically | Tell customer to check their account || `gateway_error` | Gateway error prevented processing | Escalate to payments team |
## Step 2 — Identify Failure Type
### Gateway Timeout
The payment was initiated but the gateway did not receive a confirmation within the allowed window (typically 30 seconds). The amount is often debited but not credited to the merchant.
**Transaction status:** `failed`**Resolution:** Initiate refund via `initiate_refund`. Refund credited within 3–5 business days (debit card) or same day (wallet).
### Insufficient Funds (NSF)
The transaction was declined because the account did not have sufficient balance.
**Transaction status:** `failed` or `cancelled`**Resolution:** No debit occurred — advise the customer to ensure sufficient balance and retry. No refund needed.
### Network or Bank Error
The transaction failed due to a transient network issue or error at the issuing bank.
**Transaction status:** `failed`**Resolution:** Advise the customer to retry. If the error has persisted across multiple attempts or the amount was debited, initiate a refund.
### Card or Account Blocked
The transaction was declined due to a security hold, expired card, or account restriction.
**Transaction status:** `failed` or `flagged`**Resolution:**- Expired card: guide customer to update card details in the app- `flagged` status: escalate to fraud team immediately — Fin does not investigate flagged transactions- Account lock: use `unlock_account` if it is a standard lock; escalate if fraud lock or compliance hold
### Pending Too Long
The payment is stuck in `pending` status beyond the normal 1–3 business day window.
**Transaction status:** `pending` from a previous day**Resolution:** Escalate to payments team (`payment_processing_delayed` outcome).
## Transaction Status Reference
| Status | Meaning | Action ||---|---|---|| `pending` | Submitted, awaiting gateway confirmation | Check if same-day — if previous day, escalate || `processing` | Gateway accepted, settlement in progress | Normal — give timeline || `failed` | Deducted but not credited | Eligible for refund || `cancelled` | Cancelled before settlement | Auto-reversal within 3–5 business days || `expired` | Payment link or session timed out | No charge — advise customer to retry |
## Key Information to Collect
Before initiating a refund or escalating:1. Transaction ID (format: TXN-XXXX)2. Transaction amount and date3. Merchant name4. Whether the amount was debited from the account5. If the customer has received any confirmation messages
## Refund Timelines for Payment Failures
| Payment Method | Timeline After Initiation ||---|---|| Wallet / app balance | Same business day || Debit card | 3–5 business days || Credit card | 5–7 business days || Bank account (NEFT) | 3–7 business days || International card | 7–10 business days |
## High-Value Threshold
Transactions at or above ₹50,000 require escalation to the senior-support team regardless of failure type. Fin does not initiate refunds for high-value transactions without senior approval.
## Escalation Triggers
Escalate to the appropriate team immediately when:- Transaction status is `flagged` (fraud team)- Transaction status shows `kyc_hold` or `compliance_hold` (respective teams)- Amount is ₹50,000 or above (senior-support)- Customer reports the same issue a second time without resolution- Customer expresses high frustration or explicitly requests a human agent123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778# Refund Policy
## Eligibility
Fin can initiate refunds directly using the `initiate_refund` tool. A refund may be initiated when:
1. A payment was debited but the transaction did not complete — **status must be `failed`**2. A duplicate charge resulted in one `failed` transaction alongside a `completed` one3. An unauthorized charge was made and the transaction status is `failed`
Refunds are **not initiated by Fin** for:- Transactions with status `completed` — these require a formal dispute via `raise_dispute`- Transactions with status `refund_initiated` or `refund_processing` — already in progress- Transactions with status `refund_completed` — already processed- Transactions with status `flagged` — fraud review required first- Transactions with status `kyc_hold` — KYC must be resolved first- Transactions older than 90 days — requires manager approval
## Status-Based Response Rules
Before initiating a refund, Fin checks the transaction status and responds accordingly:
| Transaction Status | Fin's Action ||---|---|| `failed` | Initiate refund (eligible) || `refund_initiated` | Refund already underway — give 3–5 business day timeline || `refund_processing` | Refund in transit — give timeline, no re-initiation || `refund_completed` | Refund processed — ask customer to check their account or bank || `completed` | Not eligible for refund — offer to raise a dispute instead || `flagged` | Fraud review required — escalate to fraud team immediately || `kyc_hold` | Account KYC hold — escalate to KYC team || `compliance_hold` | Regulatory hold — escalate to compliance team |
## Session Idempotency
Fin will not initiate the same refund twice in one call. If a refund has already been opened in the current session, Fin confirms the case ID and timeline without re-initiating.
## High-Value Transactions
Transactions at or above ₹50,000 are not refunded directly by Fin. Fin escalates these to the senior-support team regardless of eligibility.
## Refund Timelines
Processing times begin from the day the refund is initiated, not the day the customer reports the issue.
| Refund Method | Processing Time ||---|---|| Wallet / app balance | Same business day || Debit card | 3–5 business days || Credit card | 5–7 business days || Bank account (NEFT) | 3–7 business days || International card | 7–10 business days |
## Initiating a Refund (Process)
1. Verify the customer's identity (`verify_account`)2. Look up the transaction (`lookup_transaction`)3. Confirm the transaction status is `failed`4. Send OTP and verify (`send_otp` → `verify_otp`)5. Initiate the refund (`initiate_refund`)6. Confirm the refund case ID and expected timeline to the customer
Fin provides a refund case reference on successful initiation. The customer should retain this for follow-up.
## Refund Dispute — Refund Not Received
If a customer says their refund has not arrived after the stated timeline:
1. Check the transaction status — confirm it shows `refund_completed`2. Confirm the refund destination matches the customer's registered payment method3. If `refund_completed` but not received: ask the customer to allow 1 additional business day and contact their bank — processing delays are on the bank side, not Fin's4. If more than 2 business days past the expected date and still not received: escalate with the transaction ID, refund initiation date, and refund case ID
## Key Notes
- Never promise same-day refunds unless the payment method is a wallet/app balance and it has been explicitly confirmed- Always confirm the customer's registered payment method before stating the refund timeline- If the transaction status shows `failed` but the customer says no amount was deducted, explain that no debit occurred and no refund is needed — this is a declined transaction, not a failed debit123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189# Transaction Status Guide
## Overview
Every transaction in the system has a `status` field that describes exactly where the payment is in its lifecycle. This guide explains what each status means, what the customer can expect, and what Fin does in response.
There are 17 transaction statuses grouped into six categories.
---
## In-Flight Statuses
These transactions are still moving through the payment system. No action is needed yet.
### `pending`
The payment has been submitted to the payment gateway and is awaiting confirmation. This is normal immediately after a transaction is initiated.
**Expected duration:** 1–3 business days for most transactions.**If stuck:** If the status is `pending` from a previous business day, this may indicate a gateway delay. Fin escalates to the payments team.**Customer message:** "Your payment is being processed. It should update within 1–3 business days."
### `processing`
The gateway has accepted the payment and funds are moving through the settlement system. This is further along than `pending` — the merchant will receive the funds once settlement completes.
**Expected duration:** 1–2 business days.**Customer message:** "Your payment is processing. Funds should settle within 1–2 business days."
---
## Terminal Statuses
These transactions have reached a final state and will not change unless an action is taken.
### `completed`
The payment has settled successfully. Funds have been credited to the merchant and debited from the customer's account.
**Refund eligible?** No — a completed transaction is not eligible for a direct refund. If the customer has a grievance, they must file a dispute via `raise_dispute`.**Customer message:** "This payment completed successfully. If you have an issue with this charge, I can raise a dispute for you."
### `failed`
The payment was attempted and funds were debited from the customer's account, but the transaction did not credit to the merchant. This is the most common scenario requiring a refund.
**Refund eligible?** Yes — Fin initiates a refund directly via `initiate_refund`.**Customer message:** "This transaction failed after the amount was deducted. I can initiate a refund for you."
### `cancelled`
The transaction was cancelled before settlement was complete. The amount was never fully debited, or an auto-reversal has been initiated.
**Refund eligible?** Typically no — auto-reversal returns funds within 3–5 business days.**Customer message:** "This transaction was cancelled. Any held amount will be reversed within 3–5 business days."
### `expired`
The payment link or session timed out before the customer completed the payment. No charge was made.
**Refund eligible?** No — no debit occurred.**Customer message:** "The payment session expired. No amount was charged. You can retry the payment."
---
## Refund Lifecycle Statuses
### `refund_initiated`
A refund has been submitted to the payment processor. The process is underway.
**Customer message:** "A refund is already in progress for this transaction. It typically takes 3–5 business days to appear in your account."
### `refund_processing`
The processor has accepted the refund request. Funds are in transit back to the customer's account.
**Customer message:** "Your refund is processing. Funds should appear within a few business days."
### `refund_completed`
The refund has been processed and funds have been credited back to the customer's original payment method.
**If customer hasn't received it:** Ask them to check with their bank. Allow 1 additional business day. If still not received after 2 business days past the expected date, escalate with the transaction ID and refund initiation date.**Customer message:** "Your refund has been processed. Please check your account or allow one additional business day for your bank to update."
---
## Hold and Review Statuses
Transactions in these states cannot be processed further until the hold is resolved.
### `flagged`
The transaction has been flagged by automated fraud detection systems for review. All outbound activity on this transaction is blocked.
**Fin's action:** Escalate to the fraud team immediately. Do not attempt to process a refund or dispute for a flagged transaction.**Customer message:** "This transaction is currently under fraud review. I need to connect you with our fraud team."
### `kyc_hold`
A KYC (Know Your Customer) verification is required before this transaction can proceed or be refunded. The account's KYC status is incomplete or under review.
**Fin's action:** Escalate to the KYC specialist team. Guide the customer to re-upload documents if applicable.**Customer message:** "There is a KYC verification hold on this account. I'll connect you with our KYC team."
### `compliance_hold`
A regulatory or AML (Anti-Money Laundering) review is in progress. This is a more serious hold triggered by risk or compliance analysis.
**Fin's action:** Escalate to the compliance team. Do not share the reason for the hold.**Customer message:** "There is a regulatory hold on this account. Our compliance team will need to review this."
---
## Dispute and Chargeback Lifecycle
### `disputed`
A formal dispute has been filed for this transaction. The payment operations team is investigating.
**Fin's action:** Give a status update, do not re-file. Provide the existing dispute reference if available.
### `chargeback_initiated`
The dispute has been escalated to the issuing bank or card network for a formal chargeback review.
**Fin's action:** Inform the customer the dispute is now with the bank. Timeline: 5–14 business days for bank resolution.
### `chargeback_won`
The chargeback was resolved in the customer's favour. A refund will be issued.
**Timeline:** Refund within 5 business days of the chargeback decision.
### `chargeback_lost`
The chargeback was denied. The original transaction charge stands.
**Fin's action:** Offer escalation to the senior disputes team if the customer wants to appeal. Fin does not re-file independently.**Customer message:** "The chargeback review did not find in your favour. I can connect you with our senior disputes team if you'd like to appeal."
---
## Fraud Lifecycle Statuses
### `fraud_reported`
A fraud case has been opened for this transaction. The fraud team is conducting an initial review.
**Fin's action:** Confirm the case is open, give the case reference (FRD-XXXXXXXX), set SLA expectations.
### `fraud_confirmed`
The fraud team has confirmed that the transaction was fraudulent.
**Fin's action:** Escalate to the fraud team immediately — they will initiate the reversal process.
### `fraud_reversed`
The fraudulent charge has been reversed. Funds are being returned per the standard refund timeline.
**Customer message:** "The fraudulent charge has been reversed. Funds will appear in your account per the standard refund timeline."
---
## Quick Reference
| Status | Category | Refund Eligible | Dispute Eligible | Fin Action ||---|---|---|---|---|| `pending` | In-flight | No | No | Monitor, escalate if delayed || `processing` | In-flight | No | No | Inform, give timeline || `completed` | Terminal | No | Yes | Raise dispute || `failed` | Terminal | Yes | No | Initiate refund || `cancelled` | Terminal | No | No | Auto-reversal in 3–5 days || `expired` | Terminal | No | No | No charge, advise retry || `refund_initiated` | Refund | — | — | Already underway || `refund_processing` | Refund | — | — | In transit || `refund_completed` | Refund | — | — | Done — check bank || `flagged` | Hold | No | No | Escalate fraud team || `kyc_hold` | Hold | No | No | Escalate KYC team || `compliance_hold` | Hold | No | No | Escalate compliance team || `disputed` | Dispute | — | — | Status update only || `chargeback_initiated` | Dispute | — | — | With bank — give timeline || `chargeback_won` | Dispute | — | — | Refund in 5 days || `chargeback_lost` | Dispute | — | — | Offer senior appeal || `fraud_reported` | Fraud | — | — | Case open — give reference || `fraud_confirmed` | Fraud | — | — | Escalate fraud team || `fraud_reversed` | Fraud | — | — | Refund in progress |123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161import loggingimport warnings
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(name)s — %(message)s")logging.getLogger("chromadb.telemetry").setLevel(logging.CRITICAL)logging.getLogger("httpx").setLevel(logging.WARNING)logging.getLogger("httpcore").setLevel(logging.WARNING)
warnings.filterwarnings( "ignore", message="resource_tracker: There appear to be", category=UserWarning,)
from contextlib import asynccontextmanager
import chromadbfrom fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddlewarefrom openai import AsyncOpenAIfrom sqlalchemy import text
from config import settingsfrom config_loader import load_active_configfrom database import AsyncSessionLocalfrom voice import sentiment as sentiment_modulefrom tools import crm_query as crm_query_modulefrom agents import companion_agent as companion_modulefrom agents import qa_agent as qa_agent_modulefrom agents import coaching_agent as coaching_agent_modulefrom knowledge import embeddings as embeddings_modulefrom knowledge import kb_manager as kb_manager_module
@asynccontextmanagerasync def lifespan(app: FastAPI): # Load active tenant config first — all voice/agent code depends on it await load_active_config()
# Shared AsyncOpenAI client — one instance, async-safe openai_client = AsyncOpenAI(api_key=settings.openai_api_key) app.state.openai_client = openai_client sentiment_module.init_openai_client(openai_client)
# ChromaDB — persistent collections (default + all tenant KB collections) chroma_client = chromadb.PersistentClient( path=settings.chroma_persist_dir, settings=chromadb.Settings(anonymized_telemetry=False), ) app.state.chroma_client = chroma_client kb_collection = chroma_client.get_or_create_collection("kb_collection") fin_collection = chroma_client.get_or_create_collection("fin_support") calls_collection = chroma_client.get_or_create_collection("calls_collection") app.state.kb_collection = kb_collection app.state.calls_collection = calls_collection
collections_dict = { "kb_collection": kb_collection, "fin_support": fin_collection, }
# CRM query module needs the OpenAI client + ChromaDB collections crm_query_module.init_crm_query(openai_client, kb_collection, calls_collection)
# Companion + QA agents companion_module.init_companion_agent(openai_client) qa_agent_module.init_qa_agent(openai_client) coaching_agent_module.init_coaching_agent(openai_client)
# Embeddings + KB manager embeddings_module.init_embeddings(openai_client) kb_manager_module.init_kb_manager(kb_collection, calls_collection, collections_dict=collections_dict)
# Agent connection registry app.state.connected_agents = {}
# Start reminder loop — T-24h and T-1h email reminders for confirmed demos import asyncio as _asyncio from voice.reminder_service import start_reminder_loop reminder_task = _asyncio.create_task(start_reminder_loop())
yield
reminder_task.cancel() try: await reminder_task except _asyncio.CancelledError: pass
await openai_client.close()
app = FastAPI(title="Wavvy API", version="1.0.0", lifespan=lifespan)
app.add_middleware( CORSMiddleware, allow_origins=["*"] if settings.environment == "development" else settings.allowed_origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)
# Routersfrom routers.livekit_router import router as livekit_routerfrom routers.ws_agent import router as agent_routerfrom routers.ws_supervisor import router as supervisor_routerfrom routers.knowledge import router as knowledge_routerfrom routers.calls import router as calls_routerfrom routers.eval import router as eval_routerfrom routers.coaching import router as coaching_routerfrom routers.auth_router import router as auth_routerfrom routers.tenant_router import router as tenant_routerfrom routers.debug_router import router as debug_routerfrom routers.orchestration_router import router as orchestration_router
app.include_router(auth_router)app.include_router(livekit_router)app.include_router(agent_router)app.include_router(supervisor_router)app.include_router(knowledge_router)app.include_router(calls_router)app.include_router(eval_router)app.include_router(coaching_router)app.include_router(tenant_router)app.include_router(debug_router)app.include_router(orchestration_router)
@app.get("/api/health")async def health(): db_status = "disconnected" customer_count = 0 agent_count = 0
customer_count = 0 agent_count = 0 try: async with AsyncSessionLocal() as session: result = await session.execute(text("SELECT COUNT(*) FROM customers")) customer_count = result.scalar() result = await session.execute(text("SELECT COUNT(*) FROM agent_profiles")) agent_count = result.scalar() db_status = "connected" except Exception: db_status = "disconnected"
chroma_status = "disconnected" try: _ = app.state.kb_collection _ = app.state.calls_collection chroma_status = "connected" except Exception: pass
return { "status": "ok", "db": db_status, "chroma": chroma_status, "customers_seeded": customer_count, "agents_seeded": agent_count, }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253import asynciofrom logging.config import fileConfig
from sqlalchemy.ext.asyncio import create_async_engine
from alembic import context
from config import settingsfrom database import Base
# Import all models so Alembic sees the metadataimport models # noqa: F401
config = context.configif config.config_file_name is not None: fileConfig(config.config_file_name)
target_metadata = Base.metadata
def run_migrations_offline() -> None: url = settings.database_url context.configure( url=url, target_metadata=target_metadata, literal_binds=True, dialect_opts={"paramstyle": "named"}, ) with context.begin_transaction(): context.run_migrations()
def do_run_migrations(connection): context.configure(connection=connection, target_metadata=target_metadata) with context.begin_transaction(): context.run_migrations()
async def run_async_migrations() -> None: engine = create_async_engine(settings.database_url) async with engine.connect() as connection: await connection.run_sync(do_run_migrations) await engine.dispose()
def run_migrations_online() -> None: asyncio.run(run_async_migrations())
if context.is_offline_mode(): run_migrations_offline()else: run_migrations_online()12345678910111213141516171819202122232425"""${message}
Revision ID: ${up_revision}Revises: ${down_revision | comma,n}Create Date: ${create_date}
"""from typing import Sequence, Union
from alembic import opimport sqlalchemy as sa${imports if imports else ""}
revision: str = ${repr(up_revision)}down_revision: Union[str, None] = ${repr(down_revision)}branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None: ${upgrades if upgrades else "pass"}
def downgrade() -> None: ${downgrades if downgrades else "pass"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139"""Initial schema — all tables and indexes
Revision ID: 001Revises:Create Date: 2026-05-16"""from typing import Sequence, Union
from alembic import op
revision: str = "001"down_revision: Union[str, None] = Nonebranch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: op.execute('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"')
op.execute(""" CREATE TABLE IF NOT EXISTS customers ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), name VARCHAR(255) NOT NULL, phone VARCHAR(20) UNIQUE NOT NULL, email VARCHAR(255), account_type VARCHAR(50) DEFAULT 'standard', address TEXT, order_history JSONB DEFAULT '[]', notes TEXT, created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ) """)
op.execute(""" CREATE TABLE IF NOT EXISTS agent_profiles ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), name VARCHAR(255) NOT NULL, email VARCHAR(255) UNIQUE NOT NULL, team VARCHAR(100), status VARCHAR(20) DEFAULT 'offline', created_at TIMESTAMPTZ DEFAULT NOW() ) """)
op.execute(""" CREATE TABLE IF NOT EXISTS calls ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), customer_id UUID REFERENCES customers(id), agent_id UUID REFERENCES agent_profiles(id), started_at TIMESTAMPTZ DEFAULT NOW(), ended_at TIMESTAMPTZ, duration_secs INTEGER, call_type VARCHAR(20), resolution VARCHAR(20), escalated BOOLEAN DEFAULT FALSE, escalation_reason VARCHAR(100), escalation_at TIMESTAMPTZ, voice_ai_summary TEXT, acw_summary TEXT, crm_updated BOOLEAN DEFAULT FALSE, status VARCHAR(20) DEFAULT 'active' ) """)
op.execute(""" CREATE TABLE IF NOT EXISTS transcripts ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), call_id UUID REFERENCES calls(id) ON DELETE CASCADE, speaker VARCHAR(20), content TEXT NOT NULL, sentiment FLOAT, timestamp TIMESTAMPTZ DEFAULT NOW() ) """)
op.execute(""" CREATE TABLE IF NOT EXISTS eval_scores ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), call_id UUID REFERENCES calls(id) ON DELETE CASCADE, agent_id UUID REFERENCES agent_profiles(id), guardrail_adherence INTEGER, resolution_rate INTEGER, containment INTEGER, caller_satisfaction FLOAT, handle_time_score INTEGER, disclosure_score INTEGER, overall_score INTEGER, pass_fail VARCHAR(4), violations JSONB DEFAULT '[]', coaching_note TEXT, strengths JSONB DEFAULT '[]', created_at TIMESTAMPTZ DEFAULT NOW() ) """)
op.execute(""" CREATE TABLE IF NOT EXISTS kb_documents ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), filename VARCHAR(255) NOT NULL, file_type VARCHAR(10), category VARCHAR(100) DEFAULT 'general', chunk_count INTEGER DEFAULT 0, status VARCHAR(20) DEFAULT 'processing', uploaded_at TIMESTAMPTZ DEFAULT NOW() ) """)
op.execute(""" CREATE TABLE IF NOT EXISTS coaching_packs ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), agent_id UUID REFERENCES agent_profiles(id), generated_at TIMESTAMPTZ DEFAULT NOW(), calls_analyzed INTEGER DEFAULT 0, overall_trend VARCHAR(20), strengths JSONB DEFAULT '[]', improvements JSONB DEFAULT '[]', action_items JSONB DEFAULT '[]', score_summary JSONB DEFAULT '{}' ) """)
# Indexes op.execute("CREATE INDEX IF NOT EXISTS idx_calls_customer ON calls(customer_id)") op.execute("CREATE INDEX IF NOT EXISTS idx_calls_agent ON calls(agent_id)") op.execute("CREATE INDEX IF NOT EXISTS idx_calls_status ON calls(status)") op.execute("CREATE INDEX IF NOT EXISTS idx_transcripts_call ON transcripts(call_id)") op.execute("CREATE INDEX IF NOT EXISTS idx_eval_scores_call ON eval_scores(call_id)") op.execute("CREATE INDEX IF NOT EXISTS idx_eval_scores_agent ON eval_scores(agent_id)")
def downgrade() -> None: op.execute("DROP TABLE IF EXISTS coaching_packs CASCADE") op.execute("DROP TABLE IF EXISTS kb_documents CASCADE") op.execute("DROP TABLE IF EXISTS eval_scores CASCADE") op.execute("DROP TABLE IF EXISTS transcripts CASCADE") op.execute("DROP TABLE IF EXISTS calls CASCADE") op.execute("DROP TABLE IF EXISTS agent_profiles CASCADE") op.execute("DROP TABLE IF EXISTS customers CASCADE")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253"""Add leads and demo_appointments tables
Revision ID: 002Revises: 001Create Date: 2026-05-19"""from typing import Sequence, Union
from alembic import op
revision: str = "002"down_revision: Union[str, None] = "001"branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: op.execute(""" CREATE TABLE IF NOT EXISTS leads ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), call_id UUID REFERENCES calls(id) ON DELETE SET NULL, name VARCHAR(255), email VARCHAR(255), phone VARCHAR(50), company VARCHAR(255), intent VARCHAR(100), interest_notes TEXT, status VARCHAR(20) DEFAULT 'new', created_at TIMESTAMPTZ DEFAULT NOW() ) """)
op.execute("CREATE INDEX IF NOT EXISTS idx_leads_call ON leads(call_id)") op.execute("CREATE INDEX IF NOT EXISTS idx_leads_email ON leads(email)") op.execute("CREATE INDEX IF NOT EXISTS idx_leads_status ON leads(status)")
op.execute(""" CREATE TABLE IF NOT EXISTS demo_appointments ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), lead_id UUID REFERENCES leads(id) ON DELETE CASCADE, call_id UUID REFERENCES calls(id) ON DELETE SET NULL, requested_time VARCHAR(255), status VARCHAR(20) DEFAULT 'pending', created_at TIMESTAMPTZ DEFAULT NOW() ) """)
op.execute("CREATE INDEX IF NOT EXISTS idx_appointments_lead ON demo_appointments(lead_id)")
def downgrade() -> None: op.execute("DROP TABLE IF EXISTS demo_appointments") op.execute("DROP TABLE IF EXISTS leads")1234567891011121314151617181920212223242526"""Add confirmed_time to demo_appointments
Revision ID: 003Revises: 002Create Date: 2026-05-20"""from typing import Sequence, Unionfrom alembic import op
revision: str = "003"down_revision: Union[str, None] = "002"branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: op.execute(""" ALTER TABLE demo_appointments ADD COLUMN IF NOT EXISTS confirmed_time TIMESTAMPTZ, ADD COLUMN IF NOT EXISTS slot_label VARCHAR(100) """)
def downgrade() -> None: op.execute("ALTER TABLE demo_appointments DROP COLUMN IF EXISTS confirmed_time") op.execute("ALTER TABLE demo_appointments DROP COLUMN IF EXISTS slot_label")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172"""Scheduling upgrade: slot_key race prevention, UTC storage, reschedule tracking
Revision ID: 004Revises: 003Create Date: 2026-05-20
Changes: - slot_key VARCHAR(32): UTC "YYYY-MM-DD-HH" key for 1-hour slot uniqueness - UNIQUE index on slot_key WHERE status = 'confirmed' — prevents concurrent booking races - user_timezone VARCHAR(50): caller's inferred timezone for display - previous_confirmed_time: original slot before reschedule - rescheduled_at / reschedule_count: reschedule history - status 'rescheduled' added (was only 'confirmed'|'cancelled'|'pending') - Indexes for common query patterns"""from typing import Sequence, Unionfrom alembic import op
revision: str = "004"down_revision: Union[str, None] = "003"branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: # New columns on demo_appointments op.execute(""" ALTER TABLE demo_appointments ADD COLUMN IF NOT EXISTS slot_key VARCHAR(32), ADD COLUMN IF NOT EXISTS user_timezone VARCHAR(50) DEFAULT 'Asia/Kolkata', ADD COLUMN IF NOT EXISTS previous_confirmed_time TIMESTAMPTZ, ADD COLUMN IF NOT EXISTS rescheduled_at TIMESTAMPTZ, ADD COLUMN IF NOT EXISTS reschedule_count INTEGER DEFAULT 0 """)
# Backfill slot_key from existing confirmed_time rows (UTC hour bucket) op.execute(""" UPDATE demo_appointments SET slot_key = TO_CHAR(confirmed_time AT TIME ZONE 'UTC', 'YYYY-MM-DD-HH24') WHERE confirmed_time IS NOT NULL AND slot_key IS NULL """)
# UNIQUE index on slot_key for confirmed appointments only. # Partial index: cancelled/rescheduled rows don't block the slot. # This is the primary race-condition guard — DB enforces uniqueness even under # concurrent inserts that both passed the pre-check query. op.execute(""" CREATE UNIQUE INDEX IF NOT EXISTS uniq_confirmed_slot ON demo_appointments(slot_key) WHERE status = 'confirmed' """)
# Supporting indexes op.execute("CREATE INDEX IF NOT EXISTS idx_appointments_call ON demo_appointments(call_id)") op.execute("CREATE INDEX IF NOT EXISTS idx_appointments_status ON demo_appointments(status)") op.execute("CREATE INDEX IF NOT EXISTS idx_appointments_time ON demo_appointments(confirmed_time)")
def downgrade() -> None: op.execute("DROP INDEX IF EXISTS uniq_confirmed_slot") op.execute("DROP INDEX IF EXISTS idx_appointments_call") op.execute("DROP INDEX IF EXISTS idx_appointments_status") op.execute("DROP INDEX IF EXISTS idx_appointments_time") op.execute(""" ALTER TABLE demo_appointments DROP COLUMN IF EXISTS slot_key, DROP COLUMN IF EXISTS user_timezone, DROP COLUMN IF EXISTS previous_confirmed_time, DROP COLUMN IF EXISTS rescheduled_at, DROP COLUMN IF EXISTS reschedule_count """)1234567891011121314151617181920212223242526272829303132333435363738394041"""Add customer_rating, customer_feedback, feedback_submitted_at to calls
Revision ID: 005Revises: 004Create Date: 2026-05-24
Changes: - customer_rating INTEGER CHECK (1–5): optional post-call star rating from visitor - customer_feedback TEXT: optional freeform comment, max 1000 chars enforced in app layer - feedback_submitted_at TIMESTAMPTZ: when feedback was submitted (NULL = not submitted)
Existing rows migrate cleanly: all three columns are nullable with no default."""from typing import Sequence, Union
import sqlalchemy as safrom alembic import op
revision: str = "005"down_revision: Union[str, None] = "004"branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: op.add_column("calls", sa.Column("customer_rating", sa.Integer(), nullable=True)) op.add_column("calls", sa.Column("customer_feedback", sa.Text(), nullable=True)) op.add_column("calls", sa.Column("feedback_submitted_at", sa.DateTime(timezone=True), nullable=True))
op.create_check_constraint( "ck_calls_customer_rating_range", "calls", "customer_rating IS NULL OR (customer_rating >= 1 AND customer_rating <= 5)", )
def downgrade() -> None: op.drop_constraint("ck_calls_customer_rating_range", "calls", type_="check") op.drop_column("calls", "feedback_submitted_at") op.drop_column("calls", "customer_feedback") op.drop_column("calls", "customer_rating")123456789101112131415161718192021222324252627"""Add password_hash to agent_profiles
Revision ID: 006Revises: 005Create Date: 2026-05-25
Changes: - password_hash VARCHAR(255) nullable: bcrypt hash of the agent's login password NULL = agent not yet given a password (legacy seed rows)"""from typing import Sequence, Union
import sqlalchemy as safrom alembic import op
revision: str = "006"down_revision: Union[str, None] = "005"branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: op.add_column("agent_profiles", sa.Column("password_hash", sa.String(255), nullable=True))
def downgrade() -> None: op.drop_column("agent_profiles", "password_hash")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152"""Add tenant_configs table
Revision ID: 007Revises: 006Create Date: 2026-05-26"""from typing import Sequence, Union
from alembic import op
revision: str = "007"down_revision: Union[str, None] = "006"branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: op.execute(""" CREATE TABLE IF NOT EXISTS tenant_configs ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), tenant_id VARCHAR(100) UNIQUE NOT NULL, agent_name VARCHAR(100) NOT NULL, industry VARCHAR(100),
voice_system_prompt TEXT NOT NULL, context_prompt TEXT NOT NULL, companion_mid_call_prompt TEXT, companion_acw_prompt TEXT, qa_prompt TEXT, coaching_prompt TEXT,
tool_configs JSONB DEFAULT '{}', workflow_configs JSONB DEFAULT '{}', kb_collections JSONB DEFAULT '[]',
escalation_reasons JSONB DEFAULT '[]', support_categories JSONB DEFAULT '[]',
is_active BOOLEAN DEFAULT TRUE, created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ) """)
op.execute( "CREATE INDEX IF NOT EXISTS idx_tenant_configs_active " "ON tenant_configs(is_active) WHERE is_active = TRUE" )
def downgrade() -> None: op.execute("DROP TABLE IF EXISTS tenant_configs CASCADE")12345678910111213141516171819202122232425262728293031323334353637383940414243"""Add action_audit_logs table for orchestration HITL audit trail
Revision ID: 008Revises: 007Create Date: 2026-05-28"""from typing import Sequence, Union
from alembic import op
revision: str = "008"down_revision: Union[str, None] = "007"branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: op.execute(""" CREATE TABLE IF NOT EXISTS action_audit_logs ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), call_id VARCHAR(64) NOT NULL, action_name VARCHAR(64) NOT NULL, approved_by VARCHAR(128) NOT NULL, execution_id VARCHAR(64) NOT NULL, payload JSONB NOT NULL DEFAULT '{}', result JSONB NOT NULL DEFAULT '{}', success BOOLEAN NOT NULL DEFAULT TRUE, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), CONSTRAINT uq_action_audit_execution_id UNIQUE (execution_id) ) """) op.execute(""" CREATE INDEX IF NOT EXISTS idx_action_audit_logs_call_id ON action_audit_logs(call_id) """) op.execute(""" CREATE INDEX IF NOT EXISTS idx_action_audit_logs_created_at ON action_audit_logs(created_at) """)
def downgrade() -> None: op.execute("DROP TABLE IF EXISTS action_audit_logs;").env.exampleAdded+30
agents/__init__.pyAdded
agents/coaching_agent.pyAdded+129
agents/companion_agent.pyAdded+484
agents/qa_agent.pyAdded+263
agents/scheduling_agent.pyAdded+690
agents/voice_agent.pyAdded+6
alembic.iniAdded+38
coaching/__init__.pyAdded
coaching/coaching_manager.pyAdded+145
config.pyAdded+54
config_loader.pyAdded+51
constants/__init__.pyAdded
constants/transaction_status.pyAdded+34
database.pyAdded+38
events/__init__.pyAdded
events/emitter.pyAdded+31
guardrails/__init__.pyAdded+55
guardrails/auth_gate.pyAdded+39
guardrails/rate_limiter.pyAdded+58
guardrails/scope.pyAdded+40
guardrails/tool_permissions.pyAdded+65
guardrails/validator.pyAdded+65
k8s/worker-deployment.yamlAdded+152
knowledge/__init__.pyAdded
knowledge/document_parser.pyAdded+271
knowledge/embeddings.pyAdded+44
knowledge/kb_manager.pyAdded+596
knowledge/seed.pyAdded+77
knowledge/seed_docs/_archive/wavvy_combined.mdAdded+418
knowledge/seed_docs/fin/account_security.mdAdded+130
knowledge/seed_docs/fin/dispute_resolution.mdAdded+99
knowledge/seed_docs/fin/fin_overview.mdAdded+74
knowledge/seed_docs/fin/fraud_escalation.mdAdded+81
knowledge/seed_docs/fin/kyc_verification.mdAdded+96
knowledge/seed_docs/fin/payment_failure_sop.mdAdded+102
knowledge/seed_docs/fin/refund_policy.mdAdded+78
knowledge/seed_docs/fin/transaction_status_guide.mdAdded+189
main.pyAdded+161
migrations/__init__.pyAdded
migrations/env.pyAdded+53
migrations/script.py.makoAdded+25
migrations/versions/001_initial.pyAdded+139
migrations/versions/002_leads_appointments.pyAdded+53
migrations/versions/003_appointment_confirmed_time.pyAdded+26
migrations/versions/004_scheduling_upgrade.pyAdded+72
migrations/versions/005_call_feedback.pyAdded+41
migrations/versions/006_agent_password.pyAdded+27
migrations/versions/007_tenant_config.pyAdded+52
migrations/versions/008_action_audit_logs.pyAdded+43