Spaces:
Sleeping
Sleeping
fix: webhook handles custom_analytics key + debug endpoint
Browse files123456789101112131415161718192030 unmodified lines515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041053 unmodified lines1091101111121131141151161171181192 unmodified lines1221231241251261271281294 unmodified lines134135136137138139140141"""Bolna post-call webhook β call_logs audit trail.Bolna's payload shape varies by configuration, so parsing is defensive:we pick out whatever transcript/extraction/context fields are present.The nested extracted_data shape is:{Category: {Name: {subjective, objective, confidence, reasoning}}}We flatten the known keys into typed call_logs columns."""from __future__ import annotationsfrom fastapi import APIRouter, Requestfrom store import get_storerouter = APIRouter(prefix="/api/webhooks", tags=["webhooks"])def _parse_transcript(payload: dict):raw = (30 unmodified linesreturn Nonedef _parse_extractions(extracted_data: dict) -> dict:"""Parse nested {Category: {Name: {subjective, confidence, ...}}} into schema columns."""if not isinstance(extracted_data, dict):return {}result: dict = {}confidences: list[float] = []for category, names in extracted_data.items():if not isinstance(names, dict):continuecat = category.strip().lower()for name, payload in names.items():if not isinstance(payload, dict):continuenm = name.strip().lower()val = payload.get("subjective") or payload.get("objective") or payload.get("value")conf = payload.get("confidence")if isinstance(conf, (int, float)):confidences.append(float(conf))# Conversation Intelligenceif "conversation" in cat and "summary" in nm:result["summary"] = str(val) if val else None# Customer Intelligenceelif "customer" in cat and "sentiment" in nm:result["sentiment"] = str(val) if val else None# Restaurant Intelligence β upsellelif "restaurant" in cat and "upsell" in nm:result["upsell_accepted"] = _bool(val)# Restaurant Intelligence β special requestselif "restaurant" in cat and "special" in nm:result["special_requests"] = str(val) if val else None# Operations β escalationelif "operation" in cat and "escalation" in nm:result["human_escalation"] = _bool(val)# Call Quality β languageelif ("quality" in cat or "call" in cat) and "language" in nm:result["customer_language"] = str(val) if val else None# Orders β upsell fallback (if not already set)elif "order" in cat and "upsell" in nm and "upsell_accepted" not in result:result["upsell_accepted"] = _bool(val)if confidences:result["confidence_score"] = round(sum(confidences) / len(confidences), 3)3 unmodified lines@router.post("/bolna")async def bolna_webhook(request: Request):try:payload = await request.json()except Exception:return {"success": False, "message": "Invalid JSON payload."}context = (payload.get("context_details")or payload.get("user_data")2 unmodified linesif isinstance(context, dict):context = context.get("recipient_data") or contextextracted_data = payload.get("extracted_data") or payload.get("extraction") or {}extraction_cols = _parse_extractions(extracted_data)log = {"session_id": payload.get("id")4 unmodified lines"outlet_location": context.get("outlet_location") if isinstance(context, dict) else None,"channel": "phone" if payload.get("telephony_data") else "web","transcript": _parse_transcript(payload),"extractions": extracted_data if extracted_data else None,**extraction_cols,}saved = get_store().upsert_call_log(log)return {"success": True, "id": saved.get("id")}123456789101112131415161718192021222324252630 unmodified lines575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201213 unmodified lines1251261271281291301311321331341351361371381391401411422 unmodified lines1451461471481491501511521531541551561571581591601614 unmodified lines166167168169170171172173174175176177178179180181182183184"""Bolna post-call webhook β call_logs audit trail.Bolna's payload shape varies by configuration, so parsing is defensive.Extraction data may arrive under several keys depending on Bolna version:- extracted_data {Category: {Name: {subjective, confidence, ...}}}- custom_analytics [{name, category, subjective, confidence, ...}] β list- custom_analytics {Category: {Name: {subjective, ...}}} β nested dict"""from __future__ import annotationsimport jsonimport sysfrom fastapi import APIRouter, Requestfrom store import get_storerouter = APIRouter(prefix="/api/webhooks", tags=["webhooks"])# Last raw payload for debugging via GET /api/webhooks/debug_last_payload: dict = {}def _parse_transcript(payload: dict):raw = (30 unmodified linesreturn Nonedef _parse_one_extraction(cat: str, nm: str, val, conf, result: dict, confidences: list):"""Map a single category/name/value into result columns."""if isinstance(conf, (int, float)):confidences.append(float(conf))if "conversation" in cat and "summary" in nm:result["summary"] = str(val) if val else Noneelif "customer" in cat and "sentiment" in nm:result["sentiment"] = str(val) if val else Noneelif "restaurant" in cat and "upsell" in nm:result["upsell_accepted"] = _bool(val)elif "restaurant" in cat and "special" in nm:result["special_requests"] = str(val) if val else Noneelif "operation" in cat and "escalation" in nm:result["human_escalation"] = _bool(val)elif ("quality" in cat or "call" in cat) and "language" in nm:result["customer_language"] = str(val) if val else Noneelif "order" in cat and "upsell" in nm and "upsell_accepted" not in result:result["upsell_accepted"] = _bool(val)def _parse_extractions(raw) -> dict:"""Parse Bolna extraction data into schema columns.Handles three formats Bolna may send:1. dict {Category: {Name: {subjective, confidence}}} β extracted_data2. list [{name, category, subjective, confidence, ...}] β custom_analytics list3. dict same nested format under custom_analytics key"""if not raw:return {}result: dict = {}confidences: list[float] = []# Format 2: list of flat objects [{name, category, subjective, ...}]if isinstance(raw, list):for item in raw:if not isinstance(item, dict):continuecat = (item.get("category") or "").strip().lower()nm = (item.get("name") or "").strip().lower()val = item.get("subjective") or item.get("objective") or item.get("value")conf = item.get("confidence")_parse_one_extraction(cat, nm, val, conf, result, confidences)# Format 1 / Format 3: nested dict {Category: {Name: {subjective, ...}}}elif isinstance(raw, dict):for category, names in raw.items():if not isinstance(names, dict):continuecat = category.strip().lower()for name, payload in names.items():if not isinstance(payload, dict):continuenm = name.strip().lower()val = payload.get("subjective") or payload.get("objective") or payload.get("value")conf = payload.get("confidence")_parse_one_extraction(cat, nm, val, conf, result, confidences)if confidences:result["confidence_score"] = round(sum(confidences) / len(confidences), 3)3 unmodified lines@router.post("/bolna")async def bolna_webhook(request: Request):global _last_payloadtry:payload = await request.json()except Exception:return {"success": False, "message": "Invalid JSON payload."}# Log raw payload keys to stderr so HF Space logs show us what Bolna sendssafe_preview = {k: (v if not isinstance(v, (list, dict)) else f"<{type(v).__name__} len={len(v)}>")for k, v in payload.items()}print(f"[webhook] keys={list(payload.keys())} preview={json.dumps(safe_preview)}", file=sys.stderr)_last_payload = payloadcontext = (payload.get("context_details")or payload.get("user_data")2 unmodified linesif isinstance(context, dict):context = context.get("recipient_data") or context# Bolna may send extraction results under any of these keysraw_extraction = (payload.get("extracted_data")or payload.get("custom_analytics")or payload.get("extraction")or payload.get("analytics")or payload.get("analysis")or {})extraction_cols = _parse_extractions(raw_extraction)print(f"[webhook] extraction_cols={extraction_cols}", file=sys.stderr)log = {"session_id": payload.get("id")4 unmodified lines"outlet_location": context.get("outlet_location") if isinstance(context, dict) else None,"channel": "phone" if payload.get("telephony_data") else "web","transcript": _parse_transcript(payload),"extractions": raw_extraction if raw_extraction else None,**extraction_cols,}saved = get_store().upsert_call_log(log)return {"success": True, "id": saved.get("id")}@router.get("/debug")async def webhook_debug():"""Return the last raw webhook payload for debugging extraction structure."""return {"keys": list(_last_payload.keys()),"custom_analytics": _last_payload.get("custom_analytics"),"extracted_data": _last_payload.get("extracted_data"),"extraction": _last_payload.get("extraction"),}
routes/webhooks.py+94-51