Spaces:
Running
Running
axeronis commited on
Commit ·
8edb0d5
1
Parent(s): d37b213
feat: Critical improvements - fallback and validation
Browse files- Enhanced Gemini API fallback with smart basic summary generation
- Created summary_validator.py to prevent saving broken AI summaries
- Fallback now uses keyword detection and engagement metrics
- Validation checks for error patterns and data quality
backend/app/services/gemini_client.py
CHANGED
|
@@ -436,23 +436,68 @@ Respond with ONLY a number from 0 to 100."""
|
|
| 436 |
return validated_summary.model_dump()
|
| 437 |
|
| 438 |
except Exception as e:
|
| 439 |
-
logger.error(f"
|
| 440 |
|
| 441 |
-
#
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
pain_points=["Недостаточно данных для анализа"],
|
| 448 |
-
psychotype=psychotype or "Неизвестен",
|
| 449 |
-
heat_score=heat_score if 0 <= heat_score <= 100 else 50,
|
| 450 |
-
objections=["Не обнаружено на данном этапе"],
|
| 451 |
-
hidden_signals="Скрытые мотивы будут выявлены по мере развития диалога",
|
| 452 |
-
recommendation="Продолжите диалог для уточнения потребностей клиента",
|
| 453 |
-
draft_reply=f"Здравствуйте, {lead_name}! Чем могу вам помочь сегодня?"
|
| 454 |
)
|
| 455 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 456 |
|
| 457 |
|
| 458 |
@lru_cache()
|
|
|
|
| 436 |
return validated_summary.model_dump()
|
| 437 |
|
| 438 |
except Exception as e:
|
| 439 |
+
logger.error(f"❌ Gemini API failed for summary generation: {str(e)}", exc_info=True)
|
| 440 |
|
| 441 |
+
# SMART FALLBACK: Extract basic info from messages instead of generic placeholders
|
| 442 |
+
fallback_summary = self._generate_basic_summary(
|
| 443 |
+
messages=messages,
|
| 444 |
+
lead_name=lead_name,
|
| 445 |
+
psychotype=psychotype,
|
| 446 |
+
heat_score=heat_score
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 447 |
)
|
| 448 |
+
|
| 449 |
+
logger.warning(
|
| 450 |
+
f"⚠️ Using fallback summary for lead (Gemini unavailable). "
|
| 451 |
+
f"Score: {fallback_summary.get('heat_score')}"
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
return fallback_summary
|
| 455 |
+
|
| 456 |
+
def _generate_basic_summary(
|
| 457 |
+
self,
|
| 458 |
+
messages: List[Any],
|
| 459 |
+
lead_name: str,
|
| 460 |
+
psychotype: str,
|
| 461 |
+
heat_score: int
|
| 462 |
+
) -> dict:
|
| 463 |
+
"""
|
| 464 |
+
Generate basic summary without Gemini (fallback).
|
| 465 |
+
Uses simple heuristics to extract info from messages.
|
| 466 |
+
"""
|
| 467 |
+
# Extract conversation text
|
| 468 |
+
user_messages = [m.content for m in messages if m.sender_type == 'user']
|
| 469 |
+
conversation_text = " ".join(user_messages).lower()
|
| 470 |
+
|
| 471 |
+
# Simple keyword detection
|
| 472 |
+
has_price_question = any(word in conversation_text for word in ['цена', 'стоимость', 'сколько', 'price'])
|
| 473 |
+
has_timeline = any(word in conversation_text for word in ['когда', 'срок', 'быстро', 'срочно'])
|
| 474 |
+
has_contact = any(word in conversation_text for word in ['телефон', 'почта', 'email', 'связаться'])
|
| 475 |
+
|
| 476 |
+
# Estimate engagement
|
| 477 |
+
message_count = len(user_messages)
|
| 478 |
+
avg_length = sum(len(m) for m in user_messages) / max(message_count, 1)
|
| 479 |
+
|
| 480 |
+
# Adjust heat based on engagement
|
| 481 |
+
if message_count >= 5 and avg_length > 50:
|
| 482 |
+
heat_score = min(heat_score + 10, 100)
|
| 483 |
+
elif message_count <= 2 and avg_length < 20:
|
| 484 |
+
heat_score = max(heat_score - 10, 0)
|
| 485 |
+
|
| 486 |
+
fallback = AISummary(
|
| 487 |
+
intent="Интерес к продукту/услуге (требуется уточнение)" if message_count > 1 else "Первый контакт",
|
| 488 |
+
budget="Обсуждается" if has_price_question else "Не обсуждалось",
|
| 489 |
+
timeline="Есть временные рамки" if has_timeline else "Не обсуждалось",
|
| 490 |
+
authority="Контакт установлен" if has_contact else "Требуется выявить",
|
| 491 |
+
pain_points=["Анализ Gemini недоступен - требуется ручная проверка"],
|
| 492 |
+
psychotype=psychotype or "Unknown",
|
| 493 |
+
heat_score=max(0, min(100, heat_score)),
|
| 494 |
+
objections=["Gemini недоступен"] if message_count > 0 else [],
|
| 495 |
+
hidden_signals="Анализ недоступен (Gemini API error)",
|
| 496 |
+
recommendation=f"Проверьте диалог вручную. Сообщений: {message_count}",
|
| 497 |
+
draft_reply=f"Здравствуйте! Чем могу помочь?"
|
| 498 |
+
)
|
| 499 |
+
|
| 500 |
+
return fallback.model_dump()
|
| 501 |
|
| 502 |
|
| 503 |
@lru_cache()
|
backend/app/services/summary_validator.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
AI Summary Validator - prevents saving broken/invalid summaries
|
| 3 |
+
"""
|
| 4 |
+
from typing import Dict, Any, List, Tuple
|
| 5 |
+
from app.core.logging import get_logger
|
| 6 |
+
|
| 7 |
+
logger = get_logger(__name__)
|
| 8 |
+
|
| 9 |
+
# Error indicators that suggest invalid data
|
| 10 |
+
ERROR_PATTERNS = [
|
| 11 |
+
'error', 'failed', 'undefined', 'null', 'none',
|
| 12 |
+
'n/a', 'unknown error', 'exception', 'invalid',
|
| 13 |
+
'generation error', 'summary generation error'
|
| 14 |
+
]
|
| 15 |
+
|
| 16 |
+
REQUIRED_FIELDS = ['intent', 'budget', 'timeline', 'authority', 'psychotype', 'heat_score']
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def validate_summary(summary: Dict[str, Any]) -> Tuple[bool, List[str]]:
|
| 20 |
+
"""
|
| 21 |
+
Validate AI summary for quality and correctness.
|
| 22 |
+
|
| 23 |
+
Returns:
|
| 24 |
+
(is_valid, list_of_errors)
|
| 25 |
+
"""
|
| 26 |
+
errors = []
|
| 27 |
+
|
| 28 |
+
# Check all required fields exist
|
| 29 |
+
for field in REQUIRED_FIELDS:
|
| 30 |
+
if field not in summary:
|
| 31 |
+
errors.append(f"Missing required field: {field}")
|
| 32 |
+
|
| 33 |
+
if errors:
|
| 34 |
+
return False, errors
|
| 35 |
+
|
| 36 |
+
# Check text fields don't contain error indicators
|
| 37 |
+
text_fields = ['intent', 'budget', 'timeline', 'authority',
|
| 38 |
+
'hidden_signals', 'recommendation', 'draft_reply']
|
| 39 |
+
|
| 40 |
+
for field in text_fields:
|
| 41 |
+
value = str(summary.get(field, '')).lower()
|
| 42 |
+
|
| 43 |
+
# Skip if field is intentionally empty or unavailable
|
| 44 |
+
if not value or value in ['не указано', 'неизвестно', 'требуется', 'будет уточнено']:
|
| 45 |
+
continue
|
| 46 |
+
|
| 47 |
+
# Check for error patterns
|
| 48 |
+
for pattern in ERROR_PATTERNS:
|
| 49 |
+
if pattern in value:
|
| 50 |
+
errors.append(f"Field '{field}' contains error indicator: '{pattern}'")
|
| 51 |
+
break
|
| 52 |
+
|
| 53 |
+
# Validate heat_score range
|
| 54 |
+
heat_score = summary.get('heat_score')
|
| 55 |
+
if not isinstance(heat_score, (int, float)) or not (0 <= heat_score <= 100):
|
| 56 |
+
errors.append(f"Invalid heat_score: {heat_score} (must be 0-100)")
|
| 57 |
+
|
| 58 |
+
# Validate psychotype
|
| 59 |
+
valid_psychotypes = ['dominant', 'influential', 'steady', 'conscientious', 'unknown']
|
| 60 |
+
psychotype = str(summary.get('psychotype', '')).lower()
|
| 61 |
+
if psychotype not in valid_psychotypes:
|
| 62 |
+
errors.append(f"Invalid psychotype: {psychotype}")
|
| 63 |
+
|
| 64 |
+
# Validate lists aren't empty when they should have content
|
| 65 |
+
if summary.get('pain_points') == []:
|
| 66 |
+
errors.append("pain_points is empty (should have at least placeholder)")
|
| 67 |
+
|
| 68 |
+
is_valid = len(errors) == 0
|
| 69 |
+
|
| 70 |
+
if not is_valid:
|
| 71 |
+
logger.warning(f"❌ Summary validation failed: {errors}")
|
| 72 |
+
|
| 73 |
+
return is_valid, errors
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def should_update_summary(old_summary: Dict[str, Any], new_summary: Dict[str, Any]) -> bool:
|
| 77 |
+
"""
|
| 78 |
+
Determine if new summary is better than old one.
|
| 79 |
+
Don't replace good data with bad data.
|
| 80 |
+
"""
|
| 81 |
+
# If old summary doesn't exist, always update
|
| 82 |
+
if not old_summary:
|
| 83 |
+
return True
|
| 84 |
+
|
| 85 |
+
# Validate both summaries
|
| 86 |
+
new_valid, new_errors = validate_summary(new_summary)
|
| 87 |
+
old_valid, old_errors = validate_summary(old_summary)
|
| 88 |
+
|
| 89 |
+
# Keep old if new is invalid and old is valid
|
| 90 |
+
if old_valid and not new_valid:
|
| 91 |
+
logger.info(f"⚠️ Keeping old summary (new one is invalid)")
|
| 92 |
+
return False
|
| 93 |
+
|
| 94 |
+
# Replace old invalid with new valid
|
| 95 |
+
if not old_valid and new_valid:
|
| 96 |
+
logger.info(f"✅ Replacing invalid old summary with new valid one")
|
| 97 |
+
return True
|
| 98 |
+
|
| 99 |
+
# Both valid or both invalid - update
|
| 100 |
+
return True
|