customer-support-chatbot / backend /knowledge_base.py
Hamza4100's picture
Upload 15 files
4a2c63e verified
import json
from pathlib import Path
from typing import Optional, Dict, List
class KnowledgeBase:
"""Simple FAQ retrieval system with keyword matching."""
def __init__(self, faq_path: str = "data/faq.json"):
self.faq_path = Path(faq_path)
self.faqs = []
self.load_faq()
def load_faq(self):
"""Load FAQ from JSON file."""
if self.faq_path.exists():
with open(self.faq_path, 'r') as f:
data = json.load(f)
self.faqs = data.get("faqs", [])
def retrieve_answer(self, user_message: str) -> Optional[Dict]:
"""
Retrieve relevant FAQ answer using keyword matching.
Args:
user_message: User's input message
Returns:
FAQ item with answer, or None if no match found
"""
user_message_lower = user_message.lower()
# Score FAQs based on keyword matches
scores = []
for faq in self.faqs:
keywords = faq.get("keywords", [])
matches = sum(1 for kw in keywords if kw.lower() in user_message_lower)
if matches > 0:
scores.append((faq, matches))
# Return FAQ with highest match score
if scores:
top_faq = max(scores, key=lambda x: x[1])[0]
return top_faq
return None
def get_all_faqs(self) -> List[Dict]:
"""Get all FAQs."""
return self.faqs