Spaces:
Running
Running
axeronis commited on
Commit ·
bbf53ef
1
Parent(s): 49dcf8e
perf: optimize system for high concurrency (100+ dialogues)
Browse files
backend/app/core/database.py
CHANGED
|
@@ -35,9 +35,9 @@ async_engine = create_async_engine(
|
|
| 35 |
echo=settings.DEBUG,
|
| 36 |
future=True,
|
| 37 |
pool_pre_ping=True,
|
| 38 |
-
pool_size=
|
| 39 |
-
max_overflow=
|
| 40 |
-
pool_timeout=
|
| 41 |
pool_recycle=1800, # Recycle connections every 30 min
|
| 42 |
connect_args={
|
| 43 |
"prepare_threshold": 0, # Disable prepared statements for pgbouncer/transaction pooler
|
|
|
|
| 35 |
echo=settings.DEBUG,
|
| 36 |
future=True,
|
| 37 |
pool_pre_ping=True,
|
| 38 |
+
pool_size=50, # Scaled for 100+ concurrent dialogues
|
| 39 |
+
max_overflow=50, # Room for burst traffic
|
| 40 |
+
pool_timeout=45, # Increased timeout for high load
|
| 41 |
pool_recycle=1800, # Recycle connections every 30 min
|
| 42 |
connect_args={
|
| 43 |
"prepare_threshold": 0, # Disable prepared statements for pgbouncer/transaction pooler
|
backend/app/services/ai_core/response_generator.py
CHANGED
|
@@ -117,52 +117,10 @@ async def generate_sales_response_impl(
|
|
| 117 |
|
| 118 |
ai_message_count = len([m for m in conversation_history if get_sender_type(m) == 'ai']) if conversation_history else 0
|
| 119 |
|
| 120 |
-
#
|
| 121 |
-
#
|
| 122 |
user_requested_no_voice = False
|
| 123 |
-
user_requested_voice = False
|
| 124 |
-
|
| 125 |
-
# Get the current user message (last one in history)
|
| 126 |
-
current_user_msg = user_message.strip() if user_message else ""
|
| 127 |
-
|
| 128 |
-
# DEBUG: Log what we're checking
|
| 129 |
-
logger.info(f"� VOICE CHECK: Analyzing current message: '{current_user_msg[:100]}...'")
|
| 130 |
-
|
| 131 |
-
# SMART LLM CHECK: Semantic analysis for voice preference
|
| 132 |
-
if current_user_msg and len(current_user_msg) > 2:
|
| 133 |
-
try:
|
| 134 |
-
voice_analysis = await ai_core.llm.generate_response(
|
| 135 |
-
prompt=f"""Analyze this user message. Does the user want a VOICE/AUDIO response, or do they prefer TEXT?
|
| 136 |
-
|
| 137 |
-
User's message: "{current_user_msg}"
|
| 138 |
-
|
| 139 |
-
Determine the user's preference:
|
| 140 |
-
- WANT_VOICE: User explicitly wants voice (e.g., "отправь голосовое", "озвучь", "голосом", "send voice", asking to hear something)
|
| 141 |
-
- NO_VOICE: User explicitly doesn't want voice (e.g., "пиши текстом", "не присылай голос", "text only", complains about audio)
|
| 142 |
-
- NEUTRAL: No clear preference about voice vs text (normal conversation)
|
| 143 |
-
|
| 144 |
-
Answer with ONE word only: WANT_VOICE, NO_VOICE, or NEUTRAL""",
|
| 145 |
-
system_instruction="Output only ONE word: WANT_VOICE, NO_VOICE, or NEUTRAL. Be strict - only detect EXPLICIT requests.",
|
| 146 |
-
context=None,
|
| 147 |
-
chat_history=[]
|
| 148 |
-
)
|
| 149 |
-
|
| 150 |
-
llm_result = voice_analysis["text"].strip().upper()
|
| 151 |
-
if "NO_VOICE" in llm_result:
|
| 152 |
-
user_requested_no_voice = True
|
| 153 |
-
logger.info(f"🧠 LLM: User wants NO VOICE")
|
| 154 |
-
elif "WANT_VOICE" in llm_result:
|
| 155 |
-
user_requested_voice = True
|
| 156 |
-
logger.info(f"🧠 LLM: User WANTS VOICE")
|
| 157 |
-
else:
|
| 158 |
-
logger.info(f"🧠 LLM: NEUTRAL (no voice preference)")
|
| 159 |
-
except Exception as e:
|
| 160 |
-
logger.warning(f"LLM voice preference check failed: {e}")
|
| 161 |
-
|
| 162 |
-
if user_requested_voice:
|
| 163 |
-
logger.info(f"📢 FINAL voice preference: YES (user requested)")
|
| 164 |
-
elif user_requested_no_voice:
|
| 165 |
-
logger.info(f"📢 FINAL voice preference: NO (user requested)")
|
| 166 |
|
| 167 |
# 4. SYSTEMATIC MEMORY: Extract key facts from AI Summary (prevents amnesia)
|
| 168 |
conversation_facts = ""
|
|
@@ -261,24 +219,17 @@ Last Interaction: {last_msg_time_str}
|
|
| 261 |
Ты можешь отправлять ГОЛОСОВЫЕ сообщения, добавив тег [SEND_VOICE] в конец ответа.
|
| 262 |
Голос создаёт ЭМОЦИОНАЛЬНУЮ СВЯЗЬ и показывает что ты живой человек.
|
| 263 |
|
| 264 |
-
⚠️
|
| 265 |
-
|
| 266 |
-
|
|
|
|
| 267 |
|
| 268 |
-
ИСПОЛЬЗ
|
| 269 |
-
•
|
| 270 |
-
•
|
| 271 |
-
• Н
|
| 272 |
-
• Это КЛЮЧЕВОЙ МОМЕНТ сделки (закрытие, финальное предложение)
|
| 273 |
-
• Чувствуешь НЕГАТИВНЫЕ ЭМОЦИИ клиента (расстроен, разочарован)
|
| 274 |
|
| 275 |
-
|
| 276 |
-
• Клиент ПРОСИЛ писать текстом / не отправлять голосовые / "пиши" / "не надо голосовых" / "текстом"
|
| 277 |
-
• Уже отправлял голос в последних 4 сообщениях (Message Count > 1)
|
| 278 |
-
• Простой информационный ответ (цена, адрес, 1-2 предложения)
|
| 279 |
-
• Короткий уточняющий вопрос
|
| 280 |
-
|
| 281 |
-
Формат: Добавь [SEND_VOICE] в САМЫЙ КОНЕЦ сообщения.
|
| 282 |
Стиль: Пиши разговорно, как говоришь вслух - с паузами (...), эмоциями.
|
| 283 |
"""
|
| 284 |
|
|
@@ -315,8 +266,20 @@ Last Interaction: {last_msg_time_str}
|
|
| 315 |
media_parts=media_parts
|
| 316 |
)
|
| 317 |
|
| 318 |
-
# POST-PROCESS:
|
| 319 |
response_text = response["text"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 320 |
if user_requested_no_voice and "[SEND_VOICE]" in response_text:
|
| 321 |
logger.info("🚫 Removing [SEND_VOICE] tag because user requested no voice messages")
|
| 322 |
response_text = response_text.replace("[SEND_VOICE]", "").strip()
|
|
|
|
| 117 |
|
| 118 |
ai_message_count = len([m for m in conversation_history if get_sender_type(m) == 'ai']) if conversation_history else 0
|
| 119 |
|
| 120 |
+
# VOICE PREFERENCE DETECTION (Integrated into main prompt)
|
| 121 |
+
# We now handle this by instructing the AI to detect it alongside the response
|
| 122 |
user_requested_no_voice = False
|
| 123 |
+
user_requested_voice = False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
|
| 125 |
# 4. SYSTEMATIC MEMORY: Extract key facts from AI Summary (prevents amnesia)
|
| 126 |
conversation_facts = ""
|
|
|
|
| 219 |
Ты можешь отправлять ГОЛОСОВЫЕ сообщения, добавив тег [SEND_VOICE] в конец ответа.
|
| 220 |
Голос создаёт ЭМОЦИОНАЛЬНУЮ СВЯЗЬ и показывает что ты живой человек.
|
| 221 |
|
| 222 |
+
⚠️ АНАЛИЗ ПРЕДПОЧТЕНИЙ (КРИТИЧЕСКИ ВАЖНО):
|
| 223 |
+
1. Если клиент просил писать ТЕКСТОМ / не присылать голосовые (или подобное) -> Добавь тег [USER_WANT_TEXT] в конец ответа и НИКОГДА не используй [SEND_VOICE].
|
| 224 |
+
2. Если клиент просит "отправь голосовое / озвучь / хочу услышать" -> Добавь тег [USER_WANTS_VOICE] в конец и ОБЯЗАТЕЛЬНО используй [SEND_VOICE].
|
| 225 |
+
3. Если это обычный диалог -> Не добавляй эти теги, просто реши сам, нужен ли голос.
|
| 226 |
|
| 227 |
+
⚠️ ПРАВИЛА ИСПОЛЬЗОВАНИЯ ГОЛОСА:
|
| 228 |
+
• Максимум 1 раз на 4-5 сообщений! Не спамь!
|
| 229 |
+
• Используй когда: первый ответ (если Voice First = True), нужно убедить, извиниться, или это ключевой момент сделки.
|
| 230 |
+
• НЕ используй когда: ��ростой ответ, уточняющий вопрос, или клиент просил текст.
|
|
|
|
|
|
|
| 231 |
|
| 232 |
+
Формат: Добавь [SEND_VOICE] в САМЫЙ КОНЕЦ сообщения, если решил говорить.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
Стиль: Пиши разговорно, как говоришь вслух - с паузами (...), эмоциями.
|
| 234 |
"""
|
| 235 |
|
|
|
|
| 266 |
media_parts=media_parts
|
| 267 |
)
|
| 268 |
|
| 269 |
+
# POST-PROCESS: Parse internal tags for voice preference
|
| 270 |
response_text = response["text"]
|
| 271 |
+
|
| 272 |
+
if "[USER_WANT_TEXT]" in response_text:
|
| 273 |
+
user_requested_no_voice = True
|
| 274 |
+
response_text = response_text.replace("[USER_WANT_TEXT]", "").strip()
|
| 275 |
+
# Ensure voice tag is removed if AI ignored it
|
| 276 |
+
if "[SEND_VOICE]" in response_text:
|
| 277 |
+
response_text = response_text.replace("[SEND_VOICE]", "").strip()
|
| 278 |
+
|
| 279 |
+
if "[USER_WANTS_VOICE]" in response_text:
|
| 280 |
+
user_requested_voice = True
|
| 281 |
+
response_text = response_text.replace("[USER_WANTS_VOICE]", "").strip()
|
| 282 |
+
|
| 283 |
if user_requested_no_voice and "[SEND_VOICE]" in response_text:
|
| 284 |
logger.info("🚫 Removing [SEND_VOICE] tag because user requested no voice messages")
|
| 285 |
response_text = response_text.replace("[SEND_VOICE]", "").strip()
|
backend/app/services/ai_queue.py
CHANGED
|
@@ -121,8 +121,11 @@ def get_ai_queue() -> AIRequestQueue:
|
|
| 121 |
"""Get global AI request queue."""
|
| 122 |
global _ai_queue
|
| 123 |
if _ai_queue is None:
|
|
|
|
|
|
|
|
|
|
| 124 |
_ai_queue = AIRequestQueue(
|
| 125 |
-
max_requests_per_minute=
|
| 126 |
-
max_concurrent=
|
| 127 |
)
|
| 128 |
return _ai_queue
|
|
|
|
| 121 |
"""Get global AI request queue."""
|
| 122 |
global _ai_queue
|
| 123 |
if _ai_queue is None:
|
| 124 |
+
# PRODUCTION SCALE:
|
| 125 |
+
# Gemini 1.5 Flash (Paid) supports up to 2000 RPM.
|
| 126 |
+
# We set 1000 RPM as a safe limit with 100 concurrent tasks.
|
| 127 |
_ai_queue = AIRequestQueue(
|
| 128 |
+
max_requests_per_minute=1000,
|
| 129 |
+
max_concurrent=100
|
| 130 |
)
|
| 131 |
return _ai_queue
|
backend/app/services/voice_service.py
CHANGED
|
@@ -9,6 +9,7 @@ Includes audio caching to save credits.
|
|
| 9 |
import httpx
|
| 10 |
import logging
|
| 11 |
import hashlib
|
|
|
|
| 12 |
from typing import Optional, Dict
|
| 13 |
from app.core.config import settings
|
| 14 |
|
|
@@ -322,6 +323,8 @@ class VoiceService:
|
|
| 322 |
def __init__(self):
|
| 323 |
self.elevenlabs_api_key = getattr(settings, 'ELEVENLABS_API_KEY', None)
|
| 324 |
self.default_voice = "professional_male"
|
|
|
|
|
|
|
| 325 |
|
| 326 |
if self.elevenlabs_api_key:
|
| 327 |
logger.info(f"✅ ElevenLabs Voice Service initialized (with caching)")
|
|
@@ -394,23 +397,24 @@ class VoiceService:
|
|
| 394 |
if cached_audio:
|
| 395 |
return cached_audio, extracted_items
|
| 396 |
|
| 397 |
-
# Generate new audio
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
|
|
|
| 414 |
|
| 415 |
return audio, extracted_items
|
| 416 |
|
|
|
|
| 9 |
import httpx
|
| 10 |
import logging
|
| 11 |
import hashlib
|
| 12 |
+
import asyncio
|
| 13 |
from typing import Optional, Dict
|
| 14 |
from app.core.config import settings
|
| 15 |
|
|
|
|
| 323 |
def __init__(self):
|
| 324 |
self.elevenlabs_api_key = getattr(settings, 'ELEVENLABS_API_KEY', None)
|
| 325 |
self.default_voice = "professional_male"
|
| 326 |
+
# Concurrency control: prevent hitting ElevenLabs parallel request limits
|
| 327 |
+
self.semaphore = asyncio.Semaphore(15)
|
| 328 |
|
| 329 |
if self.elevenlabs_api_key:
|
| 330 |
logger.info(f"✅ ElevenLabs Voice Service initialized (with caching)")
|
|
|
|
| 397 |
if cached_audio:
|
| 398 |
return cached_audio, extracted_items
|
| 399 |
|
| 400 |
+
# Generate new audio with concurrency limit
|
| 401 |
+
async with self.semaphore:
|
| 402 |
+
audio = None
|
| 403 |
+
|
| 404 |
+
# Try ElevenLabs first
|
| 405 |
+
if self.elevenlabs_api_key:
|
| 406 |
+
try:
|
| 407 |
+
audio = await self._elevenlabs_generate(clean_text, selected_voice)
|
| 408 |
+
except Exception as e:
|
| 409 |
+
logger.warning(f"⚠️ ElevenLabs failed: {e}, falling back to Edge TTS")
|
| 410 |
+
|
| 411 |
+
# Fallback to Edge TTS
|
| 412 |
+
if not audio:
|
| 413 |
+
audio = await self._edge_tts_generate(clean_text, selected_voice)
|
| 414 |
+
|
| 415 |
+
# Store in cache
|
| 416 |
+
if use_cache and audio:
|
| 417 |
+
self._add_to_cache(cache_key, audio)
|
| 418 |
|
| 419 |
return audio, extracted_items
|
| 420 |
|
backend/scripts/verify_scaling.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import asyncio
|
| 3 |
+
import sys
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
# Add project root to sys.path
|
| 7 |
+
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
|
| 8 |
+
|
| 9 |
+
# Mock settings before importing app
|
| 10 |
+
os.environ["DATABASE_URL"] = "postgresql://user:pass@localhost/db"
|
| 11 |
+
os.environ["SUPABASE_URL"] = "https://test.supabase.co"
|
| 12 |
+
os.environ["SUPABASE_KEY"] = "test"
|
| 13 |
+
os.environ["SECRET_KEY"] = "test_secret_key_long_enough_32_chars_"
|
| 14 |
+
os.environ["GROQ_API_KEY"] = "test" * 20
|
| 15 |
+
|
| 16 |
+
from app.services.ai_queue import get_ai_queue
|
| 17 |
+
from app.services.voice_service import voice_service
|
| 18 |
+
|
| 19 |
+
async def test_limits():
|
| 20 |
+
print("--- SCALING CONFIGURATION VERIFICATION ---")
|
| 21 |
+
|
| 22 |
+
# 1. Check AI Queue
|
| 23 |
+
queue = get_ai_queue()
|
| 24 |
+
print(f"AI Queue Max RPM: {queue.max_rpm}")
|
| 25 |
+
print(f"AI Queue Max Concurrent: {queue.max_concurrent}")
|
| 26 |
+
|
| 27 |
+
# 2. Check Voice Semaphore
|
| 28 |
+
print(f"Voice Semaphore Limit: {voice_service.semaphore._value}")
|
| 29 |
+
|
| 30 |
+
# 3. Check DB config from database.py manually since we can't easily check pool size without engine
|
| 31 |
+
from app.core.database import async_engine
|
| 32 |
+
print(f"DB Pool Size Config: {async_engine.pool.size()}")
|
| 33 |
+
|
| 34 |
+
print("\n✅ Scaling configurations verified.")
|
| 35 |
+
|
| 36 |
+
if __name__ == "__main__":
|
| 37 |
+
asyncio.run(test_limits())
|