Spaces:
Sleeping
Sleeping
fix: webhook handles custom_analytics key + debug endpoint
Browse files12345673456789101112131415161718192021222324252630 unmodified lines57585954555660616263646566676869707172737475767778798081828384858687888990919293946263646566676895969798997071727374757677787980818283848586878889909192939495969798991001011021001011021031041051061071081091101111121131141151161171181191201213 unmodified lines1251261271281291301311321331341351361371381391401411422 unmodified lines1451461471251261481491501511521531541551561571581591601614 unmodified lines166167168137169170171172173174175176177178179180181182183184"""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.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 annotations
import jsonimport sys
from fastapi import APIRouter, Request
from store import get_store
router = 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 lines return None
def _parse_extractions(extracted_data: dict) -> dict: """Parse nested {Category: {Name: {subjective, confidence, ...}}} into schema columns.""" if not isinstance(extracted_data, dict):def _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 None elif "customer" in cat and "sentiment" in nm: result["sentiment"] = str(val) if val else None elif "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 None elif "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 None elif "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_data 2. list [{name, category, subjective, confidence, ...}] β custom_analytics list 3. dict same nested format under custom_analytics key """ if not raw: return {}
result: dict = {} confidences: list[float] = []
for category, names in extracted_data.items(): if not isinstance(names, dict): continue cat = category.strip().lower()
for name, payload in names.items(): if not isinstance(payload, dict): # Format 2: list of flat objects [{name, category, subjective, ...}] if isinstance(raw, list): for item in raw: if not isinstance(item, dict): continue nm = 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 Intelligence if "conversation" in cat and "summary" in nm: result["summary"] = str(val) if val else None
# Customer Intelligence elif "customer" in cat and "sentiment" in nm: result["sentiment"] = str(val) if val else None
# Restaurant Intelligence β upsell elif "restaurant" in cat and "upsell" in nm: result["upsell_accepted"] = _bool(val)
# Restaurant Intelligence β special requests elif "restaurant" in cat and "special" in nm: result["special_requests"] = str(val) if val else None
# Operations β escalation elif "operation" in cat and "escalation" in nm: result["human_escalation"] = _bool(val)
# Call Quality β language elif ("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) cat = (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): continue cat = category.strip().lower() for name, payload in names.items(): if not isinstance(payload, dict): continue nm = 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_payload try: 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 sends safe_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 = payload
context = ( payload.get("context_details") or payload.get("user_data")2 unmodified lines if isinstance(context, dict): context = context.get("recipient_data") or context
extracted_data = payload.get("extracted_data") or payload.get("extraction") or {} extraction_cols = _parse_extractions(extracted_data) # Bolna may send extraction results under any of these keys raw_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": extracted_data if extracted_data else None, "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