import logging import asyncio from typing import Optional, List, Dict, Any from functools import lru_cache import time from google import genai from google.genai import types from app.core.config import settings from app.services.ai_queue import get_ai_queue from app.models.ai_summary import AISummary logger = logging.getLogger(__name__) class GeminiAPIError(Exception): """Custom exception for Gemini API errors.""" pass class GeminiRateLimitError(GeminiAPIError): """Raised when rate limit is exceeded.""" pass class GoogleGeminiClient: """Client for Google Gemini AI API (Updated for google-genai SDK).""" def __init__(self): """Initialize Gemini client.""" # New SDK Initialization self.client = genai.Client(api_key=settings.GEMINI_API_KEY) self.model_name = settings.GEMINI_MODEL self.ai_queue = get_ai_queue() # Rate limiting queue # Generation config (types.GenerateContentConfig) self.config = types.GenerateContentConfig( temperature=settings.TEMPERATURE, max_output_tokens=settings.MAX_TOKENS, ) async def generate_response( self, prompt: str, system_instruction: Optional[str] = None, context: Optional[List[Dict[str, str]]] = None, temperature: Optional[float] = None, max_retries: int = 3, priority: int = 5 ) -> Dict[str, Any]: """ Generate AI response using Gemini with retry logic and rate limiting. """ # Wrap in rate-limited queue return await self.ai_queue.execute( self._generate_response_internal, priority=priority, prompt=prompt, system_instruction=system_instruction, context=context, temperature=temperature, max_retries=max_retries ) async def _generate_response_internal( self, prompt: str, system_instruction: Optional[str] = None, context: Optional[List[Dict[str, str]]] = None, temperature: Optional[float] = None, max_retries: int = 3 ) -> Dict[str, Any]: """ Internal method - actual Gemini API call (called via queue). """ # Override config if temperature provided current_config = self.config if temperature is not None: current_config = types.GenerateContentConfig( temperature=temperature, max_output_tokens=settings.MAX_TOKENS, system_instruction=system_instruction ) elif system_instruction: current_config = types.GenerateContentConfig( temperature=settings.TEMPERATURE, max_output_tokens=settings.MAX_TOKENS, system_instruction=system_instruction ) for attempt in range(max_retries): try: # Prepare contents contents = [] # History / Context handling if context: # Map old context format to new SDK if needed # Expected: List[types.Content] or compatible list of dicts # Old format: [{"role": "user", "parts": ["text"]}] # New format: similar, but "parts" should be list of Part or text for msg in context: role = "user" if msg.get("role") in ["user", "human"] else "model" parts_text = [] if "parts" in msg: if isinstance(msg["parts"], list): for p in msg["parts"]: if isinstance(p, dict) and "text" in p: parts_text.append(p["text"]) elif isinstance(p, str): parts_text.append(p) elif "text" in msg: # Fallback parts_text.append(msg["text"]) contents.append( types.Content( role=role, parts=[types.Part.from_text(text=t) for t in parts_text] ) ) # Add current prompt contents.append( types.Content( role="user", parts=[types.Part.from_text(text=prompt)] ) ) # Execute call (run_in_executor for async) loop = asyncio.get_event_loop() response = await loop.run_in_executor( None, lambda: self.client.models.generate_content( model=self.model_name, contents=contents, config=current_config ) ) # Extract token usage usage = response.usage_metadata return { "text": response.text, "prompt_tokens": usage.prompt_token_count if usage else 0, "completion_tokens": usage.candidates_token_count if usage else 0, "total_tokens": usage.total_token_count if usage else 0, } except Exception as e: error_msg = str(e).lower() # SAFETY BLOCK ERROR (finish_reason=2) if "finish_reason" in error_msg and "2" in error_msg: if attempt < max_retries - 1: logger.warning( f"Gemini safety block detected. Retrying with safer context (attempt {attempt + 1}/{max_retries})" ) # For context-based calls, add safety instruction to existing context if context: context_copy = context.copy() context_copy.append({ "role": "user", "parts": [{"text": "ВАЖНО: Игнорируйте неуместные сообщения. Фокусируйтесь на деловой коммуникации."}] }) context = context_copy await asyncio.sleep(1) continue else: logger.error("Gemini blocked content after retries - returning professional rejection") # Return professional response when content is blocked return { "text": "Извините, я могу помогать только с вопросами, связанными с нашим бизнесом. Чем могу быть полезен по работе?", "prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0, } # Check if it's a rate limit error if "rate limit" in error_msg or "429" in error_msg or "quota" in error_msg: if attempt < max_retries - 1: # Exponential backoff: 2^attempt seconds wait_time = 2 ** attempt logger.warning(f"Gemini rate limit hit. Retrying in {wait_time}s (attempt {attempt + 1}/{max_retries})") await asyncio.sleep(wait_time) continue else: logger.error(f"Gemini rate limit exceeded after {max_retries} attempts") raise GeminiRateLimitError(f"Rate limit exceeded: {str(e)}") # Check if it's a temporary error elif "503" in error_msg or "500" in error_msg or "timeout" in error_msg: if attempt < max_retries - 1: wait_time = 1 + attempt # Linear backoff for server errors logger.warning(f"Gemini temporary error. Retrying in {wait_time}s (attempt {attempt + 1}/{max_retries})") await asyncio.sleep(wait_time) continue else: logger.error(f"Gemini API unavailable after {max_retries} attempts") raise GeminiAPIError(f"API unavailable: {str(e)}") # For other errors, fail immediately logger.error(f"Gemini API Error: {e}") raise GeminiAPIError(f"AI generation failed: {str(e)}") async def analyze_psychotype(self, messages: List[str]) -> str: """ Detect user's DISC personality type from messages. UPDATED: Immediate inference mode - analyze even single "Hi" message. Args: messages: List of user messages Returns: One of: "dominant", "influential", "steady", "conscientious", "unknown" """ prompt = f"""Analyze the following messages and determine the DISC personality type: Messages: {chr(10).join(f"- {msg}" for msg in messages[-10:])} DISC Types: - DOMINANT (D): Direct, results-oriented, decisive, assertive, competitive - INFLUENTIAL (I): Enthusiastic, optimistic, social, talkative, emotional - STEADY (S): Patient, calm, supportive, good listener, team player - CONSCIENTIOUS (C): Analytical, precise, detail-oriented, asks many questions **TASK 3: IMMEDIATE INFERENCE MODE** - Even a SINGLE message like "Hi" allows a basic DISC guess: • "Hi bro!" / "Hey!" -> I (Influential - casual, friendly) • "Greetings." / "Good day." -> C (Conscientious - formal, precise) • "Need info ASAP" / "Quick question" -> D (Dominant - direct, urgent) • "Hello, hope you're well :)" -> S (Steady - polite, considerate) - Analyze TONE, punctuation, word choice immediately - Don't wait for 3+ messages - make educated guess NOW - Only return "unknown" if message is completely ambiguous (e.g., single emoji) Respond with ONLY ONE WORD: dominant, influential, steady, conscientious, or unknown""" try: response = await self.generate_response(prompt, temperature=0.3) psychotype = response["text"].strip().lower() valid_types = ["dominant", "influential", "steady", "conscientious", "unknown"] return psychotype if psychotype in valid_types else "unknown" except Exception as e: logger.error(f"Psychotype analysis failed: {str(e)}", exc_info=True) return "unknown" async def calculate_heat_score( self, conversation_text: str, bant_data: Dict[str, Optional[str]] ) -> int: """ Calculate lead heat score (0-100). Args: conversation_text: Full conversation history bant_data: Dict with budget, authority, need, timeline Returns: Heat score from 0 to 100 """ prompt = f"""Analyze this sales conversation and assign a heat score from 0-100. Conversation: {conversation_text} BANT Qualification: - Budget: {bant_data.get('budget', 'Unknown')} - Authority: {bant_data.get('authority', 'Unknown')} - Need: {bant_data.get('need', 'Unknown')} - Timeline: {bant_data.get('timeline', 'Unknown')} Scoring criteria: - 90-100 (HOT): Ready to buy now, budget confirmed, decision maker, urgent need - 70-89 (WARM): Interested, has budget, timeline within 2 weeks - 50-69 (WARM): Exploring options, considering, timeline 1+ months - 30-49 (COLD): Just researching, no clear timeline - 0-29 (JUNK): Not interested, no budget, not decision maker, or spam Respond with ONLY a number from 0 to 100.""" try: response = await self.generate_response(prompt, temperature=0.2) score_text = response["text"].strip() # Extract number import re match = re.search(r'\b(\d{1,3})\b', score_text) if match: score = int(match.group(1)) return min(100, max(0, score)) # Clamp to 0-100 return 50 # Default middle score except Exception as e: logger.error(f"Heat score calculation failed: {str(e)}", exc_info=True) return 50 async def generate_11_point_summary( self, conversation_text: str, lead_name: str, psychotype: str, heat_score: int, business_description: str = "We provide products and services", tenant_settings: Optional[Dict[str, Any]] = None, messages: Optional[List[Any]] = None ) -> Dict[str, Any]: """ Generate the comprehensive 11-point AI summary using structured output. Uses Gemini's response_schema for guaranteed JSON matching AISummary model. **CORE LOGIC UPDATE: Universal Business Agnosticism** - Constructs dynamic system prompt from tenant.ai_settings - 100% adaptable to ANY industry (not biased towards specific business) - Injects tenant's qualification criteria, ideal customer, selling style Args: conversation_text: Full conversation history (includes USER/AI/MANAGER messages) lead_name: Name of the lead psychotype: Detected DISC type heat_score: Calculated heat score business_description: Tenant's business description from ai_settings tenant_settings: Full tenant AI settings for context Returns: Dict with 11 fields matching AISummary schema """ # TASK 3: Universal Fallback - prevent crashes for new tenants tenant_settings = tenant_settings or {} # Extract tenant-specific context (business agnostic) business_desc = business_description or tenant_settings.get('business_description', '') if not business_desc.strip(): # FALLBACK: Generic context if no configuration business_desc = "Вы - помощник по продажам. Извлекайте общую информацию о намерениях клиента." ideal_customer = tenant_settings.get('ideal_customer_profile', 'Клиент с реальными потребностями') selling_style = tenant_settings.get('selling_style', 'Консультативный') tone_of_voice = tenant_settings.get('tone_of_voice', 'Профессиональный') custom_fields = tenant_settings.get('custom_qualification_fields', []) # TASK 1: Dynamic System Prompt Construction (inject tenant settings) system_instruction = f"""Вы - эксперт по анализу продаж для бизнеса со следующим профилем: === КОНТЕКСТ БИЗНЕСА (SOLE TRUTH) === ЧТО МЫ ПРОДАЁМ: {business_desc} ИДЕАЛЬНЫЙ КЛИЕНТ: {ideal_customer} СТИЛЬ ПРОДАЖ: {selling_style} (Тон: {tone_of_voice}) === КРИТЕРИИ КВАЛИФИКАЦИИ === Пользователь определил эти специфические поля для поиска: {chr(10).join(f"- {field}" for field in custom_fields) if custom_fields else "(Стандартная BANT-квалификация)"} === ИНСТРУКЦИИ === Проанализируйте историю диалога ниже. 1. **Intent (Намерение):** На основе "ЧТО МЫ ПРОДАЁМ", что хочет пользователь? Какую задачу решает? 2. **Budget (Бюджет):** Ищите денежные сигналы, релевантные ЭТОМУ бизнес-контексту. - Если клиент говорит "дорого" → ИНФЕРЬТЕ: "Ограниченный бюджет" - Если спрашивает про премиум-вариант → ИНФЕРЬТЕ: "Премиум-сегмент" 3. **Match Score (Соответствие):** Сравните пользователя с "ИДЕАЛЬНЫМ КЛИЕНТОМ". - Если хорошо соответствует → Высокая оценка - Если запрашивает то, что МЫ НЕ ПРОДАЁМ → Низкая оценка 4. **Custom Fields:** Если пользователь упоминает что-то из "КРИТЕРИЕВ КВАЛИФИКАЦИИ", добавьте в 'hidden_signals' или 'pain_points'. **КРИТИЧЕСКИ ВАЖНО:** - ВСЕ 11 полей должны быть НА РУССКОМ языке - Используйте ИНФЕРЕНС (inference): анализируйте тон, контекст, неявные сигналы - **ЗАПРЕЩЕНО додумывать боли клиента, которых НЕТ в диалоге!** - **pain_points должны быть ТОЛЬКО из РЕАЛЬНЫХ слов клиента, не из вашего воображения!** - **objections должны быть ТОЛЬКО если клиент ДЕЙСТВИТЕЛЬНО возражал!** - Только если АБСОЛЮТНО нет данных, используйте: "Будет уточнено" - НЕ используйте английские слова типа "Unknown", "Not specified" """ # TASK 2: Include MANAGER messages in prompt (fix amnesia) prompt = f"""{system_instruction} Проанализируйте этот диалог с клиентом {lead_name} и извлеките ровно 11 точек данных: === ИСТОРИЯ ДИАЛОГА (ПОЛНЫЙ КОНТЕКСТ) === {conversation_text} === ТЕКУЩИЙ АНАЛИЗ === - Обнаруженный психотип: {psychotype} - Рассчитанный Heat Score: {heat_score}/100 === ЗАДАЧА ИЗВЛЕЧЕНИЯ ДАННЫХ === **КРИТИЧЕСКИ ВАЖНО: ВСЕ ПОЛЯ ДОЛЖНЫ БЫТЬ НА РУССКОМ ЯЗЫКЕ!** На основе ПОЛНОГО контекста диалога выше (включая сообщения от USER, AI, и MANAGER), извлеките эти 11 полей: **ЖЁСТКИЕ ДАННЫЕ (Бизнес-квалификация):** 1. intent - Что клиент хочет достичь или купить? (НА РУССКОМ, используйте ИНФЕРЕНС если явно не сказано) 2. budget - Финансовые возможности, упомянутые или подразумеваемые (НА РУССКОМ, ИНФЕРЬТЕ категорию из контекста: "Низкий"/"Средний"/"Премиум" если точная сумма неизвестна) 3. timeline - Когда ему это нужно? Уровень срочности (НА РУССКОМ, ИНФЕРЬТЕ из тона: "Срочно"/"В течение месяца"/"Долгосрочно") 4. authority - Он принимает решение сам? Нужно ли одобрение? (НА РУССКОМ, ИНФЕРЬТЕ из должности/контекста) **МЯГКИЕ ДАННЫЕ (Психология и Поведение):** 5. pain_points - Перечислите 2-5 конкретных проблем, которые он хочет решить (НА РУССКОМ, массив строк, **ТОЛЬКО из РЕАЛЬНЫХ слов клиента**. Если клиент НЕ упомянул проблему → запишите ["Будет уточнено"]) 6. psychotype - Подтвердите или уточните DISC профиль: Доминантный/Влиятельный/Стабильный/Добросовестный/Неизвестен 7. heat_score - Скорректируйте оценку 0-100 на основе вовлечённости, срочности, возражений **СТРАТЕГИЯ (Рекомендации ИИ):** 8. objections - Какие барьеры или опасения мешают продаже? (НА РУССКОМ, массив строк, **ТОЛЬКО если клиент ДЕЙСТВИТЕЛЬНО возражал**. Если возражений НЕТ → запишите ["Не обнаружено"]) 9. hidden_signals - Что клиент НЕ говорит напрямую? Читайте между строк (НА РУССКОМ, **ИНФЕРЕНС здесь РАЗРЕШЕН**) 10. recommendation - Что должен сделать менеджер по продажам ДАЛЕЕ? Будьте конкретны (НА РУССКОМ) 11. draft_reply - Напишите профессиональный ответ для продолжения диалога (НА РУССКОМ, адаптируйте к психотипу) **CONFIDENCE SCORES (0.0-1.0):** Для каждого поля (intent, budget, timeline, authority, psychotype) укажите уверенность: - **1.0** = Абсолютно уверен (клиент четко указал) - **0.7-0.9** = Высокая уверенность (сильные косвенные признаки) - **0.4-0.6** = Средняя уверенность (слабые признаки или предположение) - **0.1-0.3** = Низкая уверенность (очень слабые данные) - **0.0** = Нет данных вообще Примеры: - Клиент: "Мой бюджет $5000" → budget_confidence: 1.0 - Клиент: "Цена важна, но готов платить за качество" → budget_confidence: 0.6 - Нет упоминания бюджета → budget_confidence: 0.2 **ОБЯЗАТЕЛЬНЫЕ ПРАВИЛА:** - **pain_points:** ТОЛЬКО из РЕАЛЬНЫХ слов клиента! Если нет данных → ["Будет уточнено"] - **objections:** ТОЛЬКО если клиент ДЕЙСТВИТЕЛЬНО возражал! Если нет → ["Не обнаружено"] - **hidden_signals:** Здесь ИНФЕРЕНС РАЗРЕШЕН (например: клиент пишет коротко → возможно не заинтересован) - Будьте конкретны, не используйте общие фразы - draft_reply должен соответствовать психотипу (D=прямой, I=дружелюбный, S=поддерживающий, C=детальный) - Используйте контекст бизнеса для персонализации рекомендаций - **НИКОГДА не используйте английский язык ни в одном поле** - **ВСЕ массивы (pain_points, objections) должны содержать ТОЛЬКО русский текст** """ try: # Use new google.genai SDK with JSON response schema summary_config = types.GenerateContentConfig( temperature=0.1, max_output_tokens=4096, response_mime_type="application/json", response_schema=AISummary ) # Run in executor to avoid blocking loop = asyncio.get_event_loop() response = await loop.run_in_executor( None, lambda: self.client.models.generate_content( model=self.model_name, contents=prompt, config=summary_config ) ) import json summary_data = json.loads(response.text) # Validate with Pydantic (will apply defaults for missing fields) validated_summary = AISummary(**summary_data) return validated_summary.model_dump() except Exception as e: logger.error(f"❌ Gemini API failed for summary generation: {str(e)}", exc_info=True) # SMART FALLBACK: Extract basic info from messages instead of generic placeholders fallback_summary = self._generate_basic_summary( messages=messages or [], lead_name=lead_name, psychotype=psychotype, heat_score=heat_score ) logger.warning( f"⚠️ Using fallback summary for lead (Gemini unavailable). " f"Score: {fallback_summary.get('heat_score')}" ) return fallback_summary def _generate_basic_summary( self, messages: List[Any], lead_name: str, psychotype: str, heat_score: int ) -> dict: """ Generate basic summary without Gemini (fallback). Uses simple heuristics to extract info from messages. """ # Extract conversation text user_messages = [m.content for m in messages if m.sender_type == 'user'] conversation_text = " ".join(user_messages).lower() # Simple keyword detection has_price_question = any(word in conversation_text for word in ['цена', 'стоимость', 'сколько', 'price']) has_timeline = any(word in conversation_text for word in ['когда', 'срок', 'быстро', 'срочно']) has_contact = any(word in conversation_text for word in ['телефон', 'почта', 'email', 'связаться']) # Estimate engagement message_count = len(user_messages) avg_length = sum(len(m) for m in user_messages) / max(message_count, 1) # Adjust heat based on engagement if message_count >= 5 and avg_length > 50: heat_score = min(heat_score + 10, 100) elif message_count <= 2 and avg_length < 20: heat_score = max(heat_score - 10, 0) fallback = AISummary( intent="Интерес к продукту/услуге (требуется уточнение)" if message_count > 1 else "Первый контакт", budget="Обсуждается" if has_price_question else "Не обсуждалось", timeline="Есть временные рамки" if has_timeline else "Не обсуждалось", authority="Контакт установлен" if has_contact else "Требуется выявить", pain_points=["Анализ Gemini недоступен - требуется ручная проверка"], psychotype=psychotype or "Unknown", heat_score=max(0, min(100, heat_score)), objections=["Gemini недоступен"] if message_count > 0 else [], hidden_signals="Анализ недоступен (Gemini API error)", recommendation=f"Проверьте диалог вручную. Сообщений: {message_count}", draft_reply=f"Здравствуйте! Чем могу помочь?" ) return fallback.model_dump() async def transcribe_audio(self, audio_bytes: bytes, mime_type: str = "audio/mp3") -> str: """ Transcribe audio using Gemini's multimodal capabilities. """ try: # Run in executor to avoid blocking loop = asyncio.get_event_loop() prompt = "Transcribe this audio exactly as spoken in its original language. Do not translate. Return only the text." # Create file data object # Note: For small audio (< 20MB), we can pass bytes directly via parts response = await loop.run_in_executor( None, lambda: self.model.generate_content( [ prompt, {"mime_type": mime_type, "data": audio_bytes} ] ) ) return response.text.strip() except Exception as e: logger.error(f"Audio transcription failed: {e}", exc_info=True) return "[Audio Transcription Failed]" @lru_cache() def get_gemini_client() -> GoogleGeminiClient: """Get singleton Gemini client instance.""" return GoogleGeminiClient()