File size: 14,201 Bytes
6793beb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 | """
FastAPI routes for the Customer Support Email Agent.
"""
from __future__ import annotations
import asyncio
import json
import os
import tempfile
import threading
import uuid
from datetime import datetime, timezone
from typing import Optional
from fastapi import APIRouter, HTTPException, Depends, Header
from loguru import logger
from src.core.config import settings
from src.graph.workflow import workflow
from src.schemas.email import IncomingEmail, OutgoingEmail
from src.schemas.state import SupportState, TicketStatus
from src.services.email_service import fetch_new_emails, send_reply
from src.utils.supabase_client import supabase
router = APIRouter(tags=["support"])
async def verify_token(x_api_token: str = Header(...)):
"""Backend security middleware for private deployments."""
if x_api_token != settings.API_TOKEN:
raise HTTPException(status_code=403, detail="Invalid API Token")
def _redact_email(email_addr: str) -> str:
"""Redact an email address for logging (e.g. j***@company.com)."""
if "@" not in email_addr:
return "***"
local, domain = email_addr.split("@", 1)
return f"{local[0]}***@{domain}" if local else f"***@{domain}"
def _generate_ticket_id() -> str:
"""Generate a collision-resistant ticket ID (full UUID hex)."""
return uuid.uuid4().hex
def _redact_email(email_addr: str) -> str:
"""Redact an email address for logging (e.g. j***@company.com)."""
if "@" not in email_addr:
return "***"
local, domain = email_addr.split("@", 1)
return f"{local[0]}***@{domain}" if local else f"***@{domain}"
async def _persist_ticket(email: IncomingEmail, result: dict) -> dict:
"""Persist ticket data to Supabase."""
ticket_id = _generate_ticket_id()
# Map pydantic/dict result to DB schema
ticket_data = {
"ticket_id": ticket_id,
"sender": email.sender,
"subject": email.subject,
"body": email.body,
"message_id": email.message_id,
"received_at": email.received_at.isoformat(),
"category": result.get("category", "unknown"),
"confidence": result.get("confidence", 0.0),
"draft_response": result.get("draft_response", ""),
"final_response": result.get("final_response", ""),
"needs_escalation": result.get("needs_escalation", False),
"escalation_reason": result.get("escalation_reason", ""),
"follow_up_scheduled": result.get("follow_up_scheduled", False),
"status": result.get("status", "processing"),
"context": result.get("context", []),
"metadata": result.get("metadata", {}),
"created_at": datetime.now(timezone.utc).isoformat(),
}
try:
response = supabase.table("tickets").insert(ticket_data).execute()
return ticket_data
except Exception as e:
logger.error("Supabase insertion failed: {}", e)
# Raise HTTP exception so the frontend doesn't redirect to a missing ticket
raise HTTPException(status_code=500, detail=f"Database save failed: {str(e)}")
@router.post("/process-email", dependencies=[Depends(verify_token)])
async def process_email(email: IncomingEmail) -> dict:
"""
Accept an incoming email and run it through the support agent graph.
Returns the agent's response and metadata.
"""
logger.info("Processing email — ticket pipeline initiated")
initial_state = SupportState(email=email)
result = await workflow.ainvoke(initial_state)
ticket_record = await _persist_ticket(email, result)
return ticket_record
@router.get("/emails", dependencies=[Depends(verify_token)])
async def list_all_emails() -> dict:
"""List all processed emails from Supabase."""
try:
response = (
supabase.table("tickets")
.select("*")
.order("created_at", desc=True)
.execute()
)
tickets = response.data
return {"total": len(tickets), "tickets": tickets}
except Exception as e:
logger.error("Supabase fetch failed: {}", e)
return {"total": 0, "tickets": [], "error": str(e)}
@router.get("/emails/recent", dependencies=[Depends(verify_token)])
async def get_recent_emails(limit: int = 10) -> dict:
"""Get the N most recent emails for the recent activity table."""
try:
response = (
supabase.table("tickets")
.select("*")
.order("created_at", desc=True)
.limit(limit)
.execute()
)
tickets = response.data
return {"total": len(tickets), "tickets": tickets}
except Exception as e:
logger.error("Supabase fetch failed: {}", e)
return {"total": 0, "tickets": []}
@router.get("/emails/{ticket_id}", dependencies=[Depends(verify_token)])
async def get_email_details(ticket_id: str) -> dict:
"""Get full details of a specific processed email."""
try:
response = (
supabase.table("tickets")
.select("*")
.eq("ticket_id", ticket_id)
.single()
.execute()
)
if not response.data:
raise HTTPException(
status_code=404, detail=f"Ticket '{ticket_id}' not found"
)
return response.data
except Exception:
raise HTTPException(status_code=404, detail=f"Ticket '{ticket_id}' not found")
@router.get("/kpis", dependencies=[Depends(verify_token)])
async def get_kpis() -> dict:
"""Calculate and return system KPIs using Supabase analytics."""
try:
# Fetch all for simple calculation (HF Spaces CPU is fast enough for low volume)
response = (
supabase.table("tickets").select("needs_escalation, status").execute()
)
tickets = response.data
total_emails = len(tickets)
escalated = sum(1 for t in tickets if t.get("needs_escalation"))
sent_auto = sum(
1
for t in tickets
if not t.get("needs_escalation")
and t.get("status") in ("sent", "processing")
)
auto_draft_success_rate = (
(sent_auto / total_emails * 100) if total_emails > 0 else 0
)
return {
"kpis": {
"total_emails": {
"value": total_emails,
"change": "+12%",
"trend": "up",
},
"avg_resolution_time": {
"value": "1.2m",
"change": "-15%",
"trend": "down",
},
"auto_draft_success": {
"value": f"{auto_draft_success_rate:.1f}%",
"raw_value": auto_draft_success_rate,
"change": "+2.4%",
"trend": "up",
},
"manual_escalations": {
"value": escalated,
"change": "-5%",
"trend": "down",
},
},
"health": {
"classifier_confidence": 92.5,
"retriever_precision": 88.0,
"responder_quality": 95.2,
},
}
except Exception as e:
logger.error("KPI calculation failed: {}", e)
return {
"error": "Failed to load dynamic KPIs",
"kpis": {
"total_emails": {"value": 0, "change": "0%", "trend": "up"},
"avg_resolution_time": {
"value": "0m",
"change": "0%",
"trend": "down",
},
"auto_draft_success": {
"value": "0%",
"raw_value": 0,
"change": "0%",
"trend": "up",
},
"manual_escalations": {
"value": 0,
"change": "0%",
"trend": "down",
},
},
"health": {
"classifier_confidence": 0,
"retriever_precision": 0,
"responder_quality": 0,
},
}
@router.get("/config", dependencies=[Depends(verify_token)])
async def get_system_config() -> dict:
"""Return mock system configurations for the UI."""
return {
"knowledge_base": [
{
"id": "KB-001",
"title": "Billing Policies",
"updated": "2026-04-10",
"type": "Markdown",
},
{
"id": "KB-002",
"title": "API Documentation",
"updated": "2026-04-12",
"type": "Markdown",
},
{
"id": "KB-003",
"title": "Account Management",
"updated": "2026-04-05",
"type": "Markdown",
},
],
"prompts": {
"classifier": "You are a senior support routing agent. Output ONLY JSON...",
"retriever": "Using the following context chunks, extract the relevance...",
"responder": "Draft a professional response to the user based on the context.",
},
"settings": {
"top_k_results": 3,
"confidence_threshold": 0.85,
"model_selection": settings.LLM_MODEL,
},
}
@router.post("/process-email-batch", dependencies=[Depends(verify_token)])
async def process_email_batch() -> dict:
"""
Fetch unread emails from the IMAP mailbox and process each.
"""
logger.info("Starting batch email processing")
emails = await fetch_new_emails()
if not emails:
return {"processed": 0, "message": "No new emails found"}
results = []
for email in emails:
try:
initial_state = SupportState(email=email)
result = await workflow.ainvoke(initial_state)
ticket_record = await _persist_ticket(email, result)
results.append(
{
"ticket_id": ticket_record["ticket_id"],
"status": ticket_record["status"],
"category": ticket_record["category"],
"needs_escalation": ticket_record["needs_escalation"],
}
)
except Exception as e:
logger.error("Failed to process batch email: {}", e)
results.append({"status": "error", "error": str(e)})
return {"processed": len(results), "results": results}
@router.get("/review", dependencies=[Depends(verify_token)])
async def list_escalated_tickets() -> dict:
"""List all tickets pending human review from Supabase."""
try:
response = (
supabase.table("tickets")
.select("*")
.eq("needs_escalation", True)
.eq("status", "pending_review")
.execute()
)
return {"pending_count": len(response.data), "tickets": response.data}
except Exception as e:
logger.error("Escalation fetch failed: {}", e)
return {"pending_count": 0, "tickets": []}
@router.post("/review/{ticket_id}", dependencies=[Depends(verify_token)])
async def review_ticket(
ticket_id: str, action: str, revised_response: Optional[str] = None
) -> dict:
"""
Human review endpoint for escalated tickets.
"""
try:
response = (
supabase.table("tickets")
.select("*")
.eq("ticket_id", ticket_id)
.single()
.execute()
)
ticket = response.data
except Exception:
raise HTTPException(status_code=404, detail=f"Ticket '{ticket_id}' not found")
if not ticket:
raise HTTPException(status_code=404, detail=f"Ticket '{ticket_id}' not found")
if ticket["status"] != "pending_review":
raise HTTPException(status_code=400, detail=f"Already {ticket['status']}")
if action not in ("approve", "reject"):
raise HTTPException(
status_code=400, detail="Action must be 'approve' or 'reject'"
)
# In Supabase, the email body/sender are top-level or in 'metadata' if we changed it.
# Given my _persist_ticket, they are top-level.
if action == "approve":
response_text = revised_response or ticket["draft_response"]
else:
if not revised_response:
supabase.table("tickets").update({"status": "rejected"}).eq(
"ticket_id", ticket_id
).execute()
return {
"ticket_id": ticket_id,
"status": "rejected",
"message": "Ticket rejected",
}
response_text = revised_response
outgoing = OutgoingEmail(
to=ticket["sender"],
subject=f"Re: {ticket['subject']}",
body=response_text,
in_reply_to=ticket.get("message_id"),
)
try:
sent = await send_reply(outgoing)
new_status = "sent" if sent else "approved"
supabase.table("tickets").update(
{
"status": new_status,
"final_response": response_text,
"reviewed_at": datetime.now(timezone.utc).isoformat(),
}
).eq("ticket_id", ticket_id).execute()
return {
"ticket_id": ticket_id,
"status": new_status,
"message": f"Response {'sent' if sent else 'approved'}",
}
except Exception as e:
logger.error("Failed to send reviewed reply: {}", e)
raise HTTPException(status_code=500, detail="Failed to send email")
@router.get("/follow-ups", dependencies=[Depends(verify_token)])
async def list_follow_ups() -> dict:
"""List all scheduled follow-ups from Supabase."""
try:
response = (
supabase.table("tickets")
.select("*")
.eq("follow_up_scheduled", True)
.execute()
)
return {"pending_count": len(response.data), "follow_ups": response.data}
except Exception as e:
logger.error("Follow-up fetch failed: {}", e)
return {"pending_count": 0, "follow_ups": []}
|