Spaces:
Running

microfunnel-api / backend /app /services /lead_qualification.py
axeronis
feat: Chat UI improvements and AI core enhancements
5e04bce
Raw History Blame Contribute Delete
12.6 kB
"""
Lead Qualification Service
Automatically qualifies leads based on conversation analysis:
- BANT scoring (Budget, Authority, Need, Timeline)
- Heat score calculation (0-100)
- Intent detection
- Psychotype analysis
"""
from typing import List, Dict, Any, Optional
from pydantic import BaseModel
from datetime import datetime
from app.models.lead import Lead, LeadHeat, Psychotype, LeadStatus, Message
class BANTScore(BaseModel):
"""BANT qualification scores."""
budget: int = 0 # 0-25
authority: int = 0 # 0-25
need: int = 0 # 0-25
timeline: int = 0 # 0-25
total: int = 0 # 0-100
confidence: float = 0.0 # 0-1
class QualificationResult(BaseModel):
"""Result of lead qualification analysis."""
heat_score: int
heat_level: LeadHeat
bant: BANTScore
intent: str
psychotype: Psychotype
should_sync_to_crm: bool
extracted_fields: Dict[str, Any]
analysis_summary: str
class LeadQualificationService:
"""Service for analyzing and qualifying leads."""
def __init__(self):
self.min_hot_score = 70
self.min_warm_score = 50
self.min_cold_score = 30
async def analyze_conversation(
self,
lead: Lead,
messages: List[Message],
ai_summary: Dict[str, Any]
) -> QualificationResult:
"""
Analyze conversation and qualify the lead.
Args:
lead: The lead to analyze
messages: Conversation messages
ai_summary: AI-generated summary with extracted info
Returns:
QualificationResult with scores and recommendations
"""
# Extract BANT from AI summary
bant = self._extract_bant_from_summary(ai_summary, messages)
# Calculate heat score
heat_score = self.calculate_heat_score(bant, lead, ai_summary)
heat_level = self._calculate_heat_level(heat_score)
# Detect intent
intent = self._detect_intent(ai_summary, messages)
# Analyze psychotype
psychotype = self._analyze_psychotype(ai_summary, messages)
# Determine if should sync to CRM
should_sync = self._should_sync_to_crm(heat_score, lead, bant)
# Extract fields for CRM
extracted_fields = self._extract_crm_fields(ai_summary, lead)
# Generate analysis summary
analysis_summary = self._generate_analysis_summary(
bant, heat_score, intent, psychotype
)
return QualificationResult(
heat_score=heat_score,
heat_level=heat_level,
bant=bant,
intent=intent,
psychotype=psychotype,
should_sync_to_crm=should_sync,
extracted_fields=extracted_fields,
analysis_summary=analysis_summary
)
def _extract_bant_from_summary(
self,
ai_summary: Dict[str, Any],
messages: List[Message]
) -> BANTScore:
"""Extract BANT scores from AI summary."""
# Budget (0-25 points)
budget_score = 0
budget_text = ai_summary.get("budget", "").lower()
if "million" in budget_text or "млн" in budget_text:
budget_score = 25
elif any(word in budget_text for word in ["ready", "готов", "выделен"]):
budget_score = 20
elif any(word in budget_text for word in ["range", "диапазон", "approximate", "примерно"]):
budget_score = 15
elif any(word in budget_text for word in ["considering", "рассматриваю", "depends", "зависит"]):
budget_score = 10
elif any(word in budget_text for word in ["limited", "ограничен", "small", "небольшой"]):
budget_score = 5
# Authority (0-25 points)
authority_score = 0
authority_text = ai_summary.get("authority", "").lower()
if any(word in authority_text for word in ["owner", "ceo", "director", "владелец", "директор"]):
authority_score = 25
elif any(word in authority_text for word in ["head", "руководитель", "manager", "менеджер"]):
authority_score = 20
elif any(word in authority_text for word in ["team lead", "тимлид", "decision maker", "принимаю решения"]):
authority_score = 15
elif any(word in authority_text for word in ["influence", "влияние", "recommend", "рекомендую"]):
authority_score = 10
elif any(word in authority_text for word in ["employee", "сотрудник", "check with", "согласую"]):
authority_score = 5
# Need (0-25 points)
need_score = 0
need_text = ai_summary.get("need", "").lower()
pain_points = ai_summary.get("pain_points", "").lower()
urgency_keywords = ["urgent", "срочно", "critical", "критично", "losing", "теряем"]
moderate_keywords = ["need", "нужно", "want", "хочу", "improve", "улучшить"]
if any(word in need_text for word in urgency_keywords) or \
any(word in pain_points for word in urgency_keywords):
need_score = 25
elif "pain" in pain_points or "проблема" in pain_points:
need_score = 20
elif any(word in need_text for word in moderate_keywords):
need_score = 15
elif "nice to have" in need_text or "было бы неплохо" in need_text:
need_score = 10
# Timeline (0-25 points)
timeline_score = 0
timeline_text = ai_summary.get("timeline", "").lower()
if any(word in timeline_text for word in ["now", "immediately", "сейчас", "немедленно", "asap"]):
timeline_score = 25
elif any(word in timeline_text for word in ["week", "неделя", "days", "дней"]):
timeline_score = 20
elif any(word in timeline_text for word in ["month", "месяц", "quarter", "квартал"]):
timeline_score = 15
elif any(word in timeline_text for word in ["half year", "полгода", "year", "год"]):
timeline_score = 10
elif any(word in timeline_text for word in ["future", "будущем", "someday", "когда-нибудь"]):
timeline_score = 5
total = budget_score + authority_score + need_score + timeline_score
# Calculate confidence based on how much information we have
filled_fields = sum([
1 if budget_score > 0 else 0,
1 if authority_score > 0 else 0,
1 if need_score > 0 else 0,
1 if timeline_score > 0 else 0
])
confidence = filled_fields / 4.0
return BANTScore(
budget=budget_score,
authority=authority_score,
need=need_score,
timeline=timeline_score,
total=total,
confidence=confidence
)
def calculate_heat_score(
self,
bant: BANTScore,
lead: Lead,
ai_summary: Dict[str, Any]
) -> int:
"""Calculate overall heat score (0-100)."""
# Base score from BANT
score = bant.total
# Bonus points for having contact info
if lead.email:
score += 5
if lead.phone:
score += 5
# Bonus for engagement
if ai_summary.get("objections_addressed"):
score += 5
# Reduce for negative indicators
if ai_summary.get("intent") in ["just_browsing", "competitor_research"]:
score -= 15
# Ensure 0-100 range
return max(0, min(100, score))
def _calculate_heat_level(self, heat_score: int) -> LeadHeat:
"""Convert numerical score to heat level."""
if heat_score >= self.min_hot_score:
return LeadHeat.HOT
elif heat_score >= self.min_warm_score:
return LeadHeat.WARM
elif heat_score >= self.min_cold_score:
return LeadHeat.COLD
else:
return LeadHeat.JUNK
def _detect_intent(
self,
ai_summary: Dict[str, Any],
messages: List[Message]
) -> str:
"""Detect user intent from conversation."""
intent = ai_summary.get("intent", "unknown")
# Map AI summary intent to standard values
intent_mapping = {
"ready_to_buy": "ready_to_buy",
"готов_купить": "ready_to_buy",
"evaluating": "evaluating",
"оценивает": "evaluating",
"researching": "researching",
"исследует": "researching",
"competitor_check": "competitor_research",
"сравнение": "competitor_research",
"price_shopping": "price_shopping",
"ценовой_запрос": "price_shopping",
"just_browsing": "just_browsing",
"просто_смотрит": "just_browsing"
}
return intent_mapping.get(intent, intent)
def _analyze_psychotype(
self,
ai_summary: Dict[str, Any],
messages: List[Message]
) -> Psychotype:
"""Analyze psychotype from conversation."""
psycho = ai_summary.get("psychotype", "unknown").lower()
psychotype_mapping = {
"driver": Psychotype.DOMINANT,
"доминантный": Psychotype.DOMINANT,
"analytical": Psychotype.CONSCIENTIOUS,
"аналитический": Psychotype.CONSCIENTIOUS,
"expressive": Psychotype.INFLUENTIAL,
"влиятельный": Psychotype.INFLUENTIAL,
"amiable": Psychotype.STEADY,
"стабильный": Psychotype.STEADY,
}
return psychotype_mapping.get(psycho, Psychotype.UNKNOWN)
def _should_sync_to_crm(
self,
heat_score: int,
lead: Lead,
bant: BANTScore
) -> bool:
"""Determine if lead should be synced to CRM."""
# Must be hot lead
if heat_score < self.min_hot_score:
return False
# Must have contact info
if not lead.email and not lead.phone:
return False
# Must have decent confidence in BANT scoring
if bant.confidence < 0.5:
return False
return True
def _extract_crm_fields(
self,
ai_summary: Dict[str, Any],
lead: Lead
) -> Dict[str, Any]:
"""Extract fields suitable for CRM sync."""
fields = {
"name": lead.name,
"email": lead.email,
"phone": lead.phone,
"company": ai_summary.get("company"),
"position": ai_summary.get("position"),
"industry": ai_summary.get("industry"),
"budget": ai_summary.get("budget"),
"timeline": ai_summary.get("timeline"),
"use_case": ai_summary.get("use_case"),
"pain_points": ai_summary.get("pain_points"),
"decision_context": ai_summary.get("decision_context"),
}
# Remove None values
return {k: v for k, v in fields.items() if v is not None}
def _generate_analysis_summary(
self,
bant: BANTScore,
heat_score: int,
intent: str,
psychotype: Psychotype
) -> str:
"""Generate human-readable analysis summary."""
parts = [
f"Heat Score: {heat_score}/100",
f"BANT Total: {bant.total}/100",
f"Intent: {intent}",
f"Psychotype: {psychotype.value}"
]
if bant.confidence < 0.5:
parts.append("⚠️ Need more information for accurate qualification")
return " | ".join(parts)
# Singleton instance
_qualification_service: Optional[LeadQualificationService] = None
def get_qualification_service() -> LeadQualificationService:
"""Get lead qualification service singleton."""
global _qualification_service
if _qualification_service is None:
_qualification_service = LeadQualificationService()
return _qualification_service