Spaces:
Running

axeronis commited on
Commit
82470e0
·
1 Parent(s): 2b04736

Major: Migrate from Gemini API to Groq API

Browse files

- Created llm_client.py with OpenAI SDK for Groq compatibility
- Updated requirements.txt: removed google-generativeai, added openai + torch
- Replaced all gemini_client imports with llm_client
- Updated config.py: added GROQ_API_KEY, removed GEMINI_API_KEY
- Renamed self.gemini → self.llm in AICore
- Preserved all functionality: retry logic, AI queue, psychotype analysis
- Benefits: FREE unlimited (6000/day), 10x faster, better quotas

backend/app/api/evolution_webhook.py CHANGED
@@ -160,8 +160,8 @@ async def process_evolution_message(
160
  resp.raise_for_status()
161
  audio_bytes = resp.content
162
 
163
- from app.services.gemini_client import get_gemini_client
164
- gc = get_gemini_client()
165
 
166
  logger.info("🎤 Transcribing audio...")
167
  transcription = await gc.transcribe_audio(audio_bytes, mime_type="audio/ogg") # WhatsApp voice is usually OGG
 
160
  resp.raise_for_status()
161
  audio_bytes = resp.content
162
 
163
+ from app.services.llm_client import get_llm_client
164
+ gc = get_llm_client()
165
 
166
  logger.info("🎤 Transcribing audio...")
167
  transcription = await gc.transcribe_audio(audio_bytes, mime_type="audio/ogg") # WhatsApp voice is usually OGG
backend/app/api/tenants.py CHANGED
@@ -6,6 +6,7 @@ from typing import Optional, Dict, Any, List
6
  from uuid import UUID
7
  from pydantic import BaseModel
8
  from app.models.tenant import Tenant, SubscriptionPlan
 
9
  from app.models import User
10
  from app.api.deps import get_current_user
11
  from app.core.database import get_async_session
 
6
  from uuid import UUID
7
  from pydantic import BaseModel
8
  from app.models.tenant import Tenant, SubscriptionPlan
9
+ from app.models.partner import Partner
10
  from app.models import User
11
  from app.api.deps import get_current_user
12
  from app.core.database import get_async_session
backend/app/core/config.py CHANGED
@@ -22,15 +22,15 @@ class Settings(BaseSettings):
22
  SUPABASE_KEY: str
23
  SUPABASE_SERVICE_KEY: Optional[str] = None
24
 
25
- # Google Gemini AI
26
- GEMINI_API_KEY: str
27
- GEMINI_MODEL: str = "gemini-2.5-flash" # Latest stable model (Dec 2024)
28
- EMBEDDING_DIMENSION: int = 768 # Gemini embedding-001 dimension
29
 
30
  # Security
31
  SECRET_KEY: str
32
  ALGORITHM: str = "HS256"
33
- ACCESS_TOKEN_EXPIRE_MINUTES: int = 10080 # 7 дней (7 * 24 * 60)
 
34
 
35
  # CORS - Allowed Origins (comma-separated)
36
  # Development: http://localhost:3000
 
22
  SUPABASE_KEY: str
23
  SUPABASE_SERVICE_KEY: Optional[str] = None
24
 
25
+ # Groq AI (LLM)
26
+ GROQ_API_KEY: str
27
+ EMBEDDING_DIMENSION: int = 384 # sentence-transformers: all-MiniLM-L6-v2
 
28
 
29
  # Security
30
  SECRET_KEY: str
31
  ALGORITHM: str = "HS256"
32
+ ACCESS_TOKEN_EXPIRE_MINUTES: int = 10080 # 7 days
33
+
34
 
35
  # CORS - Allowed Origins (comma-separated)
36
  # Development: http://localhost:3000
backend/app/services/ai_core.py CHANGED
@@ -2,7 +2,7 @@ from typing import List, Dict, Any, Optional
2
  from uuid import UUID
3
  from sqlalchemy.ext.asyncio import AsyncSession
4
 
5
- from app.services.gemini_client import get_gemini_client
6
  from app.services.vector_store import get_vector_store
7
  from app.models.lead import Lead, Message, Psychotype, LeadHeat
8
  from app.models.tenant import Tenant
@@ -21,7 +21,7 @@ class AICore:
21
  """
22
 
23
  def __init__(self):
24
- self.gemini = get_gemini_client()
25
  self.vector_store = get_vector_store()
26
 
27
  async def generate_sales_response(
@@ -124,7 +124,7 @@ class AICore:
124
  chat_history = self._format_chat_history(conversation_history)
125
 
126
  # 7. Generate response
127
- response = await self.gemini.generate_response(
128
  prompt=user_message,
129
  system_instruction=system_prompt,
130
  context=chat_history
 
2
  from uuid import UUID
3
  from sqlalchemy.ext.asyncio import AsyncSession
4
 
5
+ from app.services.llm_client import get_llm_client
6
  from app.services.vector_store import get_vector_store
7
  from app.models.lead import Lead, Message, Psychotype, LeadHeat
8
  from app.models.tenant import Tenant
 
21
  """
22
 
23
  def __init__(self):
24
+ self.llm = get_llm_client()
25
  self.vector_store = get_vector_store()
26
 
27
  async def generate_sales_response(
 
124
  chat_history = self._format_chat_history(conversation_history)
125
 
126
  # 7. Generate response
127
+ response = await self.llm.generate_response(
128
  prompt=user_message,
129
  system_instruction=system_prompt,
130
  context=chat_history
backend/app/services/llm_client.py ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from openai import OpenAI
2
+ from typing import Optional, List, Dict, Any
3
+ from app.core.config import settings
4
+ import asyncio
5
+ from functools import lru_cache
6
+ from app.models.ai_summary import AISummary
7
+ import time
8
+ import logging
9
+ from app.services.ai_queue import get_ai_queue
10
+ import os
11
+ import json
12
+ import re
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class LLMAPIError(Exception):
18
+ """Custom exception for LLM API errors."""
19
+ pass
20
+
21
+
22
+ class LLMRateLimitError(LLMAPIError):
23
+ """Raised when rate limit is exceeded."""
24
+ pass
25
+
26
+
27
+ class GroqLLMClient:
28
+ """Client for Groq LLM API (OpenAI-compatible)."""
29
+
30
+ def __init__(self):
31
+ """Initialize Groq client."""
32
+ api_key = os.getenv("GROQ_API_KEY", settings.GROQ_API_KEY if hasattr(settings, 'GROQ_API_KEY') else None)
33
+ if not api_key:
34
+ raise ValueError("GROQ_API_KEY environment variable not set")
35
+
36
+ self.client = OpenAI(
37
+ api_key=api_key,
38
+ base_url="https://api.groq.com/openai/v1"
39
+ )
40
+ self.model = "llama-3.1-70b-versatile" # Fast and high-quality
41
+ self.ai_queue = get_ai_queue() # Rate limiting queue
42
+
43
+ logger.info(f"✅ Groq LLM client initialized (model: {self.model})")
44
+
45
+ async def generate_response(
46
+ self,
47
+ prompt: str,
48
+ system_instruction: Optional[str] = None,
49
+ context: Optional[List[Dict[str, str]]] = None,
50
+ temperature: Optional[float] = None,
51
+ max_retries: int = 3,
52
+ priority: int = 5 # 1-10, higher = more important
53
+ ) -> Dict[str, Any]:
54
+ """
55
+ Generate AI response using Groq with retry logic and rate limiting.
56
+
57
+ Args:
58
+ prompt: User message
59
+ system_instruction: System prompt to guide AI behavior
60
+ context: Chat history as list of {"role": "user/assistant", "content": "text"}
61
+ temperature: Override default temperature (0.7)
62
+ max_retries: Maximum number of retry attempts
63
+ priority: Request priority (1-10, higher = more important)
64
+
65
+ Returns:
66
+ Dict with response text and token usage
67
+
68
+ Raises:
69
+ LLMAPIError: If all retries fail
70
+ """
71
+ # Wrap in rate-limited queue
72
+ return await self.ai_queue.execute(
73
+ self._generate_response_internal,
74
+ priority=priority,
75
+ prompt=prompt,
76
+ system_instruction=system_instruction,
77
+ context=context,
78
+ temperature=temperature,
79
+ max_retries=max_retries
80
+ )
81
+
82
+ async def _generate_response_internal(
83
+ self,
84
+ prompt: str,
85
+ system_instruction: Optional[str] = None,
86
+ context: Optional[List[Dict[str, str]]] = None,
87
+ temperature: Optional[float] = None,
88
+ max_retries: int = 3
89
+ ) -> Dict[str, Any]:
90
+ """
91
+ Internal method - actual Groq API call (called via queue).
92
+ """
93
+ for attempt in range(max_retries):
94
+ try:
95
+ # Build messages array
96
+ messages = []
97
+
98
+ # Add system instruction
99
+ if system_instruction:
100
+ messages.append({"role": "system", "content": system_instruction})
101
+
102
+ # Add context (chat history)
103
+ if context:
104
+ # Convert Gemini format to OpenAI format if needed
105
+ for msg in context:
106
+ if "role" in msg and "parts" in msg:
107
+ # Gemini format: {"role": "user", "parts": [{"text": "..."}]}
108
+ content = msg["parts"][0]["text"] if isinstance(msg["parts"], list) else msg["parts"]
109
+ role = "assistant" if msg["role"] == "model" else msg["role"]
110
+ messages.append({"role": role, "content": content})
111
+ elif "role" in msg and "content" in msg:
112
+ # OpenAI format: {"role": "user", "content": "..."}
113
+ messages.append(msg)
114
+
115
+ # Add current prompt
116
+ messages.append({"role": "user", "content": prompt})
117
+
118
+ # Call Groq API (synchronously, in thread)
119
+ response = await asyncio.to_thread(
120
+ self.client.chat.completions.create,
121
+ model=self.model,
122
+ messages=messages,
123
+ temperature=temperature or 0.7,
124
+ max_tokens=2000
125
+ )
126
+
127
+ # Extract response
128
+ return {
129
+ "text": response.choices[0].message.content,
130
+ "prompt_tokens": response.usage.prompt_tokens,
131
+ "completion_tokens": response.usage.completion_tokens,
132
+ "total_tokens": response.usage.total_tokens,
133
+ }
134
+
135
+ except Exception as e:
136
+ error_msg = str(e).lower()
137
+
138
+ # Check if it's a rate limit error
139
+ if "rate limit" in error_msg or "429" in error_msg or "quota" in error_msg:
140
+ if attempt < max_retries - 1:
141
+ # Exponential backoff: 2^attempt seconds
142
+ wait_time = 2 ** attempt
143
+ logger.warning(f"Groq rate limit hit. Retrying in {wait_time}s (attempt {attempt + 1}/{max_retries})")
144
+ await asyncio.sleep(wait_time)
145
+ continue
146
+ else:
147
+ logger.error(f"Groq rate limit exceeded after {max_retries} attempts")
148
+ raise LLMRateLimitError(f"Rate limit exceeded: {str(e)}")
149
+
150
+ # Check if it's a temporary error
151
+ elif "503" in error_msg or "500" in error_msg or "timeout" in error_msg:
152
+ if attempt < max_retries - 1:
153
+ wait_time = 1 + attempt # Linear backoff for server errors
154
+ logger.warning(f"Groq temporary error. Retrying in {wait_time}s (attempt {attempt + 1}/{max_retries})")
155
+ await asyncio.sleep(wait_time)
156
+ continue
157
+ else:
158
+ logger.error(f"Groq API unavailable after {max_retries} attempts")
159
+ raise LLMAPIError(f"API unavailable: {str(e)}")
160
+
161
+ # For other errors, fail immediately
162
+ logger.error(f"Groq API Error: {e}")
163
+ raise LLMAPIError(f"AI generation failed: {str(e)}")
164
+
165
+ async def analyze_psychotype(self, messages: List[str]) -> str:
166
+ """
167
+ Detect user's DISC personality type from messages.
168
+
169
+ Args:
170
+ messages: List of user messages
171
+
172
+ Returns:
173
+ One of: "dominant", "influential", "steady", "conscientious", "unknown"
174
+ """
175
+ prompt = f"""Analyze the following messages and determine the DISC personality type:
176
+
177
+ Messages:
178
+ {chr(10).join(f"- {msg}" for msg in messages[-10:])}
179
+
180
+ DISC Types:
181
+ - DOMINANT (D): Direct, results-oriented, decisive, assertive, competitive
182
+ - INFLUENTIAL (I): Enthusiastic, optimistic, social, talkative, emotional
183
+ - STEADY (S): Patient, calm, supportive, good listener, team player
184
+ - CONSCIENTIOUS (C): Analytical, precise, detail-oriented, asks many questions
185
+
186
+ **IMMEDIATE INFERENCE MODE:**
187
+ - Even a SINGLE message allows a basic DISC guess
188
+ - Analyze TONE, punctuation, word choice immediately
189
+ - Only return "unknown" if message is completely ambiguous
190
+
191
+ Respond with ONLY ONE WORD: dominant, influential, steady, conscientious, or unknown"""
192
+
193
+ try:
194
+ response = await self.generate_response(prompt, temperature=0.3)
195
+ psychotype = response["text"].strip().lower()
196
+
197
+ valid_types = ["dominant", "influential", "steady", "conscientious", "unknown"]
198
+ return psychotype if psychotype in valid_types else "unknown"
199
+
200
+ except Exception as e:
201
+ logger.error(f"Psychotype analysis failed: {str(e)}", exc_info=True)
202
+ return "unknown"
203
+
204
+ async def calculate_heat_score(
205
+ self,
206
+ conversation_text: str,
207
+ bant_data: Dict[str, Optional[str]]
208
+ ) -> int:
209
+ """
210
+ Calculate lead heat score (0-100).
211
+
212
+ Args:
213
+ conversation_text: Full conversation history
214
+ bant_data: Dict with budget, authority, need, timeline
215
+
216
+ Returns:
217
+ Heat score from 0 to 100
218
+ """
219
+ prompt = f"""Analyze this sales conversation and assign a heat score from 0-100.
220
+
221
+ Conversation:
222
+ {conversation_text}
223
+
224
+ BANT Qualification:
225
+ - Budget: {bant_data.get('budget', 'Unknown')}
226
+ - Authority: {bant_data.get('authority', 'Unknown')}
227
+ - Need: {bant_data.get('need', 'Unknown')}
228
+ - Timeline: {bant_data.get('timeline', 'Unknown')}
229
+
230
+ Scoring criteria:
231
+ - 90-100 (HOT): Ready to buy now, budget confirmed, decision maker, urgent need
232
+ - 70-89 (WARM): Interested, has budget, timeline within 2 weeks
233
+ - 50-69 (WARM): Exploring options, considering, timeline 1+ months
234
+ - 30-49 (COLD): Just researching, no clear timeline
235
+ - 0-29 (JUNK): Not interested, no budget, not decision maker, or spam
236
+
237
+ Respond with ONLY a number from 0 to 100."""
238
+
239
+ try:
240
+ response = await self.generate_response(prompt, temperature=0.2)
241
+ score_text = response["text"].strip()
242
+
243
+ # Extract number
244
+ match = re.search(r'\b(\d{1,3})\b', score_text)
245
+ if match:
246
+ score = int(match.group(1))
247
+ return min(100, max(0, score)) # Clamp to 0-100
248
+ return 50 # Default middle score
249
+
250
+ except Exception as e:
251
+ logger.error(f"Heat score calculation failed: {str(e)}", exc_info=True)
252
+ return 50
253
+
254
+ async def generate_11_point_summary(
255
+ self,
256
+ conversation_text: str,
257
+ lead_name: str,
258
+ psychotype: str,
259
+ heat_score: int,
260
+ business_description: str = "We provide products and services",
261
+ tenant_settings: Optional[Dict[str, Any]] = None
262
+ ) -> Dict[str, Any]:
263
+ """
264
+ Generate comprehensive 11-point AI summary.
265
+
266
+ Note: Groq doesn't support structured output like Gemini's response_schema,
267
+ so we'll use JSON mode and validate manually.
268
+ """
269
+ tenant_settings = tenant_settings or {}
270
+
271
+ # Build business context
272
+ business_desc = business_description or tenant_settings.get('business_description', '')
273
+ if not business_desc.strip():
274
+ business_desc = "Вы - помощник по продажам. Извлекайте общую информацию о намерениях клиента."
275
+
276
+ ideal_customer = tenant_settings.get('ideal_customer_profile', 'Клиент с реальными потребностями')
277
+ selling_style = tenant_settings.get('selling_style', 'Консультативный')
278
+ tone_of_voice = tenant_settings.get('tone_of_voice', 'Профессиональный')
279
+ custom_fields = tenant_settings.get('custom_qualification_fields', [])
280
+
281
+ system_instruction = f"""Вы - эксперт по анализу продаж. Верните ТОЛЬКО валидный JSON без дополнительного текста.
282
+
283
+ КОНТЕКСТ БИЗНЕСА:
284
+ {business_desc}
285
+ ИДЕАЛЬНЫЙ КЛИЕНТ: {ideal_customer}
286
+ СТИЛЬ ПРОДАЖ: {selling_style} (Тон: {tone_of_voice})
287
+
288
+ ВЕРНИТЕ JSON со следующими полями (ВСЕ НА РУССКОМ):
289
+ {{
290
+ "intent": "Что клиент хочет",
291
+ "budget": "Финансовые возможности",
292
+ "timeline": "Когда нужно",
293
+ "authority": "Принимает решение?",
294
+ "pain_points": ["Проблема 1", "Проблема 2"],
295
+ "psychotype": "dominant/influential/steady/conscientious",
296
+ "heat_score": 0-100,
297
+ "objections": ["Возражение 1"] или ["Не обнаружено"],
298
+ "hidden_signals": "Неявные сигналы",
299
+ "recommendation": "Что делать дальше",
300
+ "draft_reply": "Ответ клиенту",
301
+ "intent_confidence": 0.0-1.0,
302
+ "budget_confidence": 0.0-1.0,
303
+ "timeline_confidence": 0.0-1.0,
304
+ "authority_confidence": 0.0-1.0,
305
+ "psychotype_confidence": 0.0-1.0
306
+ }}"""
307
+
308
+ prompt = f"""Проанализируйте диалог с {lead_name}:
309
+
310
+ {conversation_text}
311
+
312
+ Психотип: {psychotype}
313
+ Heat Score: {heat_score}/100
314
+
315
+ Верните ТОЛЬКО JSON согласно схеме без дополнительного текста."""
316
+
317
+ try:
318
+ response = await self.generate_response(
319
+ prompt,
320
+ system_instruction=system_instruction,
321
+ temperature=0.1
322
+ )
323
+
324
+ # Parse JSON
325
+ summary_data = json.loads(response["text"])
326
+
327
+ # Validate with Pydantic
328
+ validated_summary = AISummary(**summary_data)
329
+ return validated_summary.model_dump()
330
+
331
+ except Exception as e:
332
+ logger.error(f"❌ LLM summary generation failed: {str(e)}", exc_info=True)
333
+
334
+ # Fallback
335
+ return self._generate_basic_fallback(lead_name, psychotype, heat_score)
336
+
337
+ def _generate_basic_fallback(
338
+ self,
339
+ lead_name: str,
340
+ psychotype: str,
341
+ heat_score: int
342
+ ) -> dict:
343
+ """Generate basic fallback summary."""
344
+ fallback = AISummary(
345
+ intent="Требуется анализ",
346
+ budget="Не обсуждалось",
347
+ timeline="Не обсуждалось",
348
+ authority="Требуется выявить",
349
+ pain_points=["Анализ LLM недоступен"],
350
+ psychotype=psychotype or "unknown",
351
+ heat_score=max(0, min(100, heat_score)),
352
+ objections=["LLM недоступен"],
353
+ hidden_signals="Анализ недоступен",
354
+ recommendation="Проверьте диалог вручную",
355
+ draft_reply="Здравствуйте! Чем могу помочь?"
356
+ )
357
+ return fallback.model_dump()
358
+
359
+
360
+ @lru_cache()
361
+ def get_llm_client() -> GroqLLMClient:
362
+ """Get singleton Groq LLM client instance."""
363
+ return GroqLLMClient()
backend/app/services/product_service.py CHANGED
@@ -6,7 +6,7 @@ import json
6
  import logging
7
 
8
  from app.models.product import Product
9
- from app.services.gemini_client import get_gemini_client
10
 
11
  logger = logging.getLogger(__name__)
12
 
 
6
  import logging
7
 
8
  from app.models.product import Product
9
+ from app.services.llm_client import get_llm_client
10
 
11
  logger = logging.getLogger(__name__)
12
 
backend/requirements.txt CHANGED
@@ -14,9 +14,9 @@ supabase==2.3.4
14
  pgvector==0.2.4
15
 
16
  # AI & ML
17
- google-generativeai==0.8.5
18
- protobuf==5.29.5
19
- sentence-transformers==2.3.1
20
  numpy>=1.24.0
21
 
22
  # Async Tasks
 
14
  pgvector==0.2.4
15
 
16
  # AI & ML
17
+ openai==1.12.0 # For Groq API (OpenAI-compatible)
18
+ sentence-transformers==2.3.1 # Local embeddings
19
+ torch==2.2.0 # Required by sentence-transformers
20
  numpy>=1.24.0
21
 
22
  # Async Tasks