Spaces:
Running

axeronis commited on
Commit
8a521d3
·
1 Parent(s): 923df09

feat: AI now extracts and updates lead name and niche from conversation

Browse files
backend/app/models/ai_summary.py CHANGED
@@ -1,5 +1,5 @@
1
  from pydantic import BaseModel, Field
2
- from typing import List
3
 
4
 
5
  class AISummary(BaseModel):
@@ -8,6 +8,20 @@ class AISummary(BaseModel):
8
  Enhanced with confidence scores (0.0-1.0) for each key field.
9
  """
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  # Core BANT fields with confidence
12
  intent: str = Field(description="Main goal or objective of the user (НА РУССКОМ)")
13
  intent_confidence: float = Field(description="Confidence in intent extraction (0.0-1.0)")
 
1
  from pydantic import BaseModel, Field
2
+ from typing import List, Optional
3
 
4
 
5
  class AISummary(BaseModel):
 
8
  Enhanced with confidence scores (0.0-1.0) for each key field.
9
  """
10
 
11
+ # CLIENT IDENTIFICATION
12
+ client_name: Optional[str] = Field(
13
+ default=None,
14
+ description="Настоящее имя клиента, если он его назвал в разговоре (НА РУССКОМ). "
15
+ "Например: 'Эндрю', 'Иван', 'Алексей'. Если не назвал → null"
16
+ )
17
+
18
+ niche: Optional[str] = Field(
19
+ default=None,
20
+ description="Ниша/сфера деятельности клиента если упомянул (НА РУССКОМ). "
21
+ "Например: 'Авто из США', 'Ресторанный бизнес', 'IT аутсорс', 'Строительство'. "
22
+ "Извлечь из РЕАЛЬНЫХ слов клиента! Если не упомянул → null"
23
+ )
24
+
25
  # Core BANT fields with confidence
26
  intent: str = Field(description="Main goal or objective of the user (НА РУССКОМ)")
27
  intent_confidence: float = Field(description="Confidence in intent extraction (0.0-1.0)")
backend/app/services/ai_core/lead_analyzer.py CHANGED
@@ -70,6 +70,16 @@ def merge_summaries(old: Dict[str, Any], new: Dict[str, Any]) -> Dict[str, Any]:
70
  merged['timeline'] = old['timeline']
71
  print(f"⏰ Kept old timeline: {old['timeline']}")
72
 
 
 
 
 
 
 
 
 
 
 
73
  # PAIN POINTS: Append unique new points (max 5)
74
  old_pains = old.get('pain_points', []) if isinstance(old.get('pain_points'), list) else []
75
  new_pains = new.get('pain_points', []) if isinstance(new.get('pain_points'), list) else []
@@ -317,6 +327,20 @@ async def analyze_lead_impl(
317
  merged_summary = merge_summaries(old_summary, new_summary)
318
  lead.ai_summary_json = merged_summary
319
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320
  print(f"🔀 Merged summary applied")
321
 
322
  except Exception as e:
 
70
  merged['timeline'] = old['timeline']
71
  print(f"⏰ Kept old timeline: {old['timeline']}")
72
 
73
+ # CLIENT_NAME: Keep old if new is empty (name doesn't change)
74
+ if not new.get('client_name') and old.get('client_name'):
75
+ merged['client_name'] = old['client_name']
76
+ print(f"👤 Kept old client_name: {old['client_name']}")
77
+
78
+ # NICHE: Keep old if new is empty, update if new has better value
79
+ if not new.get('niche') and old.get('niche'):
80
+ merged['niche'] = old['niche']
81
+ print(f"🏢 Kept old niche: {old['niche']}")
82
+
83
  # PAIN POINTS: Append unique new points (max 5)
84
  old_pains = old.get('pain_points', []) if isinstance(old.get('pain_points'), list) else []
85
  new_pains = new.get('pain_points', []) if isinstance(new.get('pain_points'), list) else []
 
327
  merged_summary = merge_summaries(old_summary, new_summary)
328
  lead.ai_summary_json = merged_summary
329
 
330
+ # UPDATE LEAD NAME if AI discovered client's real name
331
+ extracted_name = new_summary.get('client_name')
332
+ if extracted_name and isinstance(extracted_name, str) and len(extracted_name) >= 2:
333
+ # Only update if current name is default (from Telegram/channel) or unknown
334
+ current_name = lead.name or ""
335
+ # Check if name looks like a username (contains @, numbers, or underscores)
336
+ is_username = any(c in current_name for c in ['@', '_', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'])
337
+ is_generic = current_name.lower() in ['unknown', 'клиент', 'client', 'user', '']
338
+
339
+ if is_username or is_generic or current_name != extracted_name:
340
+ old_name = lead.name
341
+ lead.name = extracted_name
342
+ print(f"✅ LEAD NAME UPDATED from summary: '{old_name}' → '{extracted_name}'")
343
+
344
  print(f"🔀 Merged summary applied")
345
 
346
  except Exception as e: