Spaces:
Sleeping

axeronis commited on
Commit
1a936c6
·
1 Parent(s): 2ae41f6

Enhance reactivation with human-like AI behavior

Browse files

Improved lead_analyzer.py evaluate_reactivation_impl:
- Uses lead name, psychotype, heat score for personalization
- 4 strategies: value, question, reminder, offer
- Natural conversational tone examples
- Anti-patterns to avoid formal bot language
- Temperature 0.8 for more creative responses
- Russian prompts for Russian audience

backend/app/services/ai_core/lead_analyzer.py CHANGED
@@ -336,44 +336,94 @@ async def evaluate_reactivation_impl(
336
  conversation_history: List[Message]
337
  ) -> Dict[str, Any]:
338
  """
339
- Evaluate if a stale lead should be reactivated and generate a message.
 
 
 
 
 
340
  """
341
  # Get conversation text
342
  conversation_text = "\n".join([
343
  f"{msg.sender_type.upper()}: {msg.content}"
344
- for msg in conversation_history[-10:] # Last 10 messages
345
  ])
346
 
347
- # Use LLM to generate reactivation message
 
 
 
 
348
  try:
349
- reactivation_prompt = f"""
350
- Based on the following conversation, generate a friendly reactivation message
351
- to re-engage the lead. The message should:
352
- 1. Reference something specific from the conversation
353
- 2. Add value (new info, offer, etc.)
354
- 3. Have a clear call to action
 
355
 
356
- Conversation:
357
  {conversation_text}
358
 
359
- Generate ONLY the reactivation message, nothing else.
360
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361
 
362
  response = await ai_core.llm.generate_response(
363
  prompt=reactivation_prompt,
364
- system_instruction="You are a sales assistant. Be friendly and non-pushy."
 
 
 
 
365
  )
366
 
 
 
 
 
 
367
  return {
 
368
  "should_reactivate": True,
369
- "message": response["text"],
370
- "reason": "Stale lead reactivation"
 
371
  }
372
 
373
  except Exception as e:
374
  print(f"⚠️ Reactivation evaluation failed: {e}")
375
  return {
 
376
  "should_reactivate": False,
 
377
  "message": None,
378
  "reason": str(e)
379
  }
 
 
336
  conversation_history: List[Message]
337
  ) -> Dict[str, Any]:
338
  """
339
+ Evaluate if a stale lead should be reactivated and generate a HUMAN-LIKE message.
340
+
341
+ The AI should:
342
+ 1. Analyze the conversation to understand the lead's needs
343
+ 2. Decide the best reactivation strategy
344
+ 3. Generate a natural, personalized message
345
  """
346
  # Get conversation text
347
  conversation_text = "\n".join([
348
  f"{msg.sender_type.upper()}: {msg.content}"
349
+ for msg in conversation_history[-15:] # Last 15 messages for more context
350
  ])
351
 
352
+ lead_name = lead.name or "друг"
353
+ psychotype = getattr(lead, 'psychotype', 'unknown')
354
+ heat_score = getattr(lead, 'heat_score', 50) or 50
355
+
356
+ # Use LLM to evaluate and generate message
357
  try:
358
+ reactivation_prompt = f"""Ты — опытный менеджер по продажам. Твоя задача — вернуть клиента в диалог ЕСТЕСТВЕННЫМ способом.
359
+
360
+ 📋 ИНФОРМАЦИЯ О КЛИЕНТЕ:
361
+ - Имя: {lead_name}
362
+ - Психотип (DISC): {psychotype}
363
+ - Теплота (heat): {heat_score}%
364
+ - Последнее общение: давно (холодный контакт)
365
 
366
+ 💬 ИСТОРИЯ ДИАЛОГА:
367
  {conversation_text}
368
 
369
+ 🎯 ТВОЯ ЗАДАЧА:
370
+ 1. Проанализируй диалог и пойми СУТЬ интереса клиента
371
+ 2. Выбери ОДНУ стратегию из списка:
372
+ • ЦЕННОСТЬ — поделись полезной информацией/новостью по теме клиента
373
+ • ВОПРОС — задай уточняющий вопрос, показывая что помнишь о нём
374
+ • НАПОМИНАНИЕ — мягко напомни о незавершённом вопросе
375
+ • ПРЕДЛОЖЕНИЕ — предложи что-то интересное (скидку, акцию, новинку)
376
+
377
+ 3. Напиши ОДНО сообщение клиенту. Правила:
378
+ - Используй имя клиента естественно
379
+ - Пиши как живой человек, не робот
380
+ - Не начинай с "Привет" если это выглядит навязчиво
381
+ - Дай ценность или задай вопрос
382
+ - Не давай явных "call to action" типа "напишите нам"
383
+ - Максимум 2-3 предложения
384
+
385
+ ПРИМЕРЫ ХОРОШИХ СООБЩЕНИЙ:
386
+ • "{lead_name}, кстати, мы как раз завезли ту модель что ты смотрел — хочешь глянуть?"
387
+ • "Вспомнил про твой вопрос о [X] — нашёл интересную информацию 🤔"
388
+ • "Как дела с проектом? Если ещё актуально — готов помочь"
389
+
390
+ ❌ НЕ ПИШИ:
391
+ • "Добрый день! Связываемся с вами по поводу..."
392
+ • "Напоминаем что у нас есть отличные предложения..."
393
+ • Любой формальный бизнес-язык
394
+
395
+ 📤 ОТВЕТ:
396
+ Напиши ТОЛЬКО само сообщение клиенту (без пояснений):"""
397
 
398
  response = await ai_core.llm.generate_response(
399
  prompt=reactivation_prompt,
400
+ system_instruction="""Ты живой, дружелюбный менеджер.
401
+ Твоя цель — не продать напрямую, а ВОССТАНОВИТЬ КОНТАКТ.
402
+ Пиши как друг который вспомнил о человеке, а не как бот.
403
+ Ответ должен быть коротким (1-3 предложения) и естественным.""",
404
+ temperature=0.8 # More creative/natural
405
  )
406
 
407
+ message = response["text"].strip()
408
+
409
+ # Clean up any accidental formatting
410
+ message = message.strip('"\'')
411
+
412
  return {
413
+ "decision": True, # Compatible with old format
414
  "should_reactivate": True,
415
+ "draft_message": message,
416
+ "message": message,
417
+ "reason": "Human-like reactivation based on conversation history"
418
  }
419
 
420
  except Exception as e:
421
  print(f"⚠️ Reactivation evaluation failed: {e}")
422
  return {
423
+ "decision": False,
424
  "should_reactivate": False,
425
+ "draft_message": None,
426
  "message": None,
427
  "reason": str(e)
428
  }
429
+