Spaces:
Sleeping
Sleeping
axeronis commited on
Commit ·
d9eef76
1
Parent(s): b82c62a
fix: resolve AI intelligence regression (prompt order + cache bug)
Browse filesFiles changed (2)
312 unmodified lines313314315316317318319312 unmodified linesawait session.commit()# SIGNAL: Invalidate AI Memoryawait get_memory_manager().invalidate_memory(session, current_user.tenant_id)return {"ok": True,312 unmodified lines313314315316317318319320321312 unmodified linesawait session.commit()# SIGNAL: Invalidate AI Memorytenant = await session.get(Tenant, tenant_id)if tenant:await get_memory_manager().invalidate_memory(session, tenant)return {"ok": True,
169 unmodified lines1701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492506 unmodified lines2572582592602612622632642652662672687 unmodified lines276277278279280281282283284169 unmodified lines# C. BANNED WORDSbanned_text = f"🚫 ЗАПРЕЩЕНО использовать слова: {', '.join(banned_words)}" if banned_words else ""context = f"""═══════════════════════════════════════════════════════════════[🚨 КРИТИЧЕСКИЕ ПРАВИЛА - ОБЯЗАТЕЛЬНО СОБЛЮДАТЬ]═══════════════════════════════════════════════════════════════1️⃣ ТЫ: {bot_name} в компании {company}.2️⃣ ТОН ОБЩЕНИЯ: {tone}{tone_detail}3️⃣ БАЗА ЗНАНИЙ (СТРОГО!):- Отвечай ТОЛЬКО на основе [KNOWLEDGE BASE] ниже- Если информации НЕТ → скажи "К сожалению, у меня нет этой информации. Менеджер свяжется с вами."- НИКОГДА не придумывай цены, даты, факты!- НЕ отвечай на вопросы не по теме (погода, рецепты, и т.д.){f"4️⃣ МЕТОДОЛОГИЯ: {methodology}" if methodology else ""}{banned_text}{f"5️⃣ ОСОБЫЕ ИНСТРУКЦИИ: {custom_instructions}" if custom_instructions else ""}{f"6️⃣ ИДЕАЛЬНЫЙ КЛИЕНТ: {ideal_customer}" if ideal_customer else ""}═══════════════════════════════════════════════════════════════[📅 СИСТЕМА ЗАПИСИ]═══════════════════════════════════════════════════════════════Если клиент хочет записаться на встречу/консультацию:1. Уточни удобную дату и время2. Подтверди запись специальным тегом: [BOOK_CONFIRMED: YYYY-MM-DD HH:MM]Пример: [BOOK_CONFIRMED: 2025-12-25 14:00]═══════════════════════════════════════════════════════════════[BOT IDENTITY]═══════════════════════════════════════════════════════════════Имя: {bot_name}Компания: {company}"""# C. KNOWLEDGE BASEstmt = select(KnowledgeBase).where(KnowledgeBase.tenant_id == tenant.id,KnowledgeBase.is_active == True)kb_results = await session.execute(stmt)kb_items = kb_results.scalars().all()if kb_items:context += "\n\n═══════════════════════════════════════════════════════════════\n"context += "[KNOWLEDGE BASE - ЕДИНСТВЕННЫЙ ИСТОЧНИК ПРАВДЫ]\n"context += "═══════════════════════════════════════════════════════════════\n"for item in kb_items:context += f"Категория: {item.category}\nСодержание: {item.content_chunk}\n---\n"else:context += "\n\n[KNOWLEDGE BASE]\n(Пусто - база знаний не заполнена)\n"# D. PRODUCT CATALOGstmt_prod = select(Product).where(Product.tenant_id == tenant.id,Product.is_active == True)prod_results = await session.execute(stmt_prod)products = prod_results.scalars().all()if products:context += "\n\n═══════════════════════════════════════════════════════════════\n"context += "[PRODUCT CATALOG]\n"context += "═══════════════════════════════════════════════════════════════\n"for p in products:context += f"Товар: {p.name}\n"context += f"Цена: {p.price} {p.currency}\n"if p.description:context += f"Описание: {p.description}\n"if p.image_url:context += f"Фото: {p.image_url}\n"context += "---\n"# E. TRAINING EXAMPLES6 unmodified linestraining_examples = train_results.scalars().all()if training_examples:context += "\n\n📚 ПРИМЕРЫ ОТВЕТОВ (так нужно отвечать):\n"for i, ex in enumerate(training_examples, 1):context += f"Пример {i}:\n"context += f"Клиент: {ex.user_input}\n"context += f"Ты: {ex.ideal_response}\n"context += "---\n"# F. LEARNING RULESstmt_rules = select(AILearningRule).where(7 unmodified linesif learning_rules:context += "\n\n📜 ДОПОЛНИТЕЛЬНЫЕ ПРАВИЛА:\n"for rule in learning_rules:context += f"ПРАВИЛО: {rule.rule_name}\n"context += f"Инструкция: {rule.instruction}\n"context += "---\n"# G. REMINDER AT THE END (LLM remembers start and end best)context += f"""169 unmodified lines1701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232246 unmodified lines2312322332342352362372382392402412422432442452462472482492502512522532542552562572582592607 unmodified lines268269270271272273274169 unmodified lines# C. BANNED WORDSbanned_text = f"🚫 ЗАПРЕЩЕНО использовать слова: {', '.join(banned_words)}" if banned_words else ""# --- NEW PROMPT STRUCTURE FOR BETTER RECALL ---# 1. Identity & Tone# 2. Booking System# 3. Product Catalog# 4. Training Examples# 5. KNOWLEDGE BASE (Crucial - Moved to End)# 6. Final Rulescontext = f"""═══════════════════════════════════════════════════════════════[1️⃣ ИДЕНТИЧНОСТЬ]═══════════════════════════════════════════════════════════════Ты: {bot_name} из {company}.Тон: {tone} ({tone_detail}){f"Цель: {methodology}" if methodology else ""}{f"Инфо о клиенте: {ideal_customer}" if ideal_customer else ""}{f"Доп. инструкции: {custom_instructions}" if custom_instructions else ""}═══════════════════════════════════════════════════════════════[2️⃣ СИСТЕМА ЗАПИСИ И ЗАКАЗОВ]═══════════════════════════════════════════════════════════════• Если клиент хочет записаться на встречу:1. Спроси дату и время.2. Подтверди: [BOOK_CONFIRMED: YYYY-MM-DD HH:MM]• Если клиент хочет купить товар:Предложи оформить заказ."""# D. PRODUCT CATALOGstmt_prod = select(Product).where(Product.tenant_id == tenant.id,Product.is_active == True # Only active products)prod_results = await session.execute(stmt_prod)products = prod_results.scalars().all()if products:context += "\n═══════════════════════════════════════════════════════════════\n"context += "[3️⃣ КАТАЛОГ ТОВАРОВ]\n"context += "═══════════════════════════════════════════════════════════════\n"for p in products:# Only show products in stock instructions? (Optional)context += f"• {p.name} | Цена: {p.price} {p.currency}\n"if p.description:context += f" Описание: {p.description}\n"# Only include photo URL if validif p.image_url and "http" in p.image_url:context += f" Фото: {p.image_url}\n"context += "---\n"# E. TRAINING EXAMPLES6 unmodified linestraining_examples = train_results.scalars().all()if training_examples:context += "\n═══════════════════════════════════════════════════════════════\n"context += "[4️⃣ ПРИМЕРЫ ДИАЛОГОВ (Обучение)]\n"context += "═══════════════════════════════════════════════════════════════\n"for i, ex in enumerate(training_examples, 1):context += f"Ввод: {ex.user_input}\n"context += f"Ответ: {ex.ideal_response}\n---\n"# C. KNOWLEDGE BASE (MOVED TO END FOR ATTENTION)stmt = select(KnowledgeBase).where(KnowledgeBase.tenant_id == tenant.id,KnowledgeBase.is_active == True)kb_results = await session.execute(stmt)kb_items = kb_results.scalars().all()context += "\n═══════════════════════════════════════════════════════════════\n"context += "[5️⃣ БАЗА ЗНАНИЙ - ЕДИНСТВЕННЫЙ ИСТОЧНИК ПРАВДЫ]\n"context += "═══════════════════════════════════════════════════════════════\n"if kb_items:for item in kb_items:context += f"[{item.category.upper()}]\n{item.content_chunk}\n---\n"else:context += "(База знаний пуста)\n"# F. LEARNING RULESstmt_rules = select(AILearningRule).where(7 unmodified linesif learning_rules:context += "\n\n📜 ДОПОЛНИТЕЛЬНЫЕ ПРАВИЛА:\n"for rule in learning_rules:context += f"ПРАВИЛО: {rule.rule_name}: {rule.instruction}\n"# G. REMINDER AT THE END (LLM remembers start and end best)context += f"""
backend/app/api/knowledge.py+3-1
backend/app/services/ai_memory_manager.py+53-63