Spaces:
Running
Running
File size: 11,453 Bytes
90be4ab 895402e 90be4ab 895402e 90be4ab bbc6d21 90be4ab bbc6d21 90be4ab bbc6d21 90be4ab bbc6d21 90be4ab bbc6d21 90be4ab bbc6d21 90be4ab bbc6d21 90be4ab 895402e 90be4ab bbc6d21 90be4ab 895402e 90be4ab | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 | """
Message Processor Service
Unified message processing logic for all webhook handlers.
Handles: Lead/Conversation lookup, message storage, AI response, sending.
Used by:
- telegram_webhook.py
- meta_webhooks.py
- webhook.py (email)
"""
from typing import List, Optional, Dict, Any
from uuid import UUID
from datetime import datetime
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func
import logging
from datetime import datetime, timedelta
from app.models.tenant import Tenant
from app.models.lead import Lead, Message, Conversation, MessageStatus
from app.services.ai_core import get_ai_core
from app.core.config import settings
logger = logging.getLogger(__name__)
# =============================================================================
# Data Classes for Clean Interface
# =============================================================================
class IncomingMessage:
"""Represents an incoming message from any channel."""
def __init__(
self,
channel: str, # "telegram", "whatsapp", "instagram", "email"
sender_id: str, # Unique ID (phone, telegram_id, email)
sender_name: str,
text: str,
is_voice: bool = False,
media_url: Optional[str] = None,
media_type: Optional[str] = None,
raw_payload: Optional[Dict[str, Any]] = None
):
self.channel = channel
self.sender_id = sender_id
self.sender_name = sender_name
self.text = text
self.is_voice = is_voice
self.media_url = media_url
self.media_type = media_type
self.raw_payload = raw_payload or {}
# =============================================================================
# Lead/Conversation Management
# =============================================================================
async def get_or_create_lead(
session: AsyncSession,
tenant_id: UUID,
channel: str,
sender_id: str,
sender_name: str
) -> Lead:
"""
Find existing lead or create new one.
Matches by channel-specific ID (telegram_id, whatsapp_id, email).
"""
# Build query based on channel
if channel == "telegram":
stmt = select(Lead).where(
Lead.tenant_id == tenant_id,
Lead.telegram_id == sender_id
)
elif channel in ("whatsapp", "instagram"):
stmt = select(Lead).where(
Lead.tenant_id == tenant_id,
Lead.whatsapp_id == sender_id
)
else: # email
stmt = select(Lead).where(
Lead.tenant_id == tenant_id,
Lead.email == sender_id
)
result = await session.execute(stmt)
lead = result.scalar_one_or_none()
if not lead:
# Create new lead with channel-specific ID
lead_data = {
"tenant_id": tenant_id,
"name": sender_name,
"status": "NEW",
"processing_status": "idle"
}
if channel == "telegram":
lead_data["telegram_id"] = sender_id
elif channel in ("whatsapp", "instagram"):
lead_data["whatsapp_id"] = sender_id
else:
lead_data["email"] = sender_id
lead = Lead(**lead_data)
session.add(lead)
await session.flush()
logger.info(f"✨ Created new lead {lead.id} for {channel}:{sender_id}")
return lead
async def get_or_create_conversation(
session: AsyncSession,
tenant_id: UUID,
lead_id: UUID,
channel: str
) -> Conversation:
"""Find active conversation or create new one."""
stmt = select(Conversation).where(
Conversation.tenant_id == tenant_id,
Conversation.lead_id == lead_id,
Conversation.channel == channel,
Conversation.is_active == True
)
result = await session.execute(stmt)
conversation = result.scalar_one_or_none()
if not conversation:
conversation = Conversation(
tenant_id=tenant_id,
lead_id=lead_id,
channel=channel,
is_active=True
)
session.add(conversation)
await session.flush()
logger.info(f"✨ Created new conversation {conversation.id}")
return conversation
async def get_conversation_history(
session: AsyncSession,
conversation_id: UUID
) -> List[Message]:
"""Get all messages in conversation ordered by time."""
stmt = select(Message).where(
Message.conversation_id == conversation_id
).order_by(Message.created_at)
result = await session.execute(stmt)
return list(result.scalars().all())
# =============================================================================
# Message Processing
# =============================================================================
async def save_user_message(
session: AsyncSession,
tenant_id: UUID,
conversation_id: UUID,
text: str,
media_url: Optional[str] = None,
media_type: Optional[str] = None
) -> Message:
"""Save incoming user message to database."""
message = Message(
tenant_id=tenant_id,
conversation_id=conversation_id,
sender_type="user",
content=text,
media_url=media_url,
media_type=media_type
)
session.add(message)
await session.flush()
return message
async def save_ai_message(
session: AsyncSession,
tenant_id: UUID,
conversation_id: UUID,
text: str,
tokens: Dict[str, int] = None
) -> Message:
"""Save AI response message to database."""
tokens = tokens or {}
message = Message(
tenant_id=tenant_id,
conversation_id=conversation_id,
sender_type="ai",
content=text,
prompt_tokens=tokens.get("prompt_tokens"),
completion_tokens=tokens.get("completion_tokens"),
model_used=settings.GEMINI_MODEL,
status=MessageStatus.PENDING
)
session.add(message)
await session.flush()
return message
async def generate_ai_response(
session: AsyncSession,
tenant: Tenant,
lead: Lead,
user_message: str,
conversation_history: List[Message],
media_url: Optional[str] = None,
media_type: Optional[str] = None
) -> Dict[str, Any]:
"""Generate AI sales response using AICore."""
ai_core = get_ai_core()
response = await ai_core.generate_sales_response(
session=session,
tenant=tenant,
lead=lead,
user_message=user_message,
conversation_history=conversation_history,
media_url=media_url,
media_type=media_type
)
return response
# =============================================================================
# Main Processing Function
# =============================================================================
async def process_incoming_message(
session: AsyncSession,
tenant: Tenant,
message: IncomingMessage
) -> Dict[str, Any]:
"""
Unified message processing pipeline.
Steps:
1. Find/Create Lead
2. Find/Create Conversation
3. Save User Message
4. Generate AI Response
5. Save AI Message
6. Return response for sending
Returns:
Dict with keys: lead, conversation, user_message, ai_message, response_text
"""
# 1. Find/Create Lead
lead = await get_or_create_lead(
session=session,
tenant_id=tenant.id,
channel=message.channel,
sender_id=message.sender_id,
sender_name=message.sender_name
)
lead.last_message_at = datetime.utcnow()
lead.processing_status = "generating"
session.add(lead)
# 2. Find/Create Conversation
conversation = await get_or_create_conversation(
session=session,
tenant_id=tenant.id,
lead_id=lead.id,
channel=message.channel
)
# 3. Save User Message
user_msg = await save_user_message(
session=session,
tenant_id=tenant.id,
conversation_id=conversation.id,
text=message.text,
media_url=message.media_url,
media_type=message.media_type
)
await session.commit()
# 4. ANTI-SPAM: Kill Switch (Max 50 messages per hour)
one_hour_ago = datetime.utcnow() - timedelta(hours=1)
count_stmt = select(func.count(Message.id)).where(
Message.conversation_id == conversation.id,
Message.sender_type == "user",
Message.created_at >= one_hour_ago
)
msg_count_res = await session.execute(count_stmt)
msg_count = msg_count_res.scalar_one()
if msg_count > 50:
logger.warning(
f"🚨 KILL SWITCH ACTIVATED: Lead {lead.id} sent {msg_count} messages in 1 hour. Disabling AI."
)
conversation.human_takeover = True
lead.needs_attention = True
lead.processing_status = "idle"
session.add(conversation)
session.add(lead)
await session.commit()
# Notify Manager
from app.services.notification import notification_service
await notification_service.notify_kill_switch(
tenant=tenant,
lead=lead,
msg_count=msg_count
)
return {
"lead": lead,
"conversation": conversation,
"user_message": user_msg,
"ai_message": None,
"response_text": "(ИИ временно отключен из-за подозрительной активности. Ожидайте ответа менеджера.)",
"is_voice_reply": False
}
# 5. Get History & Generate AI Response
history = await get_conversation_history(session, conversation.id)
response = await generate_ai_response(
session=session,
tenant=tenant,
lead=lead,
user_message=message.text,
conversation_history=history,
media_url=message.media_url,
media_type=message.media_type
)
# 6. Save AI Message
ai_msg = await save_ai_message(
session=session,
tenant_id=tenant.id,
conversation_id=conversation.id,
text=response["text"],
tokens={
"prompt_tokens": response.get("prompt_tokens"),
"completion_tokens": response.get("completion_tokens")
}
)
lead.processing_status = "idle"
session.add(lead)
await session.commit()
return {
"lead": lead,
"conversation": conversation,
"user_message": user_msg,
"ai_message": ai_msg,
"response_text": response["text"],
"is_voice_reply": message.is_voice
}
# =============================================================================
# Singleton
# =============================================================================
class MessageProcessor:
"""Facade for message processing service."""
async def process(
self,
session: AsyncSession,
tenant: Tenant,
message: IncomingMessage
) -> Dict[str, Any]:
return await process_incoming_message(session, tenant, message)
_processor_instance: Optional[MessageProcessor] = None
def get_message_processor() -> MessageProcessor:
"""Get message processor instance."""
global _processor_instance
if _processor_instance is None:
_processor_instance = MessageProcessor()
return _processor_instance
|