#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
聊天机器人核心逻辑
作者: 赵小燕
"""
import random
import json
from utils import preprocess_text, match_pattern
class ChatBot:
def __init__(self):
# 加载聊天规则和回复
self.load_knowledge_base()
# 初始化对话历史
self.conversation_history = []
def load_knowledge_base(self):
"""加载知识库"""
try:
with open('data/knowledge_base.json', 'r', encoding='utf-8') as f:
self.knowledge_base = json.load(f)
except FileNotFoundError:
# 使用默认知识库
self.knowledge_base = {
"greetings": {
"patterns": ["你好", "嗨", "在吗", "您好", "hi", "hello"],
"responses": [
"你好!很高兴和你聊天。",
"嗨!有什么我能帮助你的吗?",
"你好呀!今天过得怎么样?"
]
},
"farewells": {
"patterns": ["再见", "拜拜", "下次见", "goodbye", "bye"],
"responses": [
"再见!希望很快能再次和你聊天。",
"拜拜!祝你有美好的一天。",
"下次见!"
]
},
"thanks": {
"patterns": ["谢谢", "感谢", "多谢", "thank"],
"responses": [
"不客气!",
"很高兴能帮到你!",
"随时为你服务!"
]
},
"fallback": {
"responses": [
"抱歉,我不太明白你的意思。",
"能换个说法吗?我没有理解。",
"这个问题有点复杂,我需要学习更多。"
]
}
}
def get_response(self, message):
"""根据用户输入生成回复"""
# 预处理用户输入
processed_input = preprocess_text(message)
# 记录对话历史
self.conversation_history.append({"user": message})
# 寻找匹配的规则
for intent, data in self.knowledge_base.items():
if intent == "fallback":
continue
if "patterns" in data:
for pattern in data["patterns"]:
if match_pattern(processed_input, pattern):
# 随机选择一个回复
response = random.choice(data["responses"])
self.conversation_history.append({"bot": response})
return response
# 没有找到匹配的规则,使用默认回复
fallback_response = random.choice(self.knowledge_base["fallback"]["responses"])
self.conversation_history.append({"bot": fallback_response})
return fallback_response