Spaces:
Running

axeronis commited on
Commit
22ede4b
·
1 Parent(s): fec5732

fix: limit name extraction to first 5 messages only to prevent random word extraction

Browse files
Files changed (1) hide show
  1. backend/app/api/webhook.py +39 -19
backend/app/api/webhook.py CHANGED
@@ -1,5 +1,6 @@
1
  from fastapi import APIRouter, Request, HTTPException, Depends, BackgroundTasks, Header
2
  from sqlalchemy.ext.asyncio import AsyncSession
 
3
  from sqlmodel import select
4
  from typing import Dict, Any, Optional
5
  from datetime import datetime
@@ -837,31 +838,50 @@ async def telegram_webhook(
837
  logger.warning(f"⚠️ WebSocket notify failed (non-critical): {e}")
838
 
839
  # Extract real name from message (avoid using Telegram nicknames)
 
840
  try:
841
  from app.utils.name_extraction import extract_name_from_message, should_update_lead_name
842
  from app.services.llm_client import get_llm_client
 
843
 
844
- # Try to extract name from first few messages using AI
845
- if user_text and len(user_text) > 5:
846
- llm = get_llm_client()
847
- extracted_name = await extract_name_from_message(user_text, llm_client=llm, use_llm_first=True)
 
 
 
 
 
 
 
 
848
 
849
- if extracted_name and should_update_lead_name(lead.name or "", extracted_name):
850
- logger.info(f"✅ Updating lead name from '{lead.name}' to '{extracted_name}'")
851
- lead.name = extracted_name
852
- session.add(lead)
853
- await session.commit()
854
 
855
- # Notify WebSocket clients about name update for real-time AI Summary refresh
856
- try:
857
- from app.api.websocket_chat import notify_lead_updated
858
- await notify_lead_updated(str(lead.id), {
859
- "id": str(lead.id),
860
- "name": lead.name,
861
- })
862
- logger.debug(f"📡 WebSocket: lead name updated to '{lead.name}'")
863
- except Exception as ws_err:
864
- logger.warning(f"⚠️ WebSocket lead update failed: {ws_err}")
 
 
 
 
 
 
 
 
 
 
865
  except Exception as e:
866
  logger.warning(f"⚠️ Name extraction failed (non-critical): {e}")
867
 
 
1
  from fastapi import APIRouter, Request, HTTPException, Depends, BackgroundTasks, Header
2
  from sqlalchemy.ext.asyncio import AsyncSession
3
+ from sqlalchemy import func
4
  from sqlmodel import select
5
  from typing import Dict, Any, Optional
6
  from datetime import datetime
 
838
  logger.warning(f"⚠️ WebSocket notify failed (non-critical): {e}")
839
 
840
  # Extract real name from message (avoid using Telegram nicknames)
841
+ # IMPORTANT: Only try extraction in FIRST 5 messages to avoid extracting random words
842
  try:
843
  from app.utils.name_extraction import extract_name_from_message, should_update_lead_name
844
  from app.services.llm_client import get_llm_client
845
+ from app.models.lead import Message as LeadMessage
846
 
847
+ # Count how many messages this lead has sent
848
+ msg_count_stmt = select(func.count()).select_from(LeadMessage).where(
849
+ LeadMessage.conversation_id == conversation.id,
850
+ LeadMessage.sender_type == "user"
851
+ )
852
+ msg_count_result = await session.execute(msg_count_stmt)
853
+ message_count = msg_count_result.scalar() or 0
854
+
855
+ # Only try to extract name in first 5 messages
856
+ # AND only if current name looks like nickname or is missing
857
+ if message_count <= 5 and user_text and len(user_text) > 5:
858
+ current_name = lead.name or ""
859
 
860
+ # Check if we even need to update (has nickname or no name)
861
+ if should_update_lead_name(current_name, "ПотенциальноеИмя"):
862
+ llm = get_llm_client()
863
+ extracted_name = await extract_name_from_message(user_text, llm_client=llm, use_llm_first=True)
 
864
 
865
+ if extracted_name and should_update_lead_name(current_name, extracted_name):
866
+ logger.info(f"✅ Updating lead name from '{lead.name}' to '{extracted_name}' (msg #{message_count})")
867
+ lead.name = extracted_name
868
+ session.add(lead)
869
+ await session.commit()
870
+
871
+ # Notify WebSocket clients about name update
872
+ try:
873
+ from app.api.websocket_chat import notify_lead_updated
874
+ await notify_lead_updated(str(lead.id), {
875
+ "id": str(lead.id),
876
+ "name": lead.name,
877
+ })
878
+ logger.debug(f"📡 WebSocket: lead name updated to '{lead.name}'")
879
+ except Exception as ws_err:
880
+ logger.warning(f"⚠️ WebSocket lead update failed: {ws_err}")
881
+ else:
882
+ logger.debug(f"⏭️ Skipping name extraction - lead already has valid name: '{current_name}'")
883
+ elif message_count > 5:
884
+ logger.debug(f"⏭️ Skipping name extraction - past message limit ({message_count} > 5)")
885
  except Exception as e:
886
  logger.warning(f"⚠️ Name extraction failed (non-critical): {e}")
887