Charan S commited on
Commit ·
6e978f7
1
Parent(s): 9960f53
feat: Voice AI Coaching
Browse filesFiles changed (26)
- .env.example+20-6
- agents/coaching_agent.py+17-11
- agents/scheduling_agent.pyDeleted-690
- coaching/coaching_manager.py+97-57
- config.py+3-4
- guardrails/tool_permissions.py+2-5
- main.py+155-12
- models/escalation_packet.py+1-1
- routers/calls.py+27-6
- routers/coaching.py+25-52
- routers/livekit_router.py+15-3
- routers/orchestration_router.py+30-1
- routers/ws_agent.py+7
- seed.py+41-24
- session/call_session.py-11
- tools/registry.py-70
- tools/wavvy_tools.py+54-291
- voice/agent_session.py+6-3
- voice/agent_tools.py+1-141
- voice/issue_classifier.py+60-2
- voice/orchestrator.py+1-5
- voice/reminder_service.pyDeleted-98
- voice/tool_recovery.py+1-7
- voice/wavvy_agent.py+37-8
- voice/workflow_engine.pyDeleted-264
- workflow/node_executor.py+11-1
14 unmodified lines1516171819202122181920212223242526272828293031323334353637383940414243444546474814 unmodified lines# 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_...# TTS — Cartesia (required for voice output)# https://cartesia.ai — get an API key from the dashboardCARTESIA_API_KEY=sk_car_...CARTESIA_VOICE_ID=f039066f-cdb7-45ed-b51d-1034ae2f04a0CARTESIA_MODEL=sonic-2
# Database + storageDATABASE_URL=postgresql+asyncpg://wavvy:wavvy@localhost:5433/wavvyCHROMA_PERSIST_DIR=./chroma_db
# Frontend URLs (for CORS — update for production)# Frontend URLs (for CORS allowlist)# Local dev — Vite default ports:FRONTEND_LANDING_URL=http://localhost:5173FRONTEND_AGENT_URL=http://localhost:5174FRONTEND_ADMIN_URL=http://localhost:5175# Production (HuggingFace Spaces backend) — set these to your Vercel deployment URLs:# FRONTEND_LANDING_URL=https://your-landing.vercel.app# FRONTEND_AGENT_URL=https://your-agent.vercel.app# FRONTEND_ADMIN_URL=https://your-admin.vercel.app
# Backend public URL (used for SIP webhook target)# Local dev:PUBLIC_BACKEND_URL=http://localhost:8000# Production:# PUBLIC_BACKEND_URL=https://your-space.hf.space
ENVIRONMENT=development# Set to "production" on HuggingFace — enables strict CORS (specific origins only)# ENVIRONMENT=production
SECRET_KEY=change-in-production4 unmodified lines567891089101112131213141516171819202122231819242526212227282930314 unmodified lines3637383339404136424344454 unmodified lines
_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._DEFAULT_COACHING_PROMPT = """You are a Voice AI performance analyst.You will receive a list of completed call evaluations for a Voice AI agent.Generate an optimization coaching pack that helps the product team improve the Voice AI's performance.
Be specific — reference actual patterns across the calls (scores, common violations, resolution trends).Be constructive and actionable. Never generic.Be specific — identify recurring patterns across calls:- Which rubric criteria consistently score low?- What violations appear most often?- Where does the AI fail to resolve before escalating?- What types of calls show the worst satisfaction scores?
Output actionable recommendations for the team: prompt tuning, workflow node adjustments, KB content gaps.Never be generic. Every recommendation must be grounded in the evaluation data provided.
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"], "strengths": ["what the Voice AI consistently does well — pattern-based, specific"], "improvements": ["specific failure pattern with data backing — e.g. 'resolution_rate averages 52% — AI fails to confirm outcomes before ending calls'"], "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"} {"priority": "high" | "medium" | "low", "action": "specific optimization step for the team", "metric": "what to measure to confirm improvement"}, {"priority": "high" | "medium" | "low", "action": "specific optimization step for the team", "metric": "what to measure to confirm improvement"} ], "score_summary": { "avg_overall": 75,4 unmodified lines "pass_rate": 0.67, "calls_analyzed": 3 }, "coaching_note": "One paragraph personalized coaching message for the agent." "coaching_note": "One paragraph analysis for the team: what patterns emerged, what to prioritize in the next iteration of the Voice AI."}
Temperature 0.4. Focus on actionable improvements backed by data from the evaluations provided."""Temperature 0.4. Ground every finding in the evaluation data provided."""
def _get_coaching_prompt() -> str: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})4 unmodified lines5678989101112131415161617171819202121222324252627282829303031313233333435363738394034353637383940414243444546464748494849505152535455565758596061626364656667685152697071727374757677787980818283848586878889909192939495969798991001011021031041055510610757581081091101111126211311411565116117118119697012012172122741231241251268 unmodified lines13513613789909113813914014114214397981441451461471481021491501511521061531541091101111121551561571141151161171181581591601611621631641651661671681251691701711 unmodified line1731741751331761351361371381771781791401411421431441801811821831841854 unmodified linesfrom database import AsyncSessionLocalfrom models.coaching_pack import CoachingPackfrom models.eval_score import EvalScorefrom models.agent_profile import AgentProfilefrom sqlalchemy import select, funcfrom sqlalchemy import select, text
logger = logging.getLogger(__name__)
MIN_CALLS_REQUIRED = 3
# ── Voice AI eval fetching ────────────────────────────────────────────────────
async def get_agent_evals(agent_id: str, limit: int = 20) -> list[dict]: """Fetch the last `limit` scored calls for an agent."""async def get_voice_ai_evals(limit: int = 20) -> list[dict]: """Fetch the last `limit` scored Voice AI calls (agent_id IS NULL = AI-handled).""" async with AsyncSessionLocal() as db: result = await db.execute( select(EvalScore) .where(EvalScore.agent_id == uuid.UUID(agent_id)) .where(EvalScore.agent_id == None) .order_by(EvalScore.created_at.desc()) .limit(limit) ) rows = result.scalars().all() return [ { "call_id": str(r.call_id), "call_id": str(r.call_id), "guardrail_adherence": r.guardrail_adherence, "resolution_rate": r.resolution_rate, "containment": r.containment, "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, "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 def get_voice_ai_stats() -> dict: """Aggregate performance stats for the Voice AI coaching overview panel.""" async with AsyncSessionLocal() as db: result = await db.execute( select(AgentProfile).where(AgentProfile.id == uuid.UUID(agent_id)) r = await db.execute( text(""" SELECT COUNT(*) AS total_scored, ROUND(AVG(overall_score)) AS avg_score, ROUND(AVG(CASE WHEN pass_fail = 'PASS' THEN 1 ELSE 0 END)::NUMERIC, 2) AS pass_rate, ROUND(AVG(guardrail_adherence)) AS avg_guardrail, ROUND(AVG(resolution_rate)) AS avg_resolution, ROUND(AVG(containment)) AS avg_containment, ROUND(AVG(caller_satisfaction)::NUMERIC, 2) AS avg_satisfaction, ROUND(AVG(CASE WHEN created_at >= NOW() - INTERVAL '7 days' THEN overall_score END)) AS avg_score_7d, ROUND(AVG(CASE WHEN created_at >= NOW() - INTERVAL '14 days' AND created_at < NOW() - INTERVAL '7 days' THEN overall_score END)) AS avg_score_prev_7d FROM eval_scores WHERE agent_id IS NULL """) ) agent = result.scalar_one_or_none() return agent.name if agent else "Unknown Agent" row = r.mappings().first()
total_scored = int(row["total_scored"] or 0) avg_score = int(row["avg_score"]) if row["avg_score"] else None pass_rate = float(row["pass_rate"]) if row["pass_rate"] else 0.0 avg_guardrail = int(row["avg_guardrail"]) if row["avg_guardrail"] else None avg_resolution = int(row["avg_resolution"]) if row["avg_resolution"] else None avg_containment = int(row["avg_containment"]) if row["avg_containment"] else None avg_satisfaction = float(row["avg_satisfaction"]) if row["avg_satisfaction"] else None avg_7d = int(row["avg_score_7d"]) if row["avg_score_7d"] else None avg_prev_7d = int(row["avg_score_prev_7d"]) if row["avg_score_prev_7d"] else None
trend = "stable" if avg_7d is not None and avg_prev_7d is not None: diff = avg_7d - avg_prev_7d if diff >= 3: trend = "improving" elif diff <= -3: trend = "declining"
return { "total_scored": total_scored, "avg_score": avg_score, "pass_rate": pass_rate, "avg_guardrail": avg_guardrail, "avg_resolution": avg_resolution, "avg_containment": avg_containment, "avg_satisfaction": avg_satisfaction, "avg_score_7d": avg_7d, "trend": trend, "can_generate": total_scored >= MIN_CALLS_REQUIRED, "calls_needed": max(0, MIN_CALLS_REQUIRED - total_scored), }
# ── Pack generation ───────────────────────────────────────────────────────────
async def generate_pack(agent_id: str) -> dict:async def generate_voice_ai_pack() -> dict: """ Generate a coaching pack for an agent. Requires >= 3 scored calls. Returns the saved pack as a dict. Generate a coaching pack analyzing Voice AI performance. Requires >= 3 scored AI calls. agent_id is NULL for Voice AI packs. """ from agents.coaching_agent import generate_coaching_pack
evals = await get_agent_evals(agent_id) evals = await get_voice_ai_evals() if len(evals) < MIN_CALLS_REQUIRED: raise ValueError( f"Not enough scored calls to generate a coaching pack. " f"Not enough scored Voice AI calls. " 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) pack_data = await generate_coaching_pack("Voice AI", evals)
# Persist to DB pack = CoachingPack( agent_id=uuid.UUID(agent_id), agent_id=None, calls_analyzed=pack_data["score_summary"]["calls_analyzed"], overall_trend=pack_data.get("overall_trend", "stable"), strengths=pack_data.get("strengths", []),8 unmodified lines await db.refresh(pack)
return { "pack_id": str(pack.id), "agent_id": agent_id, "agent_name": agent_name, "pack_id": str(pack.id), "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 def get_voice_ai_packs() -> list[dict]: """Return all Voice AI coaching packs (agent_id IS NULL), newest first.""" async with AsyncSessionLocal() as db: result = await db.execute( select(CoachingPack) .where(CoachingPack.agent_id == uuid.UUID(agent_id)) .where(CoachingPack.agent_id == None) .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, "pack_id": str(r.id), "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, "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))1 unmodified line 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, "pack_id": str(pack.id), "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, "overall_trend": pack.overall_trend, "strengths": pack.strengths, "improvements": pack.improvements, "action_items": pack.action_items, "score_summary": pack.score_summary, }43 unmodified lines444546474748495051525352535454555643 unmodified lines
@property def allowed_origins(self) -> list[str]: origins = [ if self.environment == "development": return ["*"] return [ self.frontend_landing_url, self.frontend_agent_url, self.frontend_admin_url, ] if self.environment == "development": origins.append("*") return origins
settings = Settings()2 unmodified lines345667813 unmodified lines22232426252627292829303231323334373536372 unmodified lines# 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_status13 unmodified lines
TOOL_PERMISSIONS: dict[ConversationStage, set[str]] = { ConversationStage.GREETING: { "capture_lead", "verify_account", "escalate_to_human", "verify_account", "escalate_to_human", }, ConversationStage.DISCOVERY: { "capture_lead", "verify_account", "escalate_to_human", "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",174 unmodified lines17517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933047 unmodified lines3783793803813823833843853863872342352362372383883892412422432442452463903913921 unmodified line394395396254397398399400174 unmodified lines logger.info("KB backfill: synced %d doc(s) from ChromaDB → kb_documents", inserted)
async def _backfill_call_fields() -> None: """ One-time backfill for calls that completed before duration_secs, resolution, and customer_id were written on call end. Safe to run repeatedly. Also purges stub calls (no duration, no meaningful resolution) from the DB. """ import re as _re
_WORD_TO_DIGIT = { 'zero': '0', 'one': '1', 'two': '2', 'three': '3', 'four': '4', 'five': '5', 'six': '6', 'seven': '7', 'eight': '8', 'nine': '9', } _STOP_WORDS = { 'hey', 'thanks', 'this', 'what', 'your', 'sure', 'done', 'please', 'sorry', 'great', 'okay', 'the', 'and', 'for', 'but', 'from', 'with', 'can', 'will', 'may', 'let', 'here', 'now', 'when', 'well', 'just', 'also', 'once', 'next', 'hi', 'i', }
def _spoken_phones(text: str) -> list[str]: """Extract phone numbers from spoken-digit sequences (≥6 consecutive digit words).""" words = text.lower().split() buf: list[str] = [] result: list[str] = [] for w in words: clean = _re.sub(r'[^a-z]', '', w) if clean in _WORD_TO_DIGIT: buf.append(_WORD_TO_DIGIT[clean]) else: if len(buf) >= 6: result.append(''.join(buf)) buf = [] if len(buf) >= 6: result.append(''.join(buf)) return result
try: async with AsyncSessionLocal() as db: # Fix completed calls missing duration/resolution r = await db.execute(text(""" UPDATE calls SET duration_secs = EXTRACT(EPOCH FROM (ended_at - started_at))::INTEGER, resolution = CASE WHEN escalated = TRUE THEN 'escalated' ELSE 'resolved' END WHERE status = 'completed' AND ended_at IS NOT NULL AND (duration_secs IS NULL OR resolution IS NULL) """)) if r.rowcount: logger.info("call backfill: fixed %d completed call(s) missing duration/resolution", r.rowcount)
# Purge stub calls — no duration, no resolution, and not escalated d = await db.execute(text(""" DELETE FROM calls WHERE duration_secs IS NULL AND escalated = FALSE AND (resolution IS NULL OR resolution NOT IN ('resolved', 'escalated')) """)) if d.rowcount: logger.info("call cleanup: deleted %d stub call(s) with no duration or resolution", d.rowcount)
# Backfill customer_id for unlinked calls. # Pass 1: typed 10-digit phone numbers in voice_ai_summary. # Pass 2: spoken-digit sequences from customer transcript turns. # Pass 3: first name the AI addressed the customer by in voice_ai_summary. unlinked_summary = await db.execute(text(""" SELECT id, voice_ai_summary FROM calls WHERE customer_id IS NULL AND voice_ai_summary IS NOT NULL """)) unlinked_rows = unlinked_summary.mappings().all() linked = 0 linked_ids: set = set()
for row in unlinked_rows: summary = row["voice_ai_summary"] or "" phones = _re.findall(r'\b\d{10}\b', summary) + _spoken_phones(summary) for phone in phones: cust = await db.execute( text("SELECT id FROM customers WHERE phone LIKE :s"), {"s": f"%{phone}"}, ) m = cust.first() if m: await db.execute( text("UPDATE calls SET customer_id = :cid WHERE id = :id"), {"cid": m[0], "id": row["id"]}, ) linked_ids.add(str(row["id"])) linked += 1 break
# Pass 2: spoken phones from transcript turns unlinked_transcripts = await db.execute(text(""" SELECT DISTINCT c.id, t.content FROM calls c JOIN transcripts t ON t.call_id = c.id WHERE c.customer_id IS NULL AND t.speaker = 'customer' """)) for row in unlinked_transcripts.mappings().all(): if str(row["id"]) in linked_ids: continue for phone in _spoken_phones(row["content"] or "") + _re.findall(r'\b\d{10}\b', row["content"] or ""): cust = await db.execute( text("SELECT id FROM customers WHERE phone LIKE :s"), {"s": f"%{phone}"}, ) m = cust.first() if m: await db.execute( text("UPDATE calls SET customer_id = :cid WHERE id = :id"), {"cid": m[0], "id": row["id"]}, ) linked_ids.add(str(row["id"])) linked += 1 break
# Pass 3: first name from summary (pattern: ", Name!" or ", Name.") unlinked_names = await db.execute(text(""" SELECT id, voice_ai_summary FROM calls WHERE customer_id IS NULL AND voice_ai_summary IS NOT NULL """)) for row in unlinked_names.mappings().all(): if str(row["id"]) in linked_ids: continue names = _re.findall(r',\s+([A-Z][a-z]{2,12})[!?.]', row["voice_ai_summary"] or "") for name in dict.fromkeys(n for n in names if n.lower() not in _STOP_WORDS): cust = await db.execute( text("SELECT id FROM customers WHERE name ILIKE :n"), {"n": f"{name}%"}, ) m = cust.first() if m: await db.execute( text("UPDATE calls SET customer_id = :cid WHERE id = :id"), {"cid": m[0], "id": row["id"]}, ) linked_ids.add(str(row["id"])) linked += 1 break
if linked: logger.info("call backfill: linked %d call(s) to customers via phone/name extraction", linked)
await db.commit() except Exception: logger.exception("_backfill_call_fields: unexpected error (non-fatal)")
@asynccontextmanagerasync def lifespan(app: FastAPI): # Load active tenant config first — all voice/agent code depends on it47 unmodified lines # frontend sees an empty list even though RAG has content. await _backfill_kb_postgres(collections_dict)
# Backfill duration_secs + resolution for calls that ended before these fields # were written on call close (historical calls all have NULL for both). await _backfill_call_fields()
# 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()
1 unmodified line
app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_origins=settings.allowed_origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"],13 unmodified lines141516171718192013 unmodified lines@dataclassclass EscalationPacket: call_id: str lead_id: str | None # set if capture_lead ran before escalation lead_id: str | None # customer id if identified before escalation name: str | None # prospect name email: str | None # prospect email (masked: ar***@company.com) phone: str | None # prospect phone (masked: ***210)293 unmodified lines2942952962972972982993002 unmodified lines3033043053063073063073083091 unmodified line3113123133153143153163173193203183193203215 unmodified lines327328329330331332333334335336337338339340341342343344345346347348349350351352293 unmodified lines
@router.get("/dashboard/kpis")async def dashboard_kpis(): """Today's aggregate KPIs.""" """All-time aggregate KPIs.""" async with AsyncSessionLocal() as db: result = await db.execute( text("""SELECT2 unmodified lines COUNT(*) FILTER (WHERE escalated=TRUE) as escalated, ROUND(AVG(duration_secs)) as avg_duration, COUNT(*) FILTER (WHERE call_type='voice_ai' AND resolution='resolved') as contained FROM calls WHERE started_at >= NOW() - INTERVAL '24 hours'""") FROM calls""") ) row = result.mappings().first()
1 unmodified line contained = row["contained"] or 0 containment_rate = round((contained / total * 100), 1) if total > 0 else 0
# Avg QA score from eval_scores today # Avg QA score across all scored calls async with AsyncSessionLocal() as db: eq = await db.execute( text("""SELECT ROUND(AVG(overall_score)) as avg_score FROM eval_scores WHERE created_at >= NOW() - INTERVAL '24 hours'""") FROM eval_scores""") ) eq_row = eq.mappings().first()
5 unmodified lines "avg_score": eq_row["avg_score"] if eq_row and eq_row["avg_score"] else None, "containment_rate": containment_rate, }
@router.get("/dashboard/trend")async def dashboard_trend(days: int = 7): """Per-day QA score average for the last N days (default 7).""" days = max(1, min(days, 30)) async with AsyncSessionLocal() as db: result = await db.execute( text(""" SELECT TO_CHAR(DATE_TRUNC('day', created_at AT TIME ZONE 'UTC'), 'Dy') AS day, DATE_TRUNC('day', created_at AT TIME ZONE 'UTC') AS date, ROUND(AVG(overall_score)) AS avg_score FROM eval_scores WHERE created_at >= NOW() - INTERVAL '1 day' * :days GROUP BY DATE_TRUNC('day', created_at AT TIME ZONE 'UTC') ORDER BY date ASC """), {"days": days}, ) rows = result.mappings().all()
return [{"day": r["day"], "avg_score": int(r["avg_score"])} for r in rows]12234561 unmodified line891010111211121314151617181920212223242526141527281729303132212233343524253637383928294041424333444546474 unmodified lines5253544445464748495051525354555657585960616263646566676869707172737475767778798081import loggingfrom fastapi import APIRouter, HTTPException, BackgroundTasksfrom fastapi import APIRouter, HTTPException
from coaching import coaching_manager
logger = logging.getLogger(__name__)1 unmodified linerouter = APIRouter()
@router.get("/api/coaching/packs/{agent_id}")async def get_coaching_packs(agent_id: str): """Return all coaching packs for an agent, newest first."""# ── Voice AI coaching (primary) ───────────────────────────────────────────────
@router.get("/api/coaching/voice-ai/stats")async def voice_ai_stats(): """Aggregate performance stats for all Voice AI scored calls.""" try: return await coaching_manager.get_voice_ai_stats() except Exception as e: logger.error(f"Error fetching Voice AI coaching stats: {e}") raise HTTPException(status_code=500, detail=str(e))
@router.get("/api/coaching/voice-ai/packs")async def voice_ai_packs(): """Return all Voice AI coaching packs, newest first.""" try: packs = await coaching_manager.get_packs_for_agent(agent_id) return packs return await coaching_manager.get_voice_ai_packs() except Exception as e: logger.error(f"Error fetching coaching packs for {agent_id}: {e}") logger.error(f"Error fetching Voice AI coaching packs: {e}") raise HTTPException(status_code=500, detail=str(e))
@router.post("/api/coaching/generate/{agent_id}")async def generate_coaching_pack(agent_id: str):@router.post("/api/coaching/voice-ai/generate")async def generate_voice_ai_pack(): """ Generate a new coaching pack for an agent. Requires >= 3 scored calls. Runs synchronously so the result is returned immediately. Generate a new Voice AI coaching pack from the most recent scored calls. Requires >= 3 scored Voice AI calls (agent_id IS NULL in eval_scores). """ try: pack = await coaching_manager.generate_pack(agent_id) return pack return await coaching_manager.generate_voice_ai_pack() except ValueError as e: raise HTTPException(status_code=422, detail=str(e)) except Exception as e: logger.error(f"Error generating coaching pack for {agent_id}: {e}") logger.error(f"Error generating Voice AI coaching pack: {e}") raise HTTPException(status_code=500, detail=str(e))
4 unmodified lines if not pack: raise HTTPException(status_code=404, detail="Coaching pack not found") return pack
@router.get("/api/agents")async def list_agents(): """Return all agent profiles — used by AgentSelector in admin.""" try: from database import AsyncSessionLocal from models.agent_profile import AgentProfile from models.eval_score import EvalScore from sqlalchemy import select, func
async with AsyncSessionLocal() as db: result = await db.execute( select(AgentProfile).order_by(AgentProfile.name) ) agents = result.scalars().all()
agent_list = [] for a in agents: # Count scored calls for this agent count_result = await db.execute( select(func.count()).where(EvalScore.agent_id == a.id) ) scored_calls = count_result.scalar() or 0
agent_list.append({ "agent_id": str(a.id), "name": a.name, "email": a.email, "team": a.team, "status": a.status, "scored_calls": scored_calls, })
return agent_list except Exception as e: logger.error(f"Error listing agents: {e}") raise HTTPException(status_code=500, detail=str(e))44 unmodified lines45464748484950512 unmodified lines54555657585960616263646165666768696370717273747576777844 unmodified lines logger.error(f"[{call_id}] DB call insert failed: {exc}")
async def _persist_call_end(call_id: str, conversation_history: list) -> None:async def _persist_call_end(call_id: str, conversation_history: list, session=None) -> None: try: turns = [ m for m in conversation_history2 unmodified lines full_text = " ".join(m["content"] for m in turns) speaker_map = {"user": "customer", "assistant": "voice_ai"}
escalated = getattr(session, "escalated", False) if session else False customer_id = getattr(session, "customer_id", None) if session else None resolution = "escalated" if escalated else "resolved"
async with AsyncSessionLocal() as db: await db.execute( text("""UPDATE calls SET status = 'completed', ended_at = NOW(), voice_ai_summary = :s voice_ai_summary = :s, resolution = :resolution, duration_secs = EXTRACT(EPOCH FROM (NOW() - started_at))::INTEGER, customer_id = COALESCE(customer_id, :cid) WHERE id = :id"""), {"id": uuid.UUID(call_id), "s": full_text[:2000] if full_text else None}, { "id": uuid.UUID(call_id), "s": full_text[:2000] if full_text else None, "resolution": resolution, "cid": uuid.UUID(customer_id) if customer_id else None, }, ) for m in turns: await db.execute(12234567891096 unmodified lines107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137"""Orchestration REST API — 3 endpoints.Orchestration REST API — 4 endpoints.
POST /api/orchestration/actions/execute — execute an approved action (via agent console)GET /api/orchestration/actions — list available actions + metadataGET /api/orchestration/history/{call_id} — audit trail for a specific callGET /api/orchestration/recent-actions — latest N actions across all calls"""import loggingfrom datetime import datetime96 unmodified lines } for row in rows ]
@router.get("/recent-actions")async def get_recent_actions(limit: int = 20, db: AsyncSession = Depends(get_db)): """Return the most recent HITL action audit log entries across all calls.""" from models.action_audit_log import ActionAuditLog from sqlalchemy import desc
limit = max(1, min(limit, 100)) result = await db.execute( select(ActionAuditLog) .order_by(desc(ActionAuditLog.created_at)) .limit(limit) ) rows = result.scalars().all() return [ { "id": str(row.id), "call_id": row.call_id, "action": row.action_name, "approved_by": row.approved_by, "success": row.success, "payload": row.payload, "result": row.result, "created_at": row.created_at.isoformat() if row.created_at else None, } for row in rows ]619 unmodified lines6206216226236246256266276286296306311 unmodified line633634635636637638639619 unmodified lines if sess: sess.completed_actions.add(action_name)
# Collect any reference numbers generated by this action so the agent # can read them to the customer or record them in the case notes. _ref_keys = ("inc_number", "res_number", "rfn_number", "dsp_number", "fraud_number", "case_number", "reference_number") reference_numbers = {k: result[k] for k in _ref_keys if result.get(k)}
# Notify frontend: success await ws.send_text(json.dumps({ "type": "action_result",1 unmodified line "success": True, "message": result.get("message", "Action completed successfully."), "updated_entities": result.get("updated_entities", {}), "reference_numbers": reference_numbers, }))
# Emit executed event to activity timeline123345638 unmodified lines4546474849484950515218 unmodified lines7172737475747576777834 unmodified lines11311411511611711611711811912065 unmodified lines18618718818919019119219318919019119279 unmodified lines272273274279275276277278279280281282283284283284285286287286288289290291292293294293295296297298241 unmodified lines54054154254154354454554654754854955055155254554655355455554855655755855956056156255556356456556671 unmodified lines638639640633634641642643644645646647648649650651652653654import asyncioimport jsonfrom datetime import date, datetime, timezonefrom datetime import date, datetime, timezone, timedelta
import bcryptfrom sqlalchemy import select, func, text38 unmodified lines "kyc_status": "verified", "fraud_hold_active": False, "transactions": [ {"txn_number": "TXN-6540", "merchant": "Amazon", "amount": 1890, "txn_type": "refund", "status": "refund_initiated", "txn_date": "2026-05-22"}, {"txn_number": "TXN-6540", "merchant": "IRCTC", "amount": 1890, "txn_type": "debit", "status": "processing", "txn_date": "2026-06-18"}, ], }, {18 unmodified lines "kyc_status": "verified", "fraud_hold_active": True, "transactions": [ {"txn_number": "TXN-9901", "merchant": "Unknown Vendor", "amount": 18000, "txn_type": "debit", "status": "flagged", "txn_date": "2026-05-25"}, {"txn_number": "TXN-9901", "merchant": "Unknown Overseas Vendor", "amount": 18000, "txn_type": "debit", "status": "completed", "txn_date": "2026-06-17"}, ], }, {34 unmodified lines "kyc_status": "verified", "fraud_hold_active": False, "transactions": [ {"txn_number": "TXN-2200", "merchant": "Myntra", "amount": 3200, "txn_type": "debit", "status": "refund_initiated", "txn_date": "2026-05-23"}, {"txn_number": "TXN-2200", "merchant": "Razorpay Subscription", "amount": 3200, "txn_type": "debit", "status": "completed", "txn_date": "2026-06-15"}, ], }, {65 unmodified lines
TOOLS — only call with real values the visitor spoke, never placeholders:
escalate_to_human — collect ONLY what isn't already known, then act: 1. Name — ask ONLY if not yet given this call. 2. Email — ask ONLY if not yet given this call. 3. Call escalate_to_human. NEVER call escalate_to_human before capture_lead if capture_lead is enabled.escalate_to_human — call when the visitor explicitly requests a human.
cancel_escalation — ONLY when visitor explicitly says one of: "never mind", "go back to the AI", "stay with you", "cancel", "I changed my mind" — BEFORE escalation completes. CRITICAL: After escalate_to_human is called, do NOT reply to any visitor speech. Wait silently.79 unmodified lines ),
"coaching_prompt": ( """You are Wavvy's AI coaching specialist for Wavvy demo agents. """You are a Voice AI performance analyst for Wavvy.You will receive a list of completed call evaluations for the Wavvy Voice AI.Generate an optimization coaching pack that helps the product team improve the Voice AI's performance.
Be specific — identify recurring patterns: low-scoring rubric areas, common violations, escalation triggers, KB gaps.Output actionable recommendations: prompt tuning, workflow adjustments, KB content gaps. Never be 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"], "strengths": ["what the Voice AI consistently does well — pattern-based, specific"], "improvements": ["specific failure pattern with data — e.g. 'resolution_rate 52% avg — AI closes calls without confirming outcome'"], "action_items": [ {"priority": "high" | "medium" | "low", "action": "specific actionable step", "metric": "what to measure"} {"priority": "high" | "medium" | "low", "action": "specific optimization step for the team", "metric": "what to measure to confirm improvement"} ], "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." "coaching_note": "One paragraph analysis: what patterns emerged, what to prioritize in the next Voice AI iteration."}""" ),
241 unmodified lines ),
"coaching_prompt": ( """You are Fin's AI coaching specialist for fintech customer support agents. """You are a Voice AI performance analyst for Fin, a fintech customer support Voice AI.You will receive a list of completed call evaluations for the Fin Voice AI.Generate an optimization coaching pack that helps the product team improve Fin's performance.
Be specific — identify recurring patterns: low rubric areas, common violations, escalation triggers, unresolved issue types.Output actionable recommendations: system prompt adjustments, workflow node changes, KB gap fills. Never be 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"], "strengths": ["what Fin consistently does well — pattern-based, specific"], "improvements": ["specific failure pattern — e.g. 'resolution_rate 48% avg — Fin escalates fraud cases without attempting search_transactions first'"], "action_items": [ {"priority": "high" | "medium" | "low", "action": "specific actionable step", "metric": "what to measure"} {"priority": "high" | "medium" | "low", "action": "specific optimization step for the team", "metric": "what to measure to confirm improvement"} ], "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." "coaching_note": "One paragraph analysis: what patterns emerged across these calls, what to prioritize in the next Fin iteration."}""" ),
71 unmodified lines fin_cfg.escalation_reasons = SEED_FIN_CONFIG["escalation_reasons"] fin_cfg.support_categories = SEED_FIN_CONFIG["support_categories"] fin_cfg.companion_mid_call_prompt = SEED_FIN_CONFIG["companion_mid_call_prompt"] print("Updated fin_demo config: voice_system_prompt + tool_configs + companion_mid_call_prompt.") else: fin_cfg.coaching_prompt = SEED_FIN_CONFIG["coaching_prompt"] print("Updated fin_demo config: voice_system_prompt + tool_configs + companion_mid_call_prompt + coaching_prompt.")
wavvy_result = await db.execute( select(TenantConfig).where(TenantConfig.tenant_id == "wavvy_demo") ) wavvy_cfg = wavvy_result.scalar_one_or_none() if wavvy_cfg: wavvy_cfg.coaching_prompt = SEED_WAVVY_CONFIG["coaching_prompt"]
if not fin_cfg: db.add(TenantConfig(**SEED_WAVVY_CONFIG)) db.add(TenantConfig(**SEED_FIN_CONFIG)) print("Seeded tenant configs: wavvy_demo (inactive) + fin_demo (active).")58 unmodified lines59606162636462636433 unmodified lines989910010410510610710810911011110110210358 unmodified lines # Identity guard identity_corrected: bool = False # True after first name-confusion correction
# Lead capture — set after capture_lead succeeds lead_id: Optional[str] = None
# Verified customer — set after verify_account succeeds (fintech Fin flow) customer_id: Optional[str] = None
33 unmodified lines # Orchestration — actions already executed this call; prevents companion re-suggesting them completed_actions: set = field(default_factory=set)
# Pending demo slot — set when needs_confirmation=True; consumed by confirm_pending=True call pending_slot: Optional[dict] = None
# Confirmed visitor identity — set after first successful capture_lead # Used by all subsequent tool calls to avoid re-asking / greeting extraction confirmed_name: Optional[str] = None confirmed_email: Optional[str] = None
# Cached customer profile — set after verify_account succeeds. # Contains: name, first_name, email, phone, account_type, account_status, # fraud_hold_active, kyc_status, masked_phone, masked_email, transactions.3 unmodified lines456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767893 unmodified lines"""
TOOL_CATALOG: dict[str, dict] = { # ── Wavvy self-demo tools ───────────────────────────────────────────────── "capture_lead": { "type": "function", "function": { "name": "capture_lead", "description": ( "Save a prospect's contact details (name, email, phone, company) " "to the leads database. Call this when the user wants to schedule a " "demo or talk to the team. Ask for one field at a time." ), "parameters": { "type": "object", "properties": { "name": { "type": "string", "description": "Full name of the prospect", }, "email": { "type": "string", "description": "Email address of the prospect", }, "phone": { "type": "string", "description": "Phone number of the prospect", }, "company": { "type": "string", "description": "Company the prospect works at", }, "intent": { "type": "string", "description": "What they called about (e.g. demo_request, human_agent)", }, }, "required": ["name", "intent"], }, }, }, "schedule_demo": { "type": "function", "function": { "name": "schedule_demo", "description": ( "Book a demo appointment for a prospect. Call after capture_lead " "has run and the prospect has provided a preferred time." ), "parameters": { "type": "object", "properties": { "lead_id": { "type": "string", "description": "Lead UUID from capture_lead (optional — creates lead if missing)", }, "name": { "type": "string", "description": "Prospect's name", }, "email": { "type": "string", "description": "Prospect's email for confirmation", }, "preferred_time": { "type": "string", "description": "Natural language time preference (e.g. 'Tuesday afternoon')", }, }, "required": ["name", "preferred_time"], }, }, }, # ── Fin support tools ───────────────────────────────────────────────────── "verify_account": { "type": "function",1232356789101112131445618 unmodified lines25262739404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295282930793 unmodified lines82482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685717 unmodified lines8758768778788798808818828838848858868878888898908918928938948958968978988999009019021 unmodified line904905906907908909910911154 unmodified lines10661067106812851286128712881289129012911292129312941295129612971298129913001301130213031304130513061069107010711072"""Wavvy self-demo tool implementations.Tools: capture_lead, schedule_demo, cancel_demo, escalate_to_human.Fin fintech tool implementations.All async. Called only via execute_with_recovery() — never directly.
schedule_demo responsibilities: - Delegates slot resolution to scheduling_agent.resolve_slot() - Returns needs_clarification=True when confidence is too low - Returns needs_confirmation=True when an alternative slot is suggested - Books directly when slot is confirmed (force_slot) or free
cancel_demo responsibilities: - Delegates to scheduling_agent.cancel_appointment() - Returns success/failure with slot label for UI feedback"""import asyncioimport json18 unmodified lineslogger = logging.getLogger(__name__)
# ── capture_lead ─────────────────────────────────────────────────────────────
async def capture_lead( name: str, email: str | None, phone: str | None, company: str | None, intent: str, call_id: str,) -> dict: """ Saves lead info to the leads table. Returns {success, lead_id, fast_response_key}. Idempotent: if call_id already has a lead row, upserts it. """ async with _db_module.AsyncSessionLocal() as db: # Check for existing lead on this call existing = await db.execute( text("SELECT id FROM leads WHERE call_id = :call_id"), {"call_id": call_id}, ) row = existing.mappings().first()
if row: # Update existing lead await db.execute( text(""" UPDATE leads SET name = COALESCE(:name, name), email = COALESCE(:email, email), phone = COALESCE(:phone, phone), company = COALESCE(:company, company), intent = :intent WHERE call_id = :call_id """), { "name": name, "email": email, "phone": phone, "company": company, "intent": intent, "call_id": call_id, }, ) lead_id = str(row["id"]) else: # Insert new lead result = await db.execute( text(""" INSERT INTO leads (call_id, name, email, phone, company, intent) VALUES (:call_id, :name, :email, :phone, :company, :intent) RETURNING id """), { "call_id": call_id, "name": name, "email": email, "phone": phone, "company": company, "intent": intent, }, ) lead_id = str(result.scalar())
await db.commit()
# Update session lead_id session = get_session(call_id) if session: session.lead_id = lead_id
logger.info(json.dumps({ "call_id": call_id, "tool": "capture_lead", "lead_id": lead_id, "name": name, "intent": intent, }))
return { "success": True, "lead_id": lead_id, "fast_response_key": "lead_captured", "template_vars": {"name": name}, }
# ── schedule_demo ─────────────────────────────────────────────────────────────
async def schedule_demo( lead_id: str | None, name: str, email: str | None, preferred_time: str, call_id: str, force_slot: dict | None = None, # pre-confirmed slot from pending confirmation user_timezone: str = "Asia/Kolkata", **_extra,) -> dict: """ Resolve a preferred time and book a demo appointment.
Possible outcomes: needs_clarification=True → parse confidence too low; return clarification prompt needs_confirmation=True → alternative slot found; wait for user confirm success=True → booked; return confirmation details """ from agents.scheduling_agent import ( resolve_slot, send_confirmation_email, _slot_key, ) from datetime import datetime as _dt
if force_slot: # User already confirmed a suggested alternative — book directly confirmed_time = _dt.fromisoformat(force_slot["confirmed_time_iso"]) lbl = force_slot["slot_label"] lbl_short = force_slot["slot_label_short"] else: slot_info = await resolve_slot(preferred_time, user_timezone)
# Low confidence → ask for clarification; do NOT book if slot_info.get("needs_clarification"): return { "success": True, "needs_clarification": True, "clarification_key": slot_info["clarification_key"], "clarification_vars": slot_info["clarification_vars"], "parse_confidence": slot_info.get("parse_confidence", 0.0), }
if slot_info.get("alt_reason") == "no_slots": return { "success": False, "fast_response_key": "no_slots_available", }
confirmed_time = slot_info["confirmed_time"] lbl = slot_info["slot_label"] lbl_short = slot_info["slot_label_short"] is_alt = slot_info.get("is_alternative", False) alt_reason = slot_info.get("alt_reason")
if is_alt: # Suggest alternative; do NOT book until user confirms 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": confirmed_time.isoformat(), "slot_label": lbl, "slot_label_short": lbl_short, "alt_reason": alt_reason, }, "fast_response_key": suggest_key, "template_vars": {"slot_label": lbl_short}, }
# ── Book the appointment ────────────────────────────────────────────────── sk = _slot_key(confirmed_time)
async with _db_module.AsyncSessionLocal() as db: if not lead_id: result = await db.execute( text(""" INSERT INTO leads (call_id, name, email, intent, status) VALUES (:call_id, :name, :email, 'demo_request', 'demo_scheduled') RETURNING id """), {"call_id": call_id, "name": name, "email": email}, ) lead_id = str(result.scalar()) else: await db.execute( text("UPDATE leads SET status = 'demo_scheduled' WHERE id = :id"), {"id": lead_id}, )
try: result = await db.execute( text(""" INSERT INTO demo_appointments (lead_id, call_id, requested_time, confirmed_time, slot_label, slot_key, user_timezone, status) VALUES (:lead_id, :call_id, :req, :confirmed, :lbl, :slot_key, :tz, 'confirmed') RETURNING id """), { "lead_id": lead_id, "call_id": call_id, "req": preferred_time, "confirmed": confirmed_time, "lbl": lbl, "slot_key": sk, "tz": user_timezone, }, ) appointment_id = str(result.scalar()) await db.commit() except Exception as exc: # Unique constraint violation (concurrent booking race) — surface cleanly if "uniq_confirmed_slot" in str(exc) or "unique" in str(exc).lower(): logger.warning(json.dumps({ "call_id": call_id, "tool": "schedule_demo", "event": "slot_race_condition", "slot_key": sk, })) return { "success": False, "fast_response_key": "slot_just_taken", } raise
if email: asyncio.create_task(send_confirmation_email(name, email, lbl, call_id))
logger.info(json.dumps({ "call_id": call_id, "tool": "schedule_demo", "lead_id": lead_id, "appointment_id": appointment_id, "requested_time": preferred_time, "confirmed_time": str(confirmed_time), "slot_key": sk, "force_slot": bool(force_slot), }))
return { "success": True, "appointment_id": appointment_id, "fast_response_key": "demo_scheduled", "template_vars": { "name": name, "email": email or "your email", "slot_label": lbl_short, }, }
# ── cancel_demo ───────────────────────────────────────────────────────────────
async def cancel_demo(call_id: str, **_extra) -> dict: """ Cancel the caller's most recent confirmed demo appointment. Delegates to scheduling_agent.cancel_appointment for DB + email. """ from agents.scheduling_agent import cancel_appointment result = await cancel_appointment(call_id)
if not result.get("success"): reason = result.get("reason", "unknown") fast_key = "no_appointment_found" if reason == "no_active_appointment" else "tool_error" return {"success": False, "fast_response_key": fast_key}
logger.info(json.dumps({ "call_id": call_id, "tool": "cancel_demo", "appointment_id": result.get("appointment_id"), "slot_label": result.get("slot_label"), }))
return { "success": True, "appointment_id": result.get("appointment_id"), "fast_response_key": "demo_cancelled", "template_vars": { "name": result.get("name") or "", "slot_label": result.get("slot_label") or "your demo", }, }
# ── escalate_to_human ─────────────────────────────────────────────────────────
async def escalate_to_human(793 unmodified lines if status == FRAUD_REVERSED: return {"success": False, "fast_response_key": "fraud_transaction_reversed"}
# Check for an existing active fraud case on this transaction regardless of # transaction status — prevents duplicate cases when status was previously # changed to refund_initiated, completed, etc. async with _db_module.AsyncSessionLocal() as db: existing_case = await db.execute( text(""" SELECT fraud_number FROM fraud_cases WHERE transaction_id = :tid AND status NOT IN ('resolved', 'closed', 'rejected') LIMIT 1 """), {"tid": txn_row["id"]}, ) existing = existing_case.mappings().first() if existing: existing_num = existing["fraud_number"] logger.info("report_fraud: case %s already exists for %s — returning existing", existing_num, txn_upper) return { "success": True, "fraud_number": existing_num, "fast_response_key": "fraud_already_reported", "message": ( f"A fraud case {existing_num} is already open for this transaction " f"and is currently under review. No new case has been created." ), }
async with _db_module.AsyncSessionLocal() as db: fraud_number = await next_fraud_number(db)
17 unmodified lines "call_id": call_id, }, ) # Place a fraud hold on the account so the Agent Console can later lift it await db.execute( text(""" UPDATE customers SET fraud_hold_active = true, fraud_hold_placed_at = now() WHERE id = :cid """), {"cid": _uuid.UUID(session.customer_id)}, ) await db.execute( text(""" INSERT INTO account_holds (customer_id, hold_type, reason, status, placed_at, placed_by, call_id) VALUES (:cid, 'fraud', :reason, 'active', now(), 'voice_ai', :call_id) """), { "cid": _uuid.UUID(session.customer_id), "reason": f"Fraud reported via voice AI — {fraud_number}", "call_id": call_id, }, ) await db.commit()
# Update session cache1 unmodified line for t in (cached.get("transactions") or []): if t.get("txn_number", "").upper() == txn_upper: t["status"] = FRAUD_REPORTED if cached: cached["fraud_hold_active"] = True
logger.info(json.dumps({ "call_id": call_id, "tool": "report_fraud",154 unmodified lines
async def execute_tool(tool_name: str, args: dict, call_id: str) -> dict: """Routes tool_name to the correct implementation.""" if tool_name == "capture_lead": return await capture_lead( name=args.get("name", ""), email=args.get("email"), phone=args.get("phone"), company=args.get("company"), intent=args.get("intent", "unknown"), call_id=call_id, ) elif tool_name == "schedule_demo": return await schedule_demo( lead_id=args.get("lead_id"), name=args.get("name", ""), email=args.get("email"), preferred_time=args.get("preferred_time", "TBD"), call_id=call_id, force_slot=args.get("force_slot"), user_timezone=args.get("user_timezone", "Asia/Kolkata"), ) elif tool_name == "cancel_demo": return await cancel_demo(call_id=call_id) elif tool_name == "verify_account": if tool_name == "verify_account": return await verify_account( phone=args.get("phone", ""), call_id=call_id,324 unmodified lines32532632732832933033133233317 unmodified lines35135235335135435535635710 unmodified lines368369370368371372373374166 unmodified lines541542543541544545546547324 unmodified lines # starts speculatively and TTS begins streaming before the assistant # guard can fire. Escalated = Fin is deaf and mute. agent_session.interrupt() elif getattr(session, '_esc_task_pending', False): # Escalation deferred task is in-flight — same guard as above agent_session.interrupt()
# ── Event: conversation item added (user or agent turn) ────────────── @agent_session.on("conversation_item_added")17 unmodified lines session.turn_state = TurnState.ASSISTANT_SPEAKING # Restart silence timer — fires if user goes quiet after agent speaks silence_timer.start() # (e.g. "<function=schedule_demo>...</function>") before displaying # Strip any raw function-call fragments before displaying clean_text = re.sub(r'<function[^>]*>.*?(?:</function>|<function>)', '', text, flags=re.DOTALL).strip() asyncio.create_task(publish_event({ "type": "agent_done",10 unmodified lines # on_user_transcribed already called interrupt() but on_item_added fires in # the same async cycle — calling it again ensures preemptive generation is # fully cancelled before any new LLM call can be enqueued. if session.escalated or session.human_joined: if session.escalated or session.human_joined or getattr(session, '_esc_task_pending', False): agent_session.interrupt() return session.turn_state = TurnState.USER_SPEAKING166 unmodified lines is_esc_room = room_name.startswith("esc-") if not is_esc_room: from routers.livekit_router import _persist_call_end await _persist_call_end(call_id, session.conversation_history) await _persist_call_end(call_id, session.conversation_history, session) remove_session(call_id)
# Notify FastAPI to broadcast call_ended + trigger QA scoring (main room only)53 unmodified lines5455565758596061626364656667686970717273747576777879808157585985 unmodified lines14514614717317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928014814915023 unmodified lines174175176310177178179512 unmodified lines69269369482983083183283383469569669738 unmodified lines73673773887973974074174253 unmodified lines return v.lower().strip()
def _name_is_confirmed(name: str, history: list) -> bool: name_l = name.lower().strip() if not name_l or len(name_l) < 2: return False for i, msg in enumerate(history): if msg.get("role") != "user": continue if name_l not in msg.get("content", "").lower(): continue for j in range(i - 1, -1, -1): prev = history[j] if prev.get("role") == "assistant": if "name" in prev.get("content", "").lower(): return True break return False
def _ai_asked_for_name(history: list) -> bool: return any( "name" in m.get("content", "").lower() for m in history if m.get("role") == "assistant" )
_PHONE_WORD_MAP = { 'zero': '0', 'oh': '0',85 unmodified lines from workflow.engine import WorkflowRunner runner = WorkflowRunner(session)
# ── capture_lead ───────────────────────────────────────────────────────── if "capture_lead" in enabled: @function_tool async def capture_lead( name: str, email: str, company: str | None = None, intent: str = "general_inquiry", ) -> str: """Save visitor name and email.""" if session.confirmed_name: name = session.confirmed_name if session.confirmed_email: email = session.confirmed_email
if _is_placeholder(name): return "I need the visitor's real name. Please ask them: 'What's your name?'"
if not session.confirmed_name and not _name_is_confirmed(name, session.conversation_history): return "Please ask the visitor their name first: 'What's your name?'"
email = _normalize_email(email) if _is_placeholder(email) or not _is_valid_email(email): return "I need a real email address with @. Please ask the visitor for their email."
result = await execute_with_recovery( tool_name="capture_lead", args={"name": name, "email": email, "company": company or "", "intent": intent, "call_id": call_id}, call_id=call_id, turn_id=session.turn_count, step_id="capture_lead", session=session, ) if result.success and result.data.get("lead_id"): session.lead_id = result.data["lead_id"] session.confirmed_name = name session.confirmed_email = email
asyncio.create_task(publish_event({ "type": "tool_call", "tool": "capture_lead", "status": "done", "result": {"success": result.success}, })) return "Contact info saved." if result.success else "Unable to save info right now."
tools.append(capture_lead)
# ── schedule_demo ───────────────────────────────────────────────────────── if "schedule_demo" in enabled: @function_tool async def schedule_demo( name: str, email: str, preferred_time: str, confirm_pending: bool = False, ) -> str: """Book a Wavvy demo. preferred_time: specific day + hour e.g. 'Thursday 2pm'. Set confirm_pending=True only when visitor says yes to a suggested alternative slot.""" effective_name = session.confirmed_name or name effective_email = session.confirmed_email or email
if _is_placeholder(effective_name): return "I need the visitor's real name before booking. Ask them: 'What's your name?'"
if not session.confirmed_name and not _name_is_confirmed(effective_name, session.conversation_history): return "Please ask the visitor their name first: 'What's your name?'"
effective_email = _normalize_email(effective_email) if _is_placeholder(effective_email) or not _is_valid_email(effective_email): return "I need a real email address before booking. Ask the visitor: 'What's your email address?'"
if not confirm_pending and _is_placeholder(preferred_time): return "I need a specific time before booking. Ask: 'We're available Monday to Friday, 9am to 5pm IST. What day and time works for you?'"
args = { "name": effective_name, "email": effective_email, "preferred_time": preferred_time, "lead_id": session.lead_id, "call_id": call_id, "user_timezone": "Asia/Kolkata", } if confirm_pending and session.pending_slot: args["force_slot"] = session.pending_slot session.pending_slot = None else: session.pending_slot = None
result = await execute_with_recovery( tool_name="schedule_demo", args=args, call_id=call_id, turn_id=session.turn_count, step_id="schedule_demo", session=session, ) asyncio.create_task(publish_event({ "type": "tool_call", "tool": "schedule_demo", "status": "done", "result": result.data, }))
if result.data.get("needs_clarification"): return "That time isn't specific enough. Ask: 'We're available Monday to Friday, 9am to 5pm IST. What day and time works for you?'" if result.data.get("needs_confirmation"): session.pending_slot = result.data.get("pending_slot") tv = result.template_vars or {} slot_short = tv.get("slot_label") or preferred_time return f"That slot is taken. The next available time is {slot_short}. Does that work for you?" if result.success: tv = result.template_vars or {} slot = tv.get("slot_label") or preferred_time return f"Demo booked for {slot}. Confirmation sent to {effective_email}." return "Unable to schedule that slot. Would you like to try a different time?"
tools.append(schedule_demo)
# ── verify_account ──────────────────────────────────────────────────────── if "verify_account" in enabled: @function_tool23 unmodified lines if result.get("success"): name = result.get("first_name", "there") acct = result.get("account_type", "standard") session.confirmed_name = name # Build digit-by-digit speech for number readback (e.g. "9 8 1 2 3 4 5 6 0 1") digit_speech = " ".join(digits_only) if digits_only else "" profile = getattr(session, "customer_profile", {}) or {}512 unmodified lines if session.escalated: return "Already transferring to a human agent."
# For Fin (verify_account flow): no name required before escalation. # For Wavvy (capture_lead flow): require name first. if "capture_lead" in enabled: if not session.confirmed_name and not _ai_asked_for_name(session.conversation_history): return "Please ask the visitor their name first before transferring: 'What's your name?'"
async def _check_availability() -> dict: try: async with httpx.AsyncClient(timeout=3.0) as _c:38 unmodified lines
result = await execute_with_recovery( tool_name="escalate_to_human", args={"reason": reason, "transcript_summary": summary, "call_id": call_id}, args={"reason": reason, "lead_summary": summary, "call_id": call_id}, call_id=call_id, turn_id=session.turn_count, step_id="escalate",48 unmodified lines49505152535455565758596061626364656622 unmodified lines89909192939495969712 unmodified lines1101111129899113114115116117118119120121122112 unmodified lines23523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626724 unmodified lines29229329429529629729829930030130230330430530630730848 unmodified lines ], 0.95), (IssueType.KYC_HOLD, ["kyc", "verification hold"], 0.80),
# ── Fraud Hold Removal — MUST come before generic FRAUD patterns (higher priority) ── # Customer already has a fraud hold and wants it lifted — route to Account Unlock (IssueType.ACCOUNT_LOCKED, [ "fraud hold", "fraud investigation hold", "fraud hold on my account", "account is hold for fraud", "account is on hold for fraud", "my account is hold for a fraud", "account held for fraud", "held for fraud investigation", "account under fraud hold", "remove fraud hold", "lift fraud hold", "clear fraud hold", "held due to fraud", "held because of fraud", "fraud is on hold", "account has a fraud hold", ], 0.95),
# ── Fraud ───────────────────────────────────────────────────────────────── (IssueType.FRAUD, [ "unauthorized transaction", "someone used my account", "i didn't make",22 unmodified lines "amount was deducted", "amount got deducted", "money got deducted", "deducted from my account", "deducted but", "got debited", "debited but not", "debited and failed", # Colloquial: "money got deducted and it got failed" "deducted and got failed", "deducted and it failed", "got failed and money", "failed and money deducted", ], 0.95), (IssueType.REFUND, ["refund", "reimburs"], 0.75),
12 unmodified lines "where is my money", "money not received", "payment stuck", "transfer stuck", "transaction stuck", ], 0.90), (IssueType.TRANSACTION_STATUS, ["transaction failed", "payment failed", "transfer failed"], 0.80), (IssueType.TRANSACTION_STATUS, ["transaction", "payment"], 0.55), (IssueType.TRANSACTION_STATUS, [ "transaction failed", "payment failed", "transfer failed", # Colloquial Indian English: "it got failed", "transaction got failed" "got failed", "it failed", "transaction got failed", "payment got failed", "transfer got failed", ], 0.80), (IssueType.TRANSACTION_STATUS, ["transaction", "payment"], 0.65),
# ── General (lowest priority catch-all) ─────────────────────────────────── (IssueType.GENERAL_SUPPORT, [112 unmodified lines for phrase in _UNIVERSAL_CLOSURE_PHRASES]
# Negation words — used to suppress single-word keyword matches that appear in# a negated context ("no fraud", "I don't see any fraud", "there is no fraud").# Only applied to single-word keywords (no spaces) — multi-word intent phrases# like "I didn't make this transaction" are inherently intentional and unambiguous._NEGATION_WORDS: frozenset[str] = frozenset([ "no", "not", "never", "none", "without", "don't", "dont", "doesn't", "doesnt", "didn't", "didnt", "isn't", "isnt", "wasn't", "wasnt", "weren't", "werent", "haven't", "havent", "hasn't", "hasnt", "hadn't", "hadnt", "won't", "wont", "wouldn't", "wouldnt", "can't", "cant", "couldn't", "couldnt",])
_STRIP_PUNCT = re.compile(r"[^\w']+")
def _is_single_keyword_negated(lower: str, keyword: str) -> bool: """Return True if `keyword` (no spaces) appears within 8 words of a negation.""" if ' ' in keyword: return False # phrase keywords are intentional — skip negation check kw_re = re.compile(r'\b' + re.escape(keyword) + r'\b') for m in kw_re.finditer(lower): prefix = lower[max(0, m.start() - 60):m.start()] preceding = [_STRIP_PUNCT.sub('', w) for w in prefix.split()[-8:]] if any(w in _NEGATION_WORDS for w in preceding): return True return False
def _is_completion_context(lower: str, issue_type: IssueType) -> bool: """Return True if the utterance describes a resolved outcome, not a new request."""24 unmodified lines matched = [kw for kw, pattern in kw_patterns if pattern.search(lower)] if not matched: continue # Remove single-word keywords that appear in a negated context. # "I don't see any fraud" / "there is no fraud" → suppress "fraud" match. # Multi-word phrases (e.g. "i didn't make this") are kept — they encode intent. active = [kw for kw in matched if not _is_single_keyword_negated(lower, kw)] if not active: logger.debug( "issue_classifier: suppressed %s — all keywords negated in: %r", issue_type.value, text[:80], ) continue matched = active if best is None or confidence > best[1]: best = (issue_type, confidence, matched)
37 unmodified lines38394041424344454142434437 unmodified lines# escalate_to_human is intentionally absent — the LLM must never self-initiate# escalation. It is only offered once the customer has explicitly requested it# AND confirmed (mode = ESCALATION, handled separately in _process).GENERAL_MODE_TOOLS: frozenset[str] = frozenset([ "capture_lead", "schedule_demo", "cancel_demo",])GENERAL_MODE_TOOLS: frozenset[str] = frozenset()
# Escalation keywords — first occurrence triggers a confirmation ask; second confirms.# Includes role names (specialist, manager, supervisor) and "connect to/with" phrasing.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798"""Lightweight demo reminder service.
Sends T-24h and T-1h email reminders for confirmed demo appointments.Runs as a periodic background asyncio task — no external queue needed.
Usage (called from main.py lifespan): asyncio.create_task(start_reminder_loop())"""import asyncioimport loggingfrom datetime import datetime, timedelta, timezone
from sqlalchemy import text
from database import AsyncSessionLocal
logger = logging.getLogger(__name__)
UTC = timezone.utc
# How often to poll for upcoming appointments (seconds)REMINDER_CHECK_INTERVAL = 600 # every 10 minutes
# Windows: send reminder if appointment is within [now+X-buffer, now+X+buffer]_WINDOWS = [ (timedelta(hours=24), timedelta(minutes=10), 24), (timedelta(hours=1), timedelta(minutes=5), 1),]
async def _check_and_send() -> None: """Find appointments due for a reminder and send emails.
Only runs when the active tenant config has schedule_demo enabled. Silently skips for Fin (fintech) tenants where demo_appointments was dropped. """ try: from config_loader import get_config cfg = get_config() if not cfg.tool_configs.get("schedule_demo", {}).get("enabled", False): return except Exception: return # config not loaded yet — skip silently
now = datetime.now(UTC)
for target_offset, tolerance, hours_label in _WINDOWS: window_start = now + target_offset - tolerance window_end = now + target_offset + tolerance
try: async with AsyncSessionLocal() as db: rows = await db.execute( text(""" SELECT da.id, da.confirmed_time, da.slot_label, da.call_id, l.name, l.email FROM demo_appointments da JOIN leads l ON l.id = da.lead_id WHERE da.status = 'confirmed' AND da.confirmed_time >= :ws AND da.confirmed_time < :we AND l.email IS NOT NULL """), {"ws": window_start, "we": window_end}, ) appointments = rows.mappings().all() except Exception as exc: logger.warning(f"Reminder check DB error: {exc}") continue
for appt in appointments: try: from agents.scheduling_agent import send_reminder_email await send_reminder_email( name = appt["name"] or "there", to_email = appt["email"], slot_lbl = appt["slot_label"] or str(appt["confirmed_time"]), call_id = str(appt["call_id"] or ""), hours_until = hours_label, ) logger.info( f"Reminder sent: appt={appt['id']} hours={hours_label} " f"to={appt['email']}" ) except Exception as exc: logger.warning(f"Reminder email failed for appt {appt['id']}: {exc}")
async def start_reminder_loop() -> None: """Runs forever, checking for reminders every REMINDER_CHECK_INTERVAL seconds.""" logger.info("Reminder service started") while True: try: await _check_and_send() except Exception as exc: logger.error(f"Reminder loop error: {exc}") await asyncio.sleep(REMINDER_CHECK_INTERVAL)43 unmodified lines4445464748494748491 unmodified line515253575859545556134 unmodified lines19119219320019419519619743 unmodified lines# ── Per-tool retry policies ───────────────────────────────────────────────────
RETRY_POLICY: dict[str, int] = { "capture_lead": 2, # idempotent write — safe to retry "schedule_demo": 1, # write — single retry (slot_key UNIQUE prevents double-book) "cancel_demo": 1, # idempotent — cancelling an already-cancelled appt is safe "escalate_to_human": 1, # idempotent — single retry "default": 1,}1 unmodified line# ── Per-tool timeout budgets (seconds) ────────────────────────────────────────
TOOL_TIMEOUTS: dict[str, float] = { "capture_lead": 2.0, "schedule_demo": 6.0, # dateparser + DB conflict check + optional email "cancel_demo": 3.0, "escalate_to_human": 3.0, "default": 2.0,}134 unmodified lines return ToolResult( success=False, fast_response_key="tool_error", should_escalate=(tool_name in ("schedule_demo",)), should_escalate=False, error_type=last_error, turn_id=turn_id, )114 unmodified lines11511611711811911811912012112228 unmodified lines15115215315415415515615715715815916040 unmodified lines2012022032042052042052062072082092102112122138 unmodified lines222223224225226227228229230231232233234235236237238239229240241242243244245234246247248249250251252253254255256257258259260261262263264265266267268269270271272114 unmodified lines turn_ctx: ChatContext, new_message: ChatMessage, ) -> None: # Escalated or human taken over — do not prefetch KB or trigger LLM if self._session.escalated or self._session.human_joined: # Escalated (or escalation in flight) or human taken over — skip KB prefetch + LLM if self._session.escalated or self._session.human_joined or getattr(self._session, '_esc_task_pending', False): return text = new_message.text_content or "" if text.strip():28 unmodified lines ): session = self._session
# Escalated or human taken over — do not invoke the LLM at all. # Escalated (or escalation in flight) or human taken over — do not invoke LLM. # Returning from an async generator produces an empty stream, which the # SDK handles gracefully (no TTS, no response). if session.escalated or session.human_joined: if session.escalated or session.human_joined or getattr(session, '_esc_task_pending', False): return
# Wait for in-flight KB prefetch (max 1.5s) before building context.40 unmodified lines # → session.escalated=True only after TTS has started if decision is not None: from session.orchestrator_state import ExecutionMode as _EM if decision.mode == _EM.ESCALATION and not session.escalated: caller_name = getattr(session.orchestrator_state, "escalation_caller_name", "") or "" if decision.mode == _EM.ESCALATION and not session.escalated and not getattr(session, '_esc_task_pending', False): # Fall back to verified customer name when name-collection flow was skipped caller_name = ( getattr(session.orchestrator_state, "escalation_caller_name", "") or (getattr(session, "customer_profile", None) or {}).get("first_name") or "" ) call_reason = getattr(session.orchestrator_state, "escalation_call_reason", "") or "" _REASON_PHRASE = { "Payment Issue": "payment specialist",8 unmodified lines tts = f"Connecting you with a {specialist} right now. Please hold on." yield tts # TTS queued BEFORE escalated=True is set
# Guard against re-entry during the deferred 3.5s window. # Set AFTER yield so on_item_added fires with _esc_task_pending=False → audio OK. # Checked in on_user_turn_completed and llm_node to stop the second trigger. session._esc_task_pending = True
esc_tool = next((t for t in tools if _tool_name(t) == "escalate_to_human"), None) if esc_tool is not None: _cname = caller_name _call_reason = call_reason or "General Inquiry" _call_id = session.call_id _publish_evt = self._publish_event # captured for recovery notification
async def _fire_escalation_deferred(): # Sleep gives the SDK time to start AND finish TTS before # session.escalated=True triggers on_item_added → interrupt(). # 3.5s covers the ~2-3s Deepgram Aura TTS playback for a 15-word phrase. # 3.5s covers the ~2-3s Cartesia TTS playback for a 15-word phrase. await asyncio.sleep(3.5) try: _reason = _call_reason + (f" — caller: {_cname}" if _cname else "") await esc_tool(reason=_reason) if session.escalated: logger.info("[%s] escalation tool fired (caller=%s)", _call_id, _cname or "unknown") logger.info("[%s] escalation tool fired (caller=%s)", _call_id, _cname or "unknown") else: # Tool ran but escalation didn't complete — most likely cause: # no agent consoles are connected so availability check returned False. # Notify the frontend to cancel the transfer screen so the customer # isn't stuck staring at "Connecting to specialist…" indefinitely. logger.warning( "[%s] escalation tool returned but session.escalated=False " "(caller=%s) — no agents available; cancelling transfer screen", _call_id, _cname or "unknown", ) asyncio.create_task(_publish_evt({ "type": "escalation_cancelled", "reason": "no_specialists_available", })) session._esc_task_pending = False # allow retry on next user turn except Exception as exc: logger.warning("[%s] deferred escalation failed: %s", _call_id, exc) session._esc_task_pending = False # allow retry
asyncio.create_task(_fire_escalation_deferred()) else: logger.warning("[%s] escalate_to_human not found in tools list", session.call_id) session._esc_task_pending = False return
# ── 1. Tool scoping ───────────────────────────────────────────────────123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264"""Workflow Engine — single source of truth for session progression.
Rules:- ALL WorkflowSession mutations happen inside async with session.workflow_lock- Intent Router is used ONLY for initialization (first turn, no active workflow)- Once a workflow is active, only the Workflow Engine advances steps- TranscriptProcessor must contain NO hidden branching — add a WorkflowNode instead"""from __future__ import annotationsfrom dataclasses import dataclass, fieldfrom datetime import datetime, timezonefrom enum import Enumfrom typing import Literal
from voice.intent_router import Intentfrom voice.deterministic_responses import WAVVY_DEMO
class WorkflowStepId(Enum): START = "start" CAPTURE_LEAD = "capture_lead" SCHEDULE_DEMO = "schedule_demo" ESCALATE = "escalate" RESOLVED = "resolved"
@dataclassclass WorkflowNode: id: WorkflowStepId kind: Literal["tool", "state"] # "tool" → execute tool; "state" → speak + wait name: str # tool name OR state label on_success: WorkflowStepId | None = None on_failure: WorkflowStepId | None = None on_timeout: WorkflowStepId | None = None fast_response_key: str | None = None # for kind="state": key to speak required_entities: list[str] = field(default_factory=list)
@dataclassclass PendingAction: tool: str args: dict expires_at: datetime idempotency_key: str created_turn_id: int # discard confirmation from turns before this
@dataclassclass WorkflowSummary: """ Structured state — converted to minimal text only at LLM context build time. LLM never sees raw session state; it sees only to_text(). """ lead_captured: bool = False demo_scheduled: bool = False escalated: bool = False last_action: str | None = None # most recent completed action sentiment_status: str | None = None # "positive" | "neutral" | "negative" recent_failure: str | None = None # last tool failure key escalation_reason: str | None = None topics_discussed: list[str] = field(default_factory=list) last_slot_label: str | None = None # short label of last booked/suggested slot
def to_text(self) -> str: """Minimal structured context for LLM. Fields included only when non-default.""" parts = [] if self.lead_captured: parts.append("lead_captured") if self.demo_scheduled: parts.append("demo_scheduled") if self.escalated: parts.append("escalated") if self.last_action: parts.append(self.last_action) if self.recent_failure: parts.append(f"last_error={self.recent_failure}") if self.escalation_reason: parts.append(f"escalation={self.escalation_reason}") if self.topics_discussed: parts.append(f"topics={','.join(self.topics_discussed)}") return "; ".join(parts) if parts else "initial"
def add_topic(self, topic: str) -> None: if topic not in self.topics_discussed: self.topics_discussed.append(topic)
@dataclassclass WorkflowSession: intent: Intent = Intent.UNKNOWN entities: dict = field(default_factory=dict) current_step: WorkflowStepId = WorkflowStepId.START completed_steps: list[WorkflowStepId] = field(default_factory=list) pending_action: PendingAction | None = None # ONE active at a time summary: WorkflowSummary = field(default_factory=WorkflowSummary) call_mode: str = WAVVY_DEMO _consecutive_unknown_intents: int = 0 _entity_ask_count: dict = field(default_factory=dict) # entity → # times asked
# Slot confirmation state pending_slot: dict | None = None # slot awaiting user confirmation pending_slot_expires_at: datetime | None = None # UTC; None = no expiry set yet
# Clarification tracking — escalate after MAX_CLARIFICATION_ATTEMPTS clarification_attempts: int = 0
# Cancellation confirmation state pending_cancel: bool = False
# Rescheduling mode — True while waiting for a new preferred_time after reschedule request is_rescheduling: bool = False
# User's inferred timezone (ISO name, e.g. "Asia/Kolkata", "America/New_York") user_timezone: str = "Asia/Kolkata"
# Clarification-before-escalation tracking for UNKNOWN intents # Reset to 0 on any non-UNKNOWN intent so counters don't bleed across topics. _unknown_clarification_count: int = 0 # how many clarification turns sent this streak _last_unknown_ts: float = 0.0 # monotonic time of the last UNKNOWN turn
# ── Workflow definitions ──────────────────────────────────────────────────────
S = WorkflowStepId # alias for brevity
WORKFLOWS: dict[Intent, list[WorkflowNode]] = {
# Pure KB + LLM — no tool execution needed Intent.PRODUCT_QA: [], Intent.COMPETITOR_COMPARE: [], Intent.INTEGRATION_QA: [], Intent.GENERAL_QA: [],
# Pricing: FAST_RESPONSE handles standard tiers immediately. # enterprise keyword detected → Workflow Engine transitions to ESCALATE. Intent.PRICING_INQUIRY: [], # handled via FAST_RESPONSES in pipeline
Intent.DEMO_REQUEST: [ # Step 1: capture name + email (ask one at a time until both present) WorkflowNode( id=S.CAPTURE_LEAD, kind="tool", name="capture_lead", required_entities=["name", "email"], on_success=S.SCHEDULE_DEMO, on_failure=S.ESCALATE, ), # Step 2: collect preferred_day then preferred_time before scheduling. # Two-question flow: ask for day first, then time on that day. # Only calls schedule_demo tool once BOTH entities are present. WorkflowNode( id=S.SCHEDULE_DEMO, kind="state", name="ask_demo_day", fast_response_key="ask_demo_day", required_entities=["preferred_day", "preferred_time"], on_success=S.RESOLVED, on_failure=S.ESCALATE, on_timeout=S.RESOLVED, ), ],
Intent.HUMAN_AGENT: [ # Capture at least a name before escalating (for agent context) WorkflowNode( id=S.CAPTURE_LEAD, kind="tool", name="capture_lead", required_entities=["name"], on_success=S.ESCALATE, on_failure=S.ESCALATE, ), WorkflowNode( id=S.ESCALATE, kind="tool", name="escalate_to_human", on_success=S.RESOLVED, on_failure=S.RESOLVED, ), ],
# After 3 consecutive UNKNOWNs (or 2 + negative sentiment), escalate Intent.UNKNOWN: [ WorkflowNode( id=S.ESCALATE, kind="tool", name="escalate_to_human", on_success=S.RESOLVED, on_failure=S.RESOLVED, ), ],}
def get_workflow(intent: Intent) -> list[WorkflowNode]: """Returns the workflow node list for the given intent.""" return WORKFLOWS.get(intent, [])
def get_current_node(workflow: WorkflowSession) -> WorkflowNode | None: """Returns the active WorkflowNode for the given step, or None if no tool steps.""" nodes = get_workflow(workflow.intent) for node in nodes: if node.id == workflow.current_step: return node return None
def missing_entities(node: WorkflowNode, entities: dict) -> list[str]: """Returns list of required entity keys not yet present in entities.""" return [e for e in node.required_entities if not entities.get(e)]
def advance_step(workflow: WorkflowSession, outcome: Literal["success", "failure", "timeout"]) -> WorkflowStepId: """ Transitions current_step based on outcome. Returns the new step id. Caller must hold session.workflow_lock. """ node = get_current_node(workflow) if not node: return WorkflowStepId.RESOLVED
if workflow.current_step not in workflow.completed_steps: workflow.completed_steps.append(workflow.current_step)
if outcome == "success": next_step = node.on_success or WorkflowStepId.RESOLVED elif outcome == "timeout": next_step = node.on_timeout or WorkflowStepId.RESOLVED else: next_step = node.on_failure or WorkflowStepId.ESCALATE
workflow.current_step = next_step return next_step
def is_workflow_active(workflow: WorkflowSession) -> bool: """True if a workflow has been initialized and is not yet resolved/escalated.""" return ( workflow.current_step not in (WorkflowStepId.START, WorkflowStepId.RESOLVED) and workflow.intent != Intent.UNKNOWN )
def next_missing_entity_prompt(node: WorkflowNode, entities: dict) -> str | None: """ Returns the FAST_RESPONSE key to prompt for the next missing required entity. Returns None if all required entities are present. """ missing = missing_entities(node, entities) if not missing: return None # Map entity name → prompt key prompts = { "name": "ask_name", "email": "ask_email", "phone": "ask_phone", "company": "ask_company", "preferred_day": "ask_demo_day", "preferred_time": "ask_demo_time", } return prompts.get(missing[0])305 unmodified lines30630730830931031131291 unmodified lines40440540640740840941034 unmodified lines44544644744844945045111 unmodified lines46346446546646746846932 unmodified lines502503504505506507508509510511512513227 unmodified lines741742743734744745746747305 unmodified lines context_additions: list[dict] = [] last_fast_key = "success" _compress_verification = False _directive_template_vars: dict[str, str] = {} # filled by action handlers, applied to directive
# Validate slot formats before firing any auto_action. # Prevents cross-slot contamination (OTP digits used as TXN ID, etc.).91 unmodified lines elif action_name == "initiate_refund": rfn = tool_result.data.get("rfn_number", "") if fast_key == "success" and rfn: _directive_template_vars["rfn_number"] = rfn context_additions.append({ "role": "developer", "content": (34 unmodified lines elif action_name == "raise_dispute": dsp = tool_result.data.get("dsp_number", "") if fast_key == "dispute_filed" and dsp: _directive_template_vars["dsp_number"] = dsp context_additions.append({ "role": "developer", "content": (11 unmodified lines elif action_name == "report_fraud": fraud_num = tool_result.data.get("fraud_number", "") if fast_key == "fraud_case_opened" and fraud_num: _directive_template_vars["fraud_number"] = fraud_num context_additions.append({ "role": "developer", "content": (32 unmodified lines # over the generic _resolve_outcome_directive fallback. state.exit_workflow() directive = node.directive or _resolve_outcome_directive(node, last_fast_key) # Substitute any [placeholder] tokens that were populated by action handlers # (e.g. [dsp_number], [rfn_number], [fraud_number]). Without this the LLM # sees the literal placeholder and invents a value by pattern-matching against # known IDs in its context (e.g. TXN-3300 → DSP-3300). for key, val in _directive_template_vars.items(): directive = directive.replace(f"[{key}]", val) return NodeAdvanceResult( directive=directive, tools_for_llm=[],227 unmodified lines
lines = [ f"MANDATORY NAME RULE: Call this customer '{first_name}' in EVERY response — no exceptions.", "[Customer Verified]", "[Account data — identity already confirmed; do NOT say 'you are verified' or 'verification complete']", f"Name on account: {name} (use first name '{first_name}' in all speech).", f"Account: {acct_type} | status: {acct_status} | KYC: {kyc}", ].env.example+20-6
agents/coaching_agent.py+17-11
agents/scheduling_agent.pyDeleted-690
coaching/coaching_manager.py+97-57
config.py+3-4
guardrails/tool_permissions.py+2-5
main.py+155-12
models/escalation_packet.py+1-1
routers/calls.py+27-6
routers/coaching.py+25-52
routers/livekit_router.py+15-3
routers/orchestration_router.py+30-1
routers/ws_agent.py+7
seed.py+41-24
session/call_session.py-11
tools/registry.py-70
tools/wavvy_tools.py+54-291
voice/agent_session.py+6-3
voice/agent_tools.py+1-141
voice/issue_classifier.py+60-2
voice/orchestrator.py+1-5
voice/reminder_service.pyDeleted-98
voice/tool_recovery.py+1-7
voice/wavvy_agent.py+37-8
voice/workflow_engine.pyDeleted-264
workflow/node_executor.py+11-1