Spaces:
Running

axeronis commited on
Commit
3ecc6cd
·
1 Parent(s): 9589496

fix: final resolution for Gemini summary schema and UI real-time sync

Browse files
backend/app/api/webhook.py CHANGED
@@ -2396,6 +2396,9 @@ async def process_background_ai_tasks(
2396
  summary_generated=analysis.get('summary_generated')
2397
  )
2398
 
 
 
 
2399
  # 3. WEBSOCKET UPDATE
2400
  try:
2401
  await notify_lead_updated(str(lead.id), {
 
2396
  summary_generated=analysis.get('summary_generated')
2397
  )
2398
 
2399
+ # Refresh lead to get latest data after internal commits in analyze_lead
2400
+ await session.refresh(lead)
2401
+
2402
  # 3. WEBSOCKET UPDATE
2403
  try:
2404
  await notify_lead_updated(str(lead.id), {
backend/app/models/ai_summary.py CHANGED
@@ -11,70 +11,60 @@ class AISummary(BaseModel):
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(default="Не определено", description="Main goal or objective of the user (НА РУССКОМ)")
27
- intent_confidence: float = Field(default=0.5, description="Confidence in intent extraction (0.0-1.0)")
28
 
29
- budget: str = Field(default="Не выявлено", description="Financial capacity or budget constraint (НА РУССКОМ)")
30
- budget_confidence: float = Field(default=0.5, description="Confidence in budget assessment")
31
 
32
- timeline: str = Field(default="Не выявлено", description="Urgency or timeframe for the request (НА РУССКОМ)")
33
- timeline_confidence: float = Field(default=0.5, description="Confidence in timeline extraction")
34
 
35
- authority: str = Field(default="Не выявлено", description="Decision-making power or role in the buying process (НА РУССКОМ)")
36
- authority_confidence: float = Field(default=0.5, description="Confidence in authority assessment")
37
 
38
  # Analysis fields
39
- pain_points: List[str] = Field(
40
- default_factory=list,
41
- description="List of problems, needs, or challenges expressed by the user (НА РУССКОМ). "
42
- "ТОЛЬКО из РЕАЛЬНЫХ слов клиента! Если нет данных → ['Будет уточнено']. "
43
- "Формат: список из 2-5 конкретных боли"
44
  )
45
 
46
- psychotype: str = Field(
47
- default="Unknown",
48
- description="DISC personality profile inferred from communication style. "
49
- "Must be one of: 'Dominant', 'Influential', 'Steady', 'Conscientious', or 'Unknown'"
50
  )
51
- psychotype_confidence: float = Field(default=0.5, description="Confidence in psychotype detection")
52
 
53
- heat_score: int = Field(
54
- default=50,
55
- description="Probability of closing the deal, 0-100. Based on BANT, engagement, and buying signals"
56
  )
57
 
58
- objections: List[str] = Field(
59
- default_factory=list,
60
- description="Barriers or concerns preventing the sale (НА РУССКОМ). "
61
- "ТОЛЬКО если клиент ДЕЙСТВИТЕЛЬНО возражал! Если нет → ['Не обнаружено']"
62
  )
63
 
64
- hidden_signals: str = Field(
65
- default="Не обнаружено",
66
- description="Implicit context or subtext read between the lines (НА РУССКОМ). "
67
- "Здесь ИНФЕРЕНС РАЗРЕШЕН (например: клиент пишет коротко → возможно не заинтересован)"
68
  )
69
 
70
- recommendation: str = Field(
71
- default="Продолжить диалог",
72
- description="Strategic advice for the human sales manager on next steps (НА РУССКОМ). "
73
- "Что должен сделать менеджер ДАЛЕЕ? Будьте конкретны"
74
  )
75
 
76
- draft_reply: str = Field(
77
- default="",
78
- description="Suggested response message text, adapted to psychotype (НА РУССКОМ). "
79
- "Профессиональный ответ для продолжения диалога, соответствующий психотипу клиента"
80
  )
 
11
  # CLIENT IDENTIFICATION
12
  client_name: Optional[str] = Field(
13
  default=None,
14
+ description="Настоящее имя клиента"
 
15
  )
16
 
17
  niche: Optional[str] = Field(
18
  default=None,
19
+ description="Ниша/сфера деятельности клиента"
 
 
20
  )
21
 
22
  # Core BANT fields with confidence
23
+ intent: Optional[str] = Field(default=None, description="Main goal or objective")
24
+ intent_confidence: Optional[float] = Field(default=None)
25
 
26
+ budget: Optional[str] = Field(default=None, description="Financial capacity")
27
+ budget_confidence: Optional[float] = Field(default=None)
28
 
29
+ timeline: Optional[str] = Field(default=None, description="Urgency or timeframe")
30
+ timeline_confidence: Optional[float] = Field(default=None)
31
 
32
+ authority: Optional[str] = Field(default=None, description="Decision-making power")
33
+ authority_confidence: Optional[float] = Field(default=None)
34
 
35
  # Analysis fields
36
+ pain_points: Optional[List[str]] = Field(
37
+ default=None,
38
+ description="List of problems"
 
 
39
  )
40
 
41
+ psychotype: Optional[str] = Field(
42
+ default=None,
43
+ description="DISC personality profile"
 
44
  )
45
+ psychotype_confidence: Optional[float] = Field(default=None)
46
 
47
+ heat_score: Optional[int] = Field(
48
+ default=None,
49
+ description="Probability of closing the deal, 0-100"
50
  )
51
 
52
+ objections: Optional[List[str]] = Field(
53
+ default=None,
54
+ description="Barriers or concerns"
 
55
  )
56
 
57
+ hidden_signals: Optional[str] = Field(
58
+ default=None,
59
+ description="Implicit context"
 
60
  )
61
 
62
+ recommendation: Optional[str] = Field(
63
+ default=None,
64
+ description="Strategic advice"
 
65
  )
66
 
67
+ draft_reply: Optional[str] = Field(
68
+ default=None,
69
+ description="Suggested response message"
 
70
  )
backend/app/services/gemini_client.py CHANGED
@@ -439,53 +439,12 @@ Respond with ONLY a number from 0 to 100."""
439
  """
440
 
441
  try:
442
- # 🔧 HARDCODED STRICT SCHEMA FOR GEMINI (Avoids all Pydantic 'default'/'title' noise)
443
- # Gemini response_schema DOES NOT SUPPORT 'default' keys.
444
- gemini_strict_schema = {
445
- "type": "object",
446
- "properties": {
447
- "client_name": {"type": "string", "description": "Настоящее имя клиента или null"},
448
- "niche": {"type": "string", "description": "Ниша/бизнес клиента или null"},
449
- "intent": {"type": "string", "description": "Основная цель клиента"},
450
- "intent_confidence": {"type": "number"},
451
- "budget": {"type": "string", "description": "Бюджет клиента"},
452
- "budget_confidence": {"type": "number"},
453
- "timeline": {"type": "string", "description": "Сроки"},
454
- "timeline_confidence": {"type": "number"},
455
- "authority": {"type": "string", "description": "Роль в принятии решения"},
456
- "authority_confidence": {"type": "number"},
457
- "pain_points": {
458
- "type": "array",
459
- "items": {"type": "string"}
460
- },
461
- "psychotype": {
462
- "type": "string",
463
- "enum": ["Dominant", "Influential", "Steady", "Conscientious", "Unknown"]
464
- },
465
- "psychotype_confidence": {"type": "number"},
466
- "heat_score": {"type": "integer", "description": "0-100"},
467
- "objections": {
468
- "type": "array",
469
- "items": {"type": "string"}
470
- },
471
- "hidden_signals": {"type": "string"},
472
- "recommendation": {"type": "string"},
473
- "draft_reply": {"type": "string"}
474
- },
475
- "required": [
476
- "intent", "intent_confidence", "budget", "budget_confidence",
477
- "timeline", "timeline_confidence", "authority", "authority_confidence",
478
- "pain_points", "psychotype", "psychotype_confidence", "heat_score",
479
- "objections", "hidden_signals", "recommendation", "draft_reply"
480
- ]
481
- }
482
-
483
  # Use new google.genai SDK with JSON response schema
484
  summary_config = types.GenerateContentConfig(
485
  temperature=0.1,
486
  max_output_tokens=4096,
487
  response_mime_type="application/json",
488
- response_schema=gemini_strict_schema
489
  )
490
 
491
  # Run in executor to avoid blocking
 
439
  """
440
 
441
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
442
  # Use new google.genai SDK with JSON response schema
443
  summary_config = types.GenerateContentConfig(
444
  temperature=0.1,
445
  max_output_tokens=4096,
446
  response_mime_type="application/json",
447
+ response_schema=AISummary
448
  )
449
 
450
  # Run in executor to avoid blocking
backend/app/services/llm_client.py CHANGED
@@ -293,18 +293,19 @@ All text fields in RUSSIAN.
293
  contents=prompt,
294
  config=types.GenerateContentConfig(
295
  response_mime_type="application/json",
296
- response_schema=AISummary,
297
  temperature=0.1
298
  )
299
  )
300
  )
301
 
302
  data = json.loads(response.text)
 
303
  return AISummary(**data).model_dump()
304
  except Exception as e:
305
  logger.error(f"Summary failed: {e}")
306
  return {
307
- "intent": "Error", "heat_score": 50, "recommendation": "Manual review needed",
308
  "pain_points": [], "objections": [], "draft_reply": "Error"
309
  }
310
 
 
293
  contents=prompt,
294
  config=types.GenerateContentConfig(
295
  response_mime_type="application/json",
296
+ response_schema=AISummary,
297
  temperature=0.1
298
  )
299
  )
300
  )
301
 
302
  data = json.loads(response.text)
303
+ # Validation via Pydantic but return clean dict
304
  return AISummary(**data).model_dump()
305
  except Exception as e:
306
  logger.error(f"Summary failed: {e}")
307
  return {
308
+ "intent": "Error", "heat_score": heat_score, "recommendation": "Manual review needed",
309
  "pain_points": [], "objections": [], "draft_reply": "Error"
310
  }
311
 
frontend/types/index.ts CHANGED
@@ -67,6 +67,8 @@ export interface Lead {
67
  need: string | null
68
  timeline: string | null
69
  ai_summary_json: AISummaryJson
 
 
70
  first_message_at: string
71
  last_message_at: string
72
  created_at: string
 
67
  need: string | null
68
  timeline: string | null
69
  ai_summary_json: AISummaryJson
70
+ qualification_data?: Record<string, any>
71
+ qualification_complete?: boolean
72
  first_message_at: string
73
  last_message_at: string
74
  created_at: string