Spaces:
Running
Running
axeronis commited on
Commit ·
bc09d91
1
Parent(s): 333903b
Fix UnboundLocalError, improve AI math, greetings, and name extraction
Browse files- backend/app/api/webhook.py +3 -4
- backend/app/services/ai_core/prompt_builder.py +8 -1
- backend/app/services/ai_core/response_generator.py +25 -2
- backend/app/utils/name_extraction.py +28 -20
- frontend/app/settings/playbook/page.tsx +6 -3
- frontend/components/settings/ProductSettings.tsx +2 -2
- frontend/components/ui/switch.tsx +1 -1
backend/app/api/webhook.py
CHANGED
|
@@ -819,7 +819,7 @@ async def telegram_webhook(
|
|
| 819 |
# Try to extract name from first few messages using AI
|
| 820 |
if user_text and len(user_text) > 5:
|
| 821 |
llm = get_llm_client()
|
| 822 |
-
extracted_name = await extract_name_from_message(user_text, llm_client=llm,
|
| 823 |
|
| 824 |
if extracted_name and should_update_lead_name(lead.name or "", extracted_name):
|
| 825 |
logger.info(f"✅ Updating lead name from '{lead.name}' to '{extracted_name}'")
|
|
@@ -1119,6 +1119,8 @@ async def process_ai_response_background(
|
|
| 1119 |
- If respond_with_voice=True, AI will send voice message instead of text
|
| 1120 |
"""
|
| 1121 |
from app.core.database import async_session_maker
|
|
|
|
|
|
|
| 1122 |
import asyncio
|
| 1123 |
|
| 1124 |
logger.info(
|
|
@@ -1925,9 +1927,6 @@ Answer with ONE word:
|
|
| 1925 |
|
| 1926 |
if should_send_voice:
|
| 1927 |
try:
|
| 1928 |
-
from app.services.voice_service import voice_service
|
| 1929 |
-
from app.services.telegram_service import telegram_service
|
| 1930 |
-
|
| 1931 |
# Generate speech using tenant's selected voice
|
| 1932 |
voice_id = getattr(tenant, 'voice_id', 'professional_male')
|
| 1933 |
custom_voice_url = getattr(tenant, 'voice_reference_url', None)
|
|
|
|
| 819 |
# Try to extract name from first few messages using AI
|
| 820 |
if user_text and len(user_text) > 5:
|
| 821 |
llm = get_llm_client()
|
| 822 |
+
extracted_name = await extract_name_from_message(user_text, llm_client=llm, use_llm_first=True)
|
| 823 |
|
| 824 |
if extracted_name and should_update_lead_name(lead.name or "", extracted_name):
|
| 825 |
logger.info(f"✅ Updating lead name from '{lead.name}' to '{extracted_name}'")
|
|
|
|
| 1119 |
- If respond_with_voice=True, AI will send voice message instead of text
|
| 1120 |
"""
|
| 1121 |
from app.core.database import async_session_maker
|
| 1122 |
+
from app.services.voice_service import voice_service
|
| 1123 |
+
from app.services.telegram_service import telegram_service
|
| 1124 |
import asyncio
|
| 1125 |
|
| 1126 |
logger.info(
|
|
|
|
| 1927 |
|
| 1928 |
if should_send_voice:
|
| 1929 |
try:
|
|
|
|
|
|
|
|
|
|
| 1930 |
# Generate speech using tenant's selected voice
|
| 1931 |
voice_id = getattr(tenant, 'voice_id', 'professional_male')
|
| 1932 |
custom_voice_url = getattr(tenant, 'voice_reference_url', None)
|
backend/app/services/ai_core/prompt_builder.py
CHANGED
|
@@ -299,12 +299,19 @@ def build_system_prompt(
|
|
| 299 |
[КАЧЕСТВО ОТВЕТОВ - КРИТИЧЕСКИ ВАЖНО!]
|
| 300 |
═══════════════════════════════════════════════════════════════
|
| 301 |
⛔ ЗАПРЕЩЕНО:
|
| 302 |
-
1. НЕ ПОВТОРЯЙ приветствие
|
|
|
|
| 303 |
2. НЕ СПРАШИВАЙ информацию, которую клиент УЖЕ дал (перечитай историю!)
|
| 304 |
3. НЕ НАЗЫВАЙ разные цены на один товар - будь КОНСИСТЕНТЕН
|
| 305 |
4. НЕ ОБРЫВАЙ предложения на середине - заканчивай мысль полностью
|
| 306 |
5. НЕ ОТПРАВЛЯЙ больше одного сообщения за раз
|
| 307 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 308 |
✅ ОБЯЗАТЕЛЬНО:
|
| 309 |
1. ЧИТАЙ историю диалога - помни что обсуждали
|
| 310 |
2. Цены ВСЕГДА бери из [KNOWLEDGE BASE] - не выдумывай!
|
|
|
|
| 299 |
[КАЧЕСТВО ОТВЕТОВ - КРИТИЧЕСКИ ВАЖНО!]
|
| 300 |
═══════════════════════════════════════════════════════════════
|
| 301 |
⛔ ЗАПРЕЩЕНО:
|
| 302 |
+
1. НЕ ПОВТОРЯЙ приветствие (Привет, Здравствуйте и т.д.), если ты УЖЕ здоровался в этом диалоге.
|
| 303 |
+
- ИСКЛЮЧЕНИЕ: Если с последнего сообщения клиента прошло много времени (новый день), поздоровайся снова.
|
| 304 |
2. НЕ СПРАШИВАЙ информацию, которую клиент УЖЕ дал (перечитай историю!)
|
| 305 |
3. НЕ НАЗЫВАЙ разные цены на один товар - будь КОНСИСТЕНТЕН
|
| 306 |
4. НЕ ОБРЫВАЙ предложения на середине - заканчивай мысль полностью
|
| 307 |
5. НЕ ОТПРАВЛЯЙ больше одного сообщения за раз
|
| 308 |
|
| 309 |
+
✅ МАТЕМАТИКА И РАСЧЕТЫ:
|
| 310 |
+
- Будь ПРЕДЕЛЬНО ТОЧЕН в расчетах.
|
| 311 |
+
- Если нужно что-то посчитать (цену со скидкой, общую сумму), делай это пошагово.
|
| 312 |
+
- ПЕРЕПРОВЕРЯЙ результат перед тем как написать его клиенту.
|
| 313 |
+
- Ошибка в цифрах = потеря доверия и денег клиента.
|
| 314 |
+
|
| 315 |
✅ ОБЯЗАТЕЛЬНО:
|
| 316 |
1. ЧИТАЙ историю диалога - помни что обсуждали
|
| 317 |
2. Цены ВСЕГДА бери из [KNOWLEDGE BASE] - не выдумывай!
|
backend/app/services/ai_core/response_generator.py
CHANGED
|
@@ -190,14 +190,37 @@ Answer with ONE word only: WANT_VOICE, NO_VOICE, or NEUTRAL""",
|
|
| 190 |
conversation_facts = "\n[ПАМЯТЬ ДИАЛОГА - НЕ СПРАШИВАЙ ПОВТОРНО!]\n" + "\n".join(facts)
|
| 191 |
logger.info(f"🧠 Injecting {len(facts)} conversation facts into context")
|
| 192 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
# 5. DYNAMIC CONTEXT (Things that change per request)
|
|
|
|
|
|
|
| 194 |
dynamic_context = f"""
|
| 195 |
-
[CURRENT CONTEXT - {
|
| 196 |
User Name: {lead.name or 'Unknown'}
|
| 197 |
Psychotype: {lead.psychotype} (Adapt tone accordingly)
|
| 198 |
Funnel Stage: {current_stage.name if current_stage else 'General'}
|
| 199 |
Goal: {current_stage.ai_goal if current_stage else 'Assist user'}
|
| 200 |
-
Message Count: {ai_message_count}
|
|
|
|
|
|
|
| 201 |
{conversation_facts}
|
| 202 |
|
| 203 |
[BOOKING AVAILABILITY]
|
|
|
|
| 190 |
conversation_facts = "\n[ПАМЯТЬ ДИАЛОГА - НЕ СПРАШИВАЙ ПОВТОРНО!]\n" + "\n".join(facts)
|
| 191 |
logger.info(f"🧠 Injecting {len(facts)} conversation facts into context")
|
| 192 |
|
| 193 |
+
# 4.5 TIME AWARENESS & GREETING LOGIC
|
| 194 |
+
# Check if we should greet again (if last message was more than 12 hours ago)
|
| 195 |
+
is_new_session = False
|
| 196 |
+
last_msg_time_str = "Первое сообщение"
|
| 197 |
+
|
| 198 |
+
if conversation_history:
|
| 199 |
+
# Get the timestamp of the last message BEFORE the current one
|
| 200 |
+
# Current message might already be in history or not, depending on how it's called
|
| 201 |
+
# Usually it's messages[: -1] if last is current
|
| 202 |
+
other_messages = [m for m in conversation_history if get_content(m) != user_message]
|
| 203 |
+
if other_messages:
|
| 204 |
+
last_msg = other_messages[-1]
|
| 205 |
+
last_time = getattr(last_msg, 'created_at', None)
|
| 206 |
+
if last_time:
|
| 207 |
+
diff = datetime.utcnow() - last_time
|
| 208 |
+
if diff.total_seconds() > 12 * 3600: # 12 hours
|
| 209 |
+
is_new_session = True
|
| 210 |
+
last_msg_time_str = last_time.strftime("%d.%m %H:%M")
|
| 211 |
+
|
| 212 |
# 5. DYNAMIC CONTEXT (Things that change per request)
|
| 213 |
+
current_time = datetime.now().strftime("%Y-%m-%d %H:%M")
|
| 214 |
+
|
| 215 |
dynamic_context = f"""
|
| 216 |
+
[CURRENT CONTEXT - {current_time}]
|
| 217 |
User Name: {lead.name or 'Unknown'}
|
| 218 |
Psychotype: {lead.psychotype} (Adapt tone accordingly)
|
| 219 |
Funnel Stage: {current_stage.name if current_stage else 'General'}
|
| 220 |
Goal: {current_stage.ai_goal if current_stage else 'Assist user'}
|
| 221 |
+
Message Count: {ai_message_count}
|
| 222 |
+
Is New Session: {is_new_session} (Если True - можешь поздороваться снова, даже если уже здоровался когда-то раньше)
|
| 223 |
+
Last Interaction: {last_msg_time_str}
|
| 224 |
{conversation_facts}
|
| 225 |
|
| 226 |
[BOOKING AVAILABILITY]
|
backend/app/utils/name_extraction.py
CHANGED
|
@@ -121,7 +121,7 @@ def _is_invalid_name(name: str) -> bool:
|
|
| 121 |
async def _extract_name_with_llm(text: str, llm_client) -> Optional[str]:
|
| 122 |
"""
|
| 123 |
Use LLM to extract name from text.
|
| 124 |
-
Only used as fallback when regex fails.
|
| 125 |
"""
|
| 126 |
try:
|
| 127 |
# Import here to avoid circular dependency
|
|
@@ -130,25 +130,26 @@ async def _extract_name_with_llm(text: str, llm_client) -> Optional[str]:
|
|
| 130 |
if not llm_client:
|
| 131 |
llm_client = get_llm_client()
|
| 132 |
|
| 133 |
-
prompt = f"""Ты - система извлечения имён. Извлеки НАСТОЯЩЕЕ ИМЯ человека из сообщения.
|
| 134 |
-
|
| 135 |
-
ПРАВИЛА:
|
| 136 |
-
1. Верни ТОЛЬКО имя (или имя + фамилию)
|
| 137 |
-
2. Верни "NONE" если в
|
| 138 |
-
3.
|
| 139 |
-
4. НЕ извлекай
|
| 140 |
-
|
| 141 |
-
-
|
| 142 |
-
- Н
|
| 143 |
-
-
|
| 144 |
-
|
|
|
|
| 145 |
|
| 146 |
Сообщение: "{text[:500]}"
|
| 147 |
|
| 148 |
-
Ответ (
|
| 149 |
|
| 150 |
-
response = await llm_client.generate_simple(prompt, max_tokens=
|
| 151 |
-
extracted = response.strip().strip('"').strip("'")
|
| 152 |
|
| 153 |
# Clean up response
|
| 154 |
if extracted.startswith("Ответ:"):
|
|
@@ -156,10 +157,17 @@ async def _extract_name_with_llm(text: str, llm_client) -> Optional[str]:
|
|
| 156 |
|
| 157 |
# Validate LLM response
|
| 158 |
if extracted and extracted.upper() != "NONE" and 2 <= len(extracted) <= 50:
|
| 159 |
-
#
|
| 160 |
-
if
|
| 161 |
-
logger.info(f"
|
| 162 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
|
| 164 |
except Exception as e:
|
| 165 |
logger.error(f"LLM name extraction failed: {e}")
|
|
|
|
| 121 |
async def _extract_name_with_llm(text: str, llm_client) -> Optional[str]:
|
| 122 |
"""
|
| 123 |
Use LLM to extract name from text.
|
| 124 |
+
Only used as fallback when regex fails or for higher accuracy.
|
| 125 |
"""
|
| 126 |
try:
|
| 127 |
# Import here to avoid circular dependency
|
|
|
|
| 130 |
if not llm_client:
|
| 131 |
llm_client = get_llm_client()
|
| 132 |
|
| 133 |
+
prompt = f"""Ты - система извлечения имён. Извлеки НАСТОЯЩЕЕ ИМЯ человека из сообщения, если человек представился.
|
| 134 |
+
|
| 135 |
+
ПРАВИЛА (СОБЛЮДАЙ СТРОГО):
|
| 136 |
+
1. Верни ТОЛЬКО имя (или имя + фамилию). Пример: "Алексей" или "Иван Иванов".
|
| 137 |
+
2. Верни "NONE", если человек НЕ представился и НЕ назвал своё имя.
|
| 138 |
+
3. ВАЖНО: Если человек просто отвечает на вопрос (например, "Да", "Я из Москвы", "Хочу заказать"), это НЕ значит, что он называет имя.
|
| 139 |
+
4. НЕ извлекай имя, если оно не является частью фразы-представления.
|
| 140 |
+
5. НЕ извлекай:
|
| 141 |
+
- Глаголы (хочу, беру, думаю, я написал)
|
| 142 |
+
- Названия городов (Москва, Алматы)
|
| 143 |
+
- Юзернеймы (@user)
|
| 144 |
+
- Общие слова (клиент, привет, бот)
|
| 145 |
+
6. Ответ должен содержать ТОЛЬКО имя или слово "NONE".
|
| 146 |
|
| 147 |
Сообщение: "{text[:500]}"
|
| 148 |
|
| 149 |
+
Ответ (имя или NONE):"""
|
| 150 |
|
| 151 |
+
response = await llm_client.generate_simple(prompt, max_tokens=20)
|
| 152 |
+
extracted = response.strip().strip('"').strip("'").strip(".")
|
| 153 |
|
| 154 |
# Clean up response
|
| 155 |
if extracted.startswith("Ответ:"):
|
|
|
|
| 157 |
|
| 158 |
# Validate LLM response
|
| 159 |
if extracted and extracted.upper() != "NONE" and 2 <= len(extracted) <= 50:
|
| 160 |
+
# Check if it's just a common word or verb
|
| 161 |
+
if _is_invalid_name(extracted):
|
| 162 |
+
logger.info(f"🚫 LLM extracted invalid name (discarded): {extracted}")
|
| 163 |
+
return None
|
| 164 |
+
|
| 165 |
+
if extracted.startswith("@") or any(c.isdigit() for c in extracted):
|
| 166 |
+
logger.info(f"🚫 LLM extracted nickname/illegal chars (discarded): {extracted}")
|
| 167 |
+
return None
|
| 168 |
+
|
| 169 |
+
logger.info(f"🧠 LLM extracted name: {extracted}")
|
| 170 |
+
return extracted
|
| 171 |
|
| 172 |
except Exception as e:
|
| 173 |
logger.error(f"LLM name extraction failed: {e}")
|
frontend/app/settings/playbook/page.tsx
CHANGED
|
@@ -268,7 +268,10 @@ export default function PlaybookEditorPage() {
|
|
| 268 |
setGenerating(true)
|
| 269 |
try {
|
| 270 |
const result = await playbookApi.generateWithAI()
|
|
|
|
| 271 |
queryClient.invalidateQueries({ queryKey: ['playbook-stages'] })
|
|
|
|
|
|
|
| 272 |
toast.success('✨ Воронка создана!', result.message || `Сгенерировано ${result.stages?.length || 0} этапов`)
|
| 273 |
} catch (error: any) {
|
| 274 |
toast.error('Ошибка генерации', error.response?.data?.detail || 'Не удалось сгенерировать воронку')
|
|
@@ -298,9 +301,9 @@ export default function PlaybookEditorPage() {
|
|
| 298 |
<div className="min-h-full bg-[#0D0E18] p-6 relative overflow-hidden">
|
| 299 |
{/* Infinity Background - Matching other pages */}
|
| 300 |
<div className="absolute inset-0 pointer-events-none overflow-hidden -z-10">
|
| 301 |
-
<div className="absolute top-0 right-0 w-[60%] h-[40%] bg-gradient-to-bl from-purple-600/10 via-indigo-500/5 to-transparent blur-[
|
| 302 |
-
<div className="absolute bottom-0 left-0 w-[50%] h-[50%] bg-gradient-to-tr from-cyan-500/8 via-indigo-500/5 to-transparent blur-[
|
| 303 |
-
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[70%] h-[60%] bg-gradient-radial from-indigo-500/3 to-transparent blur-[
|
| 304 |
</div>
|
| 305 |
|
| 306 |
<div className="max-w-7xl mx-auto relative z-10">
|
|
|
|
| 268 |
setGenerating(true)
|
| 269 |
try {
|
| 270 |
const result = await playbookApi.generateWithAI()
|
| 271 |
+
// Invalidate all related caches to ensure new qualification_fields show up
|
| 272 |
queryClient.invalidateQueries({ queryKey: ['playbook-stages'] })
|
| 273 |
+
queryClient.invalidateQueries({ queryKey: ['playbook-custom-fields'] })
|
| 274 |
+
queryClient.invalidateQueries({ queryKey: ['ai-settings'] })
|
| 275 |
toast.success('✨ Воронка создана!', result.message || `Сгенерировано ${result.stages?.length || 0} этапов`)
|
| 276 |
} catch (error: any) {
|
| 277 |
toast.error('Ошибка генерации', error.response?.data?.detail || 'Не удалось сгенерировать воронку')
|
|
|
|
| 301 |
<div className="min-h-full bg-[#0D0E18] p-6 relative overflow-hidden">
|
| 302 |
{/* Infinity Background - Matching other pages */}
|
| 303 |
<div className="absolute inset-0 pointer-events-none overflow-hidden -z-10">
|
| 304 |
+
<div className="absolute top-0 right-0 w-[60%] h-[40%] bg-gradient-to-bl from-purple-600/10 via-indigo-500/5 to-transparent blur-[50px] rounded-full" />
|
| 305 |
+
<div className="absolute bottom-0 left-0 w-[50%] h-[50%] bg-gradient-to-tr from-cyan-500/8 via-indigo-500/5 to-transparent blur-[40px] rounded-full" />
|
| 306 |
+
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[70%] h-[60%] bg-gradient-radial from-indigo-500/3 to-transparent blur-[30px]" />
|
| 307 |
</div>
|
| 308 |
|
| 309 |
<div className="max-w-7xl mx-auto relative z-10">
|
frontend/components/settings/ProductSettings.tsx
CHANGED
|
@@ -203,8 +203,8 @@ export default function ProductSettings() {
|
|
| 203 |
</div>
|
| 204 |
)}
|
| 205 |
|
| 206 |
-
{/* Actions */}
|
| 207 |
-
<div className="absolute top-2 right-2 flex gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity">
|
| 208 |
<button
|
| 209 |
onClick={() => handleOpenModal(product)}
|
| 210 |
className="p-1.5 bg-black/60 backdrop-blur rounded-md text-white/80 hover:text-white"
|
|
|
|
| 203 |
</div>
|
| 204 |
)}
|
| 205 |
|
| 206 |
+
{/* Actions - Always visible on mobile, hover fade on desktop */}
|
| 207 |
+
<div className="absolute top-2 right-2 flex gap-1.5 md:opacity-0 md:group-hover:opacity-100 transition-opacity">
|
| 208 |
<button
|
| 209 |
onClick={() => handleOpenModal(product)}
|
| 210 |
className="p-1.5 bg-black/60 backdrop-blur rounded-md text-white/80 hover:text-white"
|
frontend/components/ui/switch.tsx
CHANGED
|
@@ -11,7 +11,7 @@ const Switch = React.forwardRef<
|
|
| 11 |
>(({ className, ...props }, ref) => (
|
| 12 |
<SwitchPrimitive.Root
|
| 13 |
className={cn(
|
| 14 |
-
"peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
|
| 15 |
className
|
| 16 |
)}
|
| 17 |
{...props}
|
|
|
|
| 11 |
>(({ className, ...props }, ref) => (
|
| 12 |
<SwitchPrimitive.Root
|
| 13 |
className={cn(
|
| 14 |
+
"peer inline-flex h-6 w-11 min-w-[44px] shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
|
| 15 |
className
|
| 16 |
)}
|
| 17 |
{...props}
|