Spaces:
Running

axeronis commited on
Commit
c87b355
·
1 Parent(s): 6055af4

Feature: Smart Human Escalation System

Browse files

New escalation_service.py with 5 intelligent triggers:
1. Negative sentiment detection (Russian + English)
2. Low AI confidence / [NEED_HUMAN] tag
3. Repeated questions detection
4. High-value deal alerts (notify without takeover)
5. AI-requested escalation

Backend changes:
- Integrated escalation check after AI response in webhook.py
- Added Lead model fields: needs_attention, escalation_reason, escalation_at
- Multi-channel notifications (WebSocket + Telegram)

Frontend changes:
- Red blinking badge on leads requiring attention in LeadsList

When escalation triggers:
- Sets human_takeover = true
- Sends Telegram notification to manager
- Shows badge in platform UI

backend/app/api/webhook.py CHANGED
@@ -1333,7 +1333,78 @@ async def process_ai_response_background(
1333
  session.add(ai_message)
1334
  await session.commit()
1335
 
1336
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1337
  # TASK 3: AUTO-ANALYZE LEAD after AI response (UPDATE AI SUMMARY)
1338
  # This runs analyze_lead() to update the 11-point summary
1339
  logger.info(
 
1333
  session.add(ai_message)
1334
  await session.commit()
1335
 
1336
+ # --- SMART ESCALATION CHECK ---
1337
+ # Analyze conversation for need of human intervention
1338
+ try:
1339
+ from app.services.escalation_service import escalation_service
1340
+
1341
+ # Build conversation history for analysis
1342
+ conv_history = []
1343
+ if conversation_messages:
1344
+ for msg in conversation_messages[-10:]: # Last 10 messages
1345
+ conv_history.append({
1346
+ "sender_type": msg.sender_type,
1347
+ "content": msg.content or ""
1348
+ })
1349
+
1350
+ # Analyze the exchange
1351
+ escalation_result = await escalation_service.analyze_message(
1352
+ user_message=user_text or "",
1353
+ ai_response=ai_response["text"],
1354
+ conversation_history=conv_history,
1355
+ heat_score=getattr(lead, 'heat_score', 50) or 50,
1356
+ current_stage=getattr(lead, 'current_stage_id', None)
1357
+ )
1358
+
1359
+ if escalation_result.should_escalate:
1360
+ # Set human takeover
1361
+ conversation.human_takeover = True
1362
+ lead.needs_attention = True
1363
+ lead.escalation_reason = escalation_result.reason.value
1364
+ lead.escalation_at = datetime.utcnow()
1365
+ session.add(conversation)
1366
+ session.add(lead)
1367
+ await session.commit()
1368
+
1369
+ logger.warning(
1370
+ f"🚨 ESCALATION TRIGGERED: {escalation_result.reason.value}",
1371
+ lead_id=str(lead.id),
1372
+ details=escalation_result.details
1373
+ )
1374
+
1375
+ # Send notifications
1376
+ await escalation_service.send_escalation_notification(
1377
+ lead_id=str(lead.id),
1378
+ lead_name=lead.name or "Unknown",
1379
+ reason=escalation_result.reason,
1380
+ urgency=escalation_result.urgency,
1381
+ details=escalation_result.details,
1382
+ last_message=user_text or "",
1383
+ tenant_id=str(tenant.id),
1384
+ channel=channel
1385
+ )
1386
+
1387
+ elif escalation_result.notify_only:
1388
+ # High-value deal - just notify, don't takeover
1389
+ logger.info(
1390
+ f"🟢 HIGH-VALUE ALERT: {escalation_result.details}",
1391
+ lead_id=str(lead.id)
1392
+ )
1393
+ await escalation_service.send_escalation_notification(
1394
+ lead_id=str(lead.id),
1395
+ lead_name=lead.name or "Unknown",
1396
+ reason=escalation_result.reason,
1397
+ urgency=escalation_result.urgency,
1398
+ details=escalation_result.details,
1399
+ last_message=user_text or "",
1400
+ tenant_id=str(tenant.id),
1401
+ channel=channel
1402
+ )
1403
+
1404
+ except Exception as esc_err:
1405
+ logger.warning(f"⚠️ Escalation check failed (non-critical): {esc_err}")
1406
+ # --- END ESCALATION CHECK ---
1407
+
1408
  # TASK 3: AUTO-ANALYZE LEAD after AI response (UPDATE AI SUMMARY)
1409
  # This runs analyze_lead() to update the 11-point summary
1410
  logger.info(
backend/app/models/lead.py CHANGED
@@ -94,6 +94,12 @@ class Lead(SQLModel, table=True):
94
  assigned_to_manager_id: Optional[UUID] = None
95
  assigned_at: Optional[datetime] = None
96
 
 
 
 
 
 
 
97
  # Timestamps
98
  created_at: datetime = Field(default_factory=datetime.utcnow)
99
  updated_at: datetime = Field(default_factory=datetime.utcnow)
 
94
  assigned_to_manager_id: Optional[UUID] = None
95
  assigned_at: Optional[datetime] = None
96
 
97
+ # Escalation (requires human attention)
98
+ needs_attention: bool = Field(default=False)
99
+ escalation_reason: Optional[str] = None # negative_sentiment, low_confidence, etc.
100
+ escalation_at: Optional[datetime] = None
101
+
102
+
103
  # Timestamps
104
  created_at: datetime = Field(default_factory=datetime.utcnow)
105
  updated_at: datetime = Field(default_factory=datetime.utcnow)
backend/app/services/escalation_service.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Escalation Service - Smart Human Intervention Detection
3
+
4
+ Automatically detects when AI needs human help and notifies managers.
5
+
6
+ Triggers:
7
+ 1. Negative Sentiment - Customer is upset/angry
8
+ 2. Low AI Confidence - Bot doesn't know the answer
9
+ 3. Repeated Questions - Customer asks same thing multiple times
10
+ 4. High-Value Deal - Close to closing, needs human touch
11
+ 5. Response Timeout - AI taking too long
12
+ """
13
+
14
+ import re
15
+ from datetime import datetime, timedelta
16
+ from typing import Optional, Dict, List, Tuple
17
+ from uuid import UUID
18
+ from enum import Enum
19
+ from dataclasses import dataclass
20
+ from app.core.logging import get_logger
21
+
22
+ logger = get_logger(__name__)
23
+
24
+
25
+ class EscalationReason(str, Enum):
26
+ NEGATIVE_SENTIMENT = "negative_sentiment"
27
+ LOW_CONFIDENCE = "low_confidence"
28
+ REPEATED_QUESTIONS = "repeated_questions"
29
+ HIGH_VALUE_DEAL = "high_value_deal"
30
+ RESPONSE_TIMEOUT = "response_timeout"
31
+ AI_REQUESTED = "ai_requested" # AI added [NEED_HUMAN] tag
32
+
33
+
34
+ class EscalationUrgency(str, Enum):
35
+ HIGH = "high" # Immediate attention needed
36
+ MEDIUM = "medium" # Should address soon
37
+ LOW = "low" # Informational, no rush
38
+
39
+
40
+ @dataclass
41
+ class EscalationResult:
42
+ """Result of escalation analysis."""
43
+ should_escalate: bool
44
+ reason: Optional[EscalationReason] = None
45
+ urgency: EscalationUrgency = EscalationUrgency.MEDIUM
46
+ details: str = ""
47
+ notify_only: bool = False # If True, notify but don't set human_takeover
48
+
49
+
50
+ # Negative words in Russian and English
51
+ NEGATIVE_WORDS_RU = [
52
+ "злюсь", "злой", "разозлил", "бесит", "ужасно", "ужасный", "плохо", "плохой",
53
+ "недоволен", "недовольна", "отстой", "отвратительно", "кошмар", "позор",
54
+ "враньё", "обман", "мошенники", "развод", "тупой", "идиот", "дебил",
55
+ "надоело", "достало", "хватит", "жалоба", "жаловаться", "вернуть деньги",
56
+ "отвечайте", "где ответ", "сколько можно", "третий раз"
57
+ ]
58
+
59
+ NEGATIVE_WORDS_EN = [
60
+ "angry", "upset", "frustrated", "terrible", "awful", "horrible", "bad",
61
+ "disappointed", "scam", "fraud", "liar", "idiot", "stupid", "useless",
62
+ "complain", "refund", "lawsuit", "unacceptable", "disgusting", "worst"
63
+ ]
64
+
65
+ # Phrases indicating AI doesn't know answer (added by AI)
66
+ LOW_CONFIDENCE_PHRASES = [
67
+ "[NEED_HUMAN]", "[НУЖЕН_ЧЕЛОВЕК]",
68
+ "не уверен", "не могу точно сказать", "лучше уточнить у специалиста",
69
+ "рекомендую связаться", "нужно уточнить", "не владею информацией",
70
+ "I'm not sure", "I don't know", "please contact support",
71
+ "beyond my knowledge", "специалист поможет", "не моя компетенция"
72
+ ]
73
+
74
+ # Phrases indicating repeated questions
75
+ REPETITION_PHRASES = [
76
+ "я уже спрашивал", "повторяю", "ещё раз", "снова спрашиваю",
77
+ "сколько раз", "опять", "в третий раз", "который раз",
78
+ "I already asked", "I repeat", "again", "how many times"
79
+ ]
80
+
81
+
82
+ class EscalationService:
83
+ """
84
+ Analyzes conversations and detects when human intervention is needed.
85
+ """
86
+
87
+ def __init__(self):
88
+ self.repetition_threshold = 2 # Escalate after N repeated questions
89
+ self.high_value_threshold = 80 # Heat score threshold
90
+ self.timeout_minutes = 5 # Max AI response time before escalation
91
+
92
+ async def analyze_message(
93
+ self,
94
+ user_message: str,
95
+ ai_response: str,
96
+ conversation_history: List[Dict],
97
+ heat_score: int = 50,
98
+ current_stage: Optional[str] = None
99
+ ) -> EscalationResult:
100
+ """
101
+ Analyze message and conversation to determine if escalation needed.
102
+
103
+ Args:
104
+ user_message: Latest message from customer
105
+ ai_response: Latest AI response
106
+ conversation_history: Previous messages
107
+ heat_score: Current lead heat score (0-100)
108
+ current_stage: Current funnel stage
109
+
110
+ Returns:
111
+ EscalationResult with escalation decision and details
112
+ """
113
+
114
+ # 1. Check for AI-requested escalation (highest priority)
115
+ result = self._check_ai_requested(ai_response)
116
+ if result.should_escalate:
117
+ return result
118
+
119
+ # 2. Check negative sentiment (high priority)
120
+ result = self._check_negative_sentiment(user_message)
121
+ if result.should_escalate:
122
+ return result
123
+
124
+ # 3. Check for repeated questions
125
+ result = self._check_repeated_questions(user_message, conversation_history)
126
+ if result.should_escalate:
127
+ return result
128
+
129
+ # 4. Check for high-value deal (notify only, don't takeover)
130
+ result = self._check_high_value_deal(heat_score, user_message, current_stage)
131
+ if result.should_escalate or result.notify_only:
132
+ return result
133
+
134
+ # No escalation needed
135
+ return EscalationResult(should_escalate=False)
136
+
137
+ def _check_ai_requested(self, ai_response: str) -> EscalationResult:
138
+ """Check if AI explicitly requested human help."""
139
+ ai_lower = ai_response.lower()
140
+
141
+ for phrase in LOW_CONFIDENCE_PHRASES:
142
+ if phrase.lower() in ai_lower:
143
+ return EscalationResult(
144
+ should_escalate=True,
145
+ reason=EscalationReason.AI_REQUESTED if "[NEED_HUMAN]" in ai_response else EscalationReason.LOW_CONFIDENCE,
146
+ urgency=EscalationUrgency.HIGH if "[NEED_HUMAN]" in ai_response else EscalationUrgency.MEDIUM,
147
+ details=f"AI указал на необходимость человека: '{phrase}'"
148
+ )
149
+
150
+ return EscalationResult(should_escalate=False)
151
+
152
+ def _check_negative_sentiment(self, message: str) -> EscalationResult:
153
+ """Check for negative sentiment in customer message."""
154
+ message_lower = message.lower()
155
+
156
+ # Count negative indicators
157
+ negative_count = 0
158
+ found_words = []
159
+
160
+ for word in NEGATIVE_WORDS_RU + NEGATIVE_WORDS_EN:
161
+ if word.lower() in message_lower:
162
+ negative_count += 1
163
+ found_words.append(word)
164
+
165
+ # Check for excessive caps (shouting)
166
+ caps_ratio = sum(1 for c in message if c.isupper()) / max(len(message), 1)
167
+ if caps_ratio > 0.5 and len(message) > 10:
168
+ negative_count += 1
169
+ found_words.append("CAPS LOCK")
170
+
171
+ # Check for excessive punctuation
172
+ if message.count("!") >= 3 or message.count("?") >= 3:
173
+ negative_count += 1
174
+ found_words.append("много восклицаний")
175
+
176
+ # Escalate if 2+ negative indicators
177
+ if negative_count >= 2:
178
+ return EscalationResult(
179
+ should_escalate=True,
180
+ reason=EscalationReason.NEGATIVE_SENTIMENT,
181
+ urgency=EscalationUrgency.HIGH,
182
+ details=f"Негативный тон: {', '.join(found_words[:3])}"
183
+ )
184
+ elif negative_count >= 1:
185
+ return EscalationResult(
186
+ should_escalate=True,
187
+ reason=EscalationReason.NEGATIVE_SENTIMENT,
188
+ urgency=EscalationUrgency.MEDIUM,
189
+ details=f"Возможное недовольство: {', '.join(found_words[:3])}"
190
+ )
191
+
192
+ return EscalationResult(should_escalate=False)
193
+
194
+ def _check_repeated_questions(
195
+ self,
196
+ message: str,
197
+ history: List[Dict]
198
+ ) -> EscalationResult:
199
+ """Check if customer is repeating questions."""
200
+ message_lower = message.lower()
201
+
202
+ # Check for explicit repetition phrases
203
+ for phrase in REPETITION_PHRASES:
204
+ if phrase.lower() in message_lower:
205
+ return EscalationResult(
206
+ should_escalate=True,
207
+ reason=EscalationReason.REPEATED_QUESTIONS,
208
+ urgency=EscalationUrgency.MEDIUM,
209
+ details=f"Клиент явно указал на повторение вопроса"
210
+ )
211
+
212
+ # Check history for similar questions
213
+ if len(history) >= 4:
214
+ user_messages = [
215
+ m.get("content", "").lower()
216
+ for m in history
217
+ if m.get("sender_type") == "user"
218
+ ][-5:] # Last 5 user messages
219
+
220
+ # Simple similarity check (words overlap)
221
+ current_words = set(re.findall(r'\w+', message_lower))
222
+ similar_count = 0
223
+
224
+ for prev_msg in user_messages[:-1]: # Exclude current
225
+ prev_words = set(re.findall(r'\w+', prev_msg))
226
+ overlap = len(current_words & prev_words)
227
+ if overlap >= 3 and overlap / max(len(current_words), 1) > 0.5:
228
+ similar_count += 1
229
+
230
+ if similar_count >= self.repetition_threshold:
231
+ return EscalationResult(
232
+ should_escalate=True,
233
+ reason=EscalationReason.REPEATED_QUESTIONS,
234
+ urgency=EscalationUrgency.MEDIUM,
235
+ details=f"Похожий вопрос задан {similar_count + 1} раз"
236
+ )
237
+
238
+ return EscalationResult(should_escalate=False)
239
+
240
+ def _check_high_value_deal(
241
+ self,
242
+ heat_score: int,
243
+ message: str,
244
+ stage: Optional[str]
245
+ ) -> EscalationResult:
246
+ """Check if deal is hot and needs human attention."""
247
+ message_lower = message.lower()
248
+
249
+ # Buying signals
250
+ buying_keywords = [
251
+ "цена", "стоимость", "оплата", "оплатить", "купить", "заказать",
252
+ "price", "cost", "pay", "buy", "order", "purchase",
253
+ "договор", "контракт", "счёт", "реквизиты", "когда можно начать"
254
+ ]
255
+
256
+ has_buying_signal = any(kw in message_lower for kw in buying_keywords)
257
+ is_hot = heat_score >= self.high_value_threshold
258
+ is_closing_stage = stage in ["negotiation", "closing", "payment"]
259
+
260
+ if (is_hot and has_buying_signal) or is_closing_stage:
261
+ return EscalationResult(
262
+ should_escalate=False, # Don't takeover, just notify
263
+ notify_only=True,
264
+ reason=EscalationReason.HIGH_VALUE_DEAL,
265
+ urgency=EscalationUrgency.LOW,
266
+ details=f"Горячая сделка (heat: {heat_score}%), сигнал к покупке"
267
+ )
268
+
269
+ return EscalationResult(should_escalate=False)
270
+
271
+ async def send_escalation_notification(
272
+ self,
273
+ lead_id: str,
274
+ lead_name: str,
275
+ reason: EscalationReason,
276
+ urgency: EscalationUrgency,
277
+ details: str,
278
+ last_message: str,
279
+ tenant_id: str,
280
+ channel: str = "telegram"
281
+ ):
282
+ """
283
+ Send notification to manager about escalation.
284
+
285
+ Channels:
286
+ 1. WebSocket (in-app real-time)
287
+ 2. Telegram (manager bot)
288
+ """
289
+
290
+ urgency_emoji = {
291
+ EscalationUrgency.HIGH: "🔴",
292
+ EscalationUrgency.MEDIUM: "🟡",
293
+ EscalationUrgency.LOW: "🟢"
294
+ }
295
+
296
+ reason_text = {
297
+ EscalationReason.NEGATIVE_SENTIMENT: "Негативный тон клиента",
298
+ EscalationReason.LOW_CONFIDENCE: "AI не уверен в ответе",
299
+ EscalationReason.REPEATED_QUESTIONS: "Клиент повторяет вопросы",
300
+ EscalationReason.HIGH_VALUE_DEAL: "Горячая сделка",
301
+ EscalationReason.RESPONSE_TIMEOUT: "Долгое ожидание ответа",
302
+ EscalationReason.AI_REQUESTED: "AI запросил помощь человека"
303
+ }
304
+
305
+ # 1. WebSocket notification (in-app)
306
+ try:
307
+ from app.api.websocket_chat import notify_lead_updated
308
+ await notify_lead_updated(lead_id, {
309
+ "id": lead_id,
310
+ "needs_attention": True,
311
+ "escalation_reason": reason.value,
312
+ "escalation_urgency": urgency.value,
313
+ "escalation_details": details
314
+ })
315
+ logger.info(f"📡 Escalation WebSocket sent for lead {lead_id}")
316
+ except Exception as e:
317
+ logger.warning(f"⚠️ WebSocket escalation notify failed: {e}")
318
+
319
+ # 2. Telegram notification to manager
320
+ try:
321
+ from app.services.notifications import send_platform_notification
322
+
323
+ message = f"""{urgency_emoji.get(urgency, '🔔')} Требуется внимание!
324
+
325
+ 👤 Клиент: {lead_name}
326
+ 💬 Канал: {channel}
327
+ 📊 Причина: {reason_text.get(reason, reason.value)}
328
+
329
+ 📝 Детали: {details}
330
+
331
+ 💬 Последнее сообщение:
332
+ "{last_message[:200]}..."
333
+
334
+ 🔗 Открыть чат: {{frontend_url}}/chats?leadId={lead_id}
335
+ """
336
+
337
+ await send_platform_notification(
338
+ tenant_id=tenant_id,
339
+ notification_type="escalation",
340
+ message=message
341
+ )
342
+ logger.info(f"📱 Escalation Telegram sent for lead {lead_id}")
343
+ except Exception as e:
344
+ logger.warning(f"⚠️ Telegram escalation notify failed: {e}")
345
+
346
+
347
+ # Singleton instance
348
+ escalation_service = EscalationService()
frontend/components/LeadsList.tsx CHANGED
@@ -249,6 +249,15 @@ export function LeadsList({
249
  isSelected ? "text-white" : "text-slate-300 group-hover:text-white"
250
  )}>
251
  {lead.name || 'Без имени'}
 
 
 
 
 
 
 
 
 
252
  </h3>
253
  <div className="flex items-center gap-1">
254
  {/* Delete Button - shows on hover */}
 
249
  isSelected ? "text-white" : "text-slate-300 group-hover:text-white"
250
  )}>
251
  {lead.name || 'Без имени'}
252
+ {/* Needs Attention Badge */}
253
+ {(lead as any).needs_attention && (
254
+ <span
255
+ className="inline-flex items-center ml-2 px-1.5 py-0.5 rounded-full text-[10px] font-bold bg-red-500/20 text-red-400 border border-red-500/30 animate-pulse"
256
+ title={`Требует внимания: ${(lead as any).escalation_reason || 'эскалация'}`}
257
+ >
258
+ 🔴
259
+ </span>
260
+ )}
261
  </h3>
262
  <div className="flex items-center gap-1">
263
  {/* Delete Button - shows on hover */}