Spaces:
Running

microfunnel-api / backend /app /services /summary_validator.py
axeronis
fix: AI Summary validation and save logic improvements
e9aa757
Raw History Blame Contribute Delete
3.19 kB
"""
AI Summary Validator - prevents saving broken/invalid summaries
"""
from typing import Dict, Any, List, Tuple
from app.core.logging import get_logger
logger = get_logger(__name__)
# Error indicators that suggest invalid data
ERROR_PATTERNS = [
'error', 'failed', 'undefined', 'null', 'none',
'n/a', 'unknown error', 'exception', 'invalid',
'generation error', 'summary generation error'
]
REQUIRED_FIELDS = ['intent', 'budget', 'timeline', 'authority', 'psychotype', 'heat_score']
def validate_summary(summary: Dict[str, Any]) -> Tuple[bool, List[str]]:
"""
Validate AI summary for quality and correctness.
Returns:
(is_valid, list_of_errors)
"""
errors = []
# Check all required fields exist
for field in REQUIRED_FIELDS:
if field not in summary:
errors.append(f"Missing required field: {field}")
if errors:
return False, errors
# Check text fields don't contain error indicators
text_fields = ['intent', 'budget', 'timeline', 'authority',
'hidden_signals', 'recommendation', 'draft_reply']
for field in text_fields:
value = str(summary.get(field, '')).lower()
# Skip if field is intentionally empty or unavailable
if not value or value in ['не указано', 'неизвестно', 'требуется', 'будет уточнено']:
continue
# Check for error patterns
for pattern in ERROR_PATTERNS:
if pattern in value:
errors.append(f"Field '{field}' contains error indicator: '{pattern}'")
break
# Validate heat_score range
heat_score = summary.get('heat_score')
if not isinstance(heat_score, (int, float)) or not (0 <= heat_score <= 100):
errors.append(f"Invalid heat_score: {heat_score} (must be 0-100)")
# Psychotype validation removed - Gemini returns Russian values as instructed
# Accept both English and Russian psychotypes
# Don't fail on empty pain_points - "Будет уточнено" is valid placeholder
is_valid = len(errors) == 0
if not is_valid:
logger.warning(f"⚠️ Summary validation failed: {errors}")
return is_valid, errors
def should_update_summary(old_summary: Dict[str, Any], new_summary: Dict[str, Any]) -> bool:
"""
Determine if new summary is better than old one.
Don't replace good data with bad data.
"""
# If old summary doesn't exist, always update
if not old_summary:
return True
# Validate both summaries
new_valid, new_errors = validate_summary(new_summary)
old_valid, old_errors = validate_summary(old_summary)
# Keep old if new is invalid and old is valid
if old_valid and not new_valid:
logger.info(f"⚠️ Keeping old summary (new one is invalid)")
return False
# Replace old invalid with new valid
if not old_valid and new_valid:
logger.info(f"✅ Replacing invalid old summary with new valid one")
return True
# Both valid or both invalid - update
return True