Spaces:
Running

axeronis commited on
Commit
4e07887
·
1 Parent(s): 3ee10ee

feat: enable smart LLM name extraction

Browse files
backend/app/api/webhook.py CHANGED
@@ -571,10 +571,12 @@ async def telegram_webhook(
571
  # Extract real name from message (avoid using Telegram nicknames)
572
  try:
573
  from app.utils.name_extraction import extract_name_from_message, should_update_lead_name
 
574
 
575
- # Try to extract name from first few messages
576
  if user_text and len(user_text) > 5:
577
- extracted_name = await extract_name_from_message(user_text, llm_client=None, use_llm_fallback=False)
 
578
 
579
  if extracted_name and should_update_lead_name(lead.name or "", extracted_name):
580
  logger.info(f"✅ Updating lead name from '{lead.name}' to '{extracted_name}'")
 
571
  # Extract real name from message (avoid using Telegram nicknames)
572
  try:
573
  from app.utils.name_extraction import extract_name_from_message, should_update_lead_name
574
+ from app.services.llm_client import get_llm_client
575
 
576
+ # Try to extract name from first few messages using AI
577
  if user_text and len(user_text) > 5:
578
+ llm = get_llm_client()
579
+ extracted_name = await extract_name_from_message(user_text, llm_client=llm, use_llm_fallback=True)
580
 
581
  if extracted_name and should_update_lead_name(lead.name or "", extracted_name):
582
  logger.info(f"✅ Updating lead name from '{lead.name}' to '{extracted_name}'")
backend/app/utils/name_extraction.py CHANGED
@@ -128,24 +128,35 @@ async def _extract_name_with_llm(text: str, llm_client) -> Optional[str]:
128
  if not llm_client:
129
  llm_client = get_llm_client()
130
 
131
- prompt = f"""Extract the person's real name from this message.
132
-
133
- Rules:
134
- - Return ONLY the name (first name or full name)
135
- - Return "NONE" if no real name is mentioned
136
- - Ignore usernames like @username
137
- - Ignore words like "User", "Client", etc.
138
-
139
- Message: "{text}"
140
-
141
- Name:"""
 
 
 
 
 
 
 
 
142
 
143
- response = await llm_client.generate_simple(prompt, max_tokens=50)
144
- extracted = response.strip()
 
145
 
146
  # Validate LLM response
147
- if extracted and extracted != "NONE" and 2 <= len(extracted) <= 50:
148
- if not _is_invalid_name(extracted):
 
 
149
  return extracted
150
 
151
  except Exception as e:
 
128
  if not llm_client:
129
  llm_client = get_llm_client()
130
 
131
+ prompt = f"""Ты - система извлечения имён. Извлеки НАСТОЯЩЕЕ ИМЯ человека из сообщения.
132
+
133
+ ПРАВИЛА:
134
+ 1. Верни ТОЛЬКО имя (или имя + фамилию)
135
+ 2. Верни "NONE" если в сообщении НЕТ настоящего имени человека
136
+ 3. Имя должно быть РЕАЛЬНЫМ человеческим именем (Алексей, Мария, Дмитрий, Anna, John и т.д.)
137
+ 4. НЕ извлекай:
138
+ - Глаголы (демонстрирую, показываю, хочу)
139
+ - Существительные не являющиеся именами (экспертность, качество)
140
+ - Никнеймы и юзернеймы (@username, axeron123)
141
+ - Общие слова (клиент, пользователь, User)
142
+ 5. Имя обычно представляется фразами: "меня зовут X", "я X", "my name is X", "это X"
143
+
144
+ Сообщение: "{text[:500]}"
145
+
146
+ Ответ (только имя или NONE):"""
147
+
148
+ response = await llm_client.generate_simple(prompt, max_tokens=30)
149
+ extracted = response.strip().strip('"').strip("'")
150
 
151
+ # Clean up response
152
+ if extracted.startswith("Ответ:"):
153
+ extracted = extracted[6:].strip()
154
 
155
  # Validate LLM response
156
+ if extracted and extracted.upper() != "NONE" and 2 <= len(extracted) <= 50:
157
+ # Additional validation
158
+ if not _is_invalid_name(extracted) and not extracted.startswith("@"):
159
+ logger.info(f"🧠 LLM extracted name: {extracted}")
160
  return extracted
161
 
162
  except Exception as e: