dialogue_manager.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. #! /usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # vim:fenc=utf-8
  4. from enum import Enum, auto
  5. from typing import Dict, List, Optional, Tuple, Any
  6. from datetime import datetime
  7. import time
  8. import logging
  9. import cozepy
  10. from chat_service import ChatServiceType
  11. from message import MessageType
  12. # from vector_memory_manager import VectorMemoryManager
  13. from structured_memory_manager import StructuredMemoryManager
  14. from user_manager import UserManager
  15. from prompt_templates import *
  16. # 配置日志
  17. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(funcName)s[%(lineno)d] - %(levelname)s - %(message)s')
  18. logger = logging.getLogger(__name__)
  19. class DummyVectorMemoryManager:
  20. def __init__(self, user_id):
  21. pass
  22. def add_to_memory(self, conversation):
  23. pass
  24. def retrieve_relevant_memories(self, query, k=3):
  25. return []
  26. class DialogueState(Enum):
  27. GREETING = auto() # 问候状态
  28. CHITCHAT = auto() # 闲聊状态
  29. CLARIFICATION = auto() # 澄清状态
  30. FAREWELL = auto() # 告别状态
  31. HUMAN_INTERVENTION = auto() # 人工介入状态
  32. MESSAGE_AGGREGATING = auto() # 等待消息状态
  33. class TimeContext(Enum):
  34. EARLY_MORNING = "清晨" # 清晨 (5:00-7:59)
  35. MORNING = "上午" # 上午 (8:00-11:59)
  36. NOON = "中午" # 中午 (12:00-13:59)
  37. AFTERNOON = "下午" # 下午 (14:00-17:59)
  38. EVENING = "晚上" # 晚上 (18:00-21:59)
  39. NIGHT = "深夜" # 夜晚 (22:00-4:59)
  40. def __init__(self, description):
  41. self.description = description
  42. class DialogueManager:
  43. def __init__(self, user_id: str, user_manager: UserManager):
  44. self.user_id = user_id
  45. self.user_manager = user_manager
  46. self.current_state = DialogueState.GREETING
  47. self.previous_state = None
  48. self.dialogue_history = []
  49. self.user_profile = self.user_manager.get_user_profile(user_id)
  50. self.last_interaction_time = 0
  51. self.consecutive_clarifications = 0
  52. self.complex_request_counter = 0
  53. self.human_intervention_triggered = False
  54. self.vector_memory = DummyVectorMemoryManager(user_id)
  55. self.message_aggregation_sec = 5
  56. self.unprocessed_messages = []
  57. def get_current_time_context(self) -> TimeContext:
  58. """获取当前时间上下文"""
  59. current_hour = datetime.now().hour
  60. if 5 <= current_hour < 8:
  61. return TimeContext.EARLY_MORNING
  62. elif 8 <= current_hour < 12:
  63. return TimeContext.MORNING
  64. elif 12 <= current_hour < 14:
  65. return TimeContext.NOON
  66. elif 14 <= current_hour < 18:
  67. return TimeContext.AFTERNOON
  68. elif 18 <= current_hour < 22:
  69. return TimeContext.EVENING
  70. else:
  71. return TimeContext.NIGHT
  72. def update_state(self, message: Dict) -> Tuple[DialogueState, str]:
  73. """根据用户消息更新对话状态,并返回下一条需处理的用户消息"""
  74. message_text = message.get('text', None)
  75. message_ts = message['timestamp']
  76. # 如果当前已经是人工介入状态,保持该状态
  77. if self.current_state == DialogueState.HUMAN_INTERVENTION:
  78. # 记录对话历史,但不改变状态
  79. self.dialogue_history.append({
  80. "role": "user",
  81. "content": message_text,
  82. "timestamp": int(time.time() * 1000),
  83. "state": self.current_state.name
  84. })
  85. return self.current_state, message_text
  86. # 检查是否处于消息聚合状态
  87. if self.current_state == DialogueState.MESSAGE_AGGREGATING:
  88. # 收到的是特殊定时触发的空消息,且在聚合中,且已经超时,恢复之前状态,继续处理
  89. if message['type'] == MessageType.AGGREGATION_TRIGGER \
  90. and message_ts - self.last_interaction_time > self.message_aggregation_sec * 1000:
  91. logging.debug("user_id: {}, last interaction time: {}".format(
  92. self.user_id, datetime.fromtimestamp(self.last_interaction_time / 1000)))
  93. self.current_state = self.previous_state
  94. else:
  95. # 非空消息,更新最后交互时间,保持消息聚合状态
  96. if message_text:
  97. self.unprocessed_messages.append(message_text)
  98. self.last_interaction_time = message_ts
  99. return self.current_state, message_text
  100. elif message['type'] != MessageType.AGGREGATION_TRIGGER and self.message_aggregation_sec > 0:
  101. # 收到有内容的用户消息,切换到消息聚合状态
  102. self.previous_state = self.current_state
  103. self.current_state = DialogueState.MESSAGE_AGGREGATING
  104. self.unprocessed_messages.append(message_text)
  105. # 更新最后交互时间
  106. if message_text:
  107. self.last_interaction_time = message_ts
  108. return self.current_state, message_text
  109. # 保存前一个状态
  110. self.previous_state = self.current_state
  111. # 检查是否长时间未交互(超过3小时)
  112. if self._get_hours_since_last_interaction() > 3:
  113. self.current_state = DialogueState.GREETING
  114. self.dialogue_history = [] # 重置对话历史
  115. self.consecutive_clarifications = 0 # 重置澄清计数
  116. self.complex_request_counter = 0 # 重置复杂请求计数
  117. # 获得未处理的聚合消息,并清空未处理队列
  118. if message_text:
  119. self.unprocessed_messages.append(message_text)
  120. if self.unprocessed_messages:
  121. message_text = '\n'.join(self.unprocessed_messages)
  122. self.unprocessed_messages.clear()
  123. # 根据消息内容和当前状态确定新状态
  124. new_state = self._determine_state_from_message(message_text)
  125. # 处理连续澄清的情况
  126. if new_state == DialogueState.CLARIFICATION:
  127. self.consecutive_clarifications += 1
  128. if self.consecutive_clarifications >= 2:
  129. new_state = DialogueState.HUMAN_INTERVENTION
  130. # self._trigger_human_intervention("连续多次澄清请求")
  131. else:
  132. self.consecutive_clarifications = 0
  133. # 更新状态
  134. self.current_state = new_state
  135. # 更新最后交互时间
  136. if message_text:
  137. self.last_interaction_time = message_ts
  138. # 记录对话历史
  139. if message_text:
  140. self.dialogue_history.append({
  141. "role": "user",
  142. "content": message_text,
  143. "timestamp": int(time.time() * 1000),
  144. "state": self.current_state.name
  145. })
  146. return self.current_state, message_text
  147. def _determine_state_from_message(self, message: str) -> DialogueState:
  148. """根据消息内容确定对话状态"""
  149. if not message:
  150. return self.current_state
  151. # 简单的规则-关键词匹配
  152. message_lower = message.lower()
  153. # 判断是否是复杂请求
  154. complex_request_keywords = ["帮我", "怎么办", "我需要", "麻烦你", "请帮助", "急", "紧急"]
  155. if any(keyword in message_lower for keyword in complex_request_keywords):
  156. self.complex_request_counter += 1
  157. # 如果检测到困难请求且计数达到阈值,触发人工介入
  158. if self.complex_request_counter >= 1:
  159. # self._trigger_human_intervention("检测到复杂请求")
  160. return DialogueState.HUMAN_INTERVENTION
  161. else:
  162. # 如果不是复杂请求,重置计数器
  163. self.complex_request_counter = 0
  164. # 问候检测
  165. greeting_keywords = ["你好", "早上好", "中午好", "晚上好", "嗨", "在吗"]
  166. if any(keyword in message_lower for keyword in greeting_keywords):
  167. return DialogueState.GREETING
  168. # 告别检测
  169. farewell_keywords = ["再见", "拜拜", "晚安", "明天见", "回头见"]
  170. if any(keyword in message_lower for keyword in farewell_keywords):
  171. return DialogueState.FAREWELL
  172. # 澄清请求
  173. clarification_keywords = ["没明白", "不明白", "没听懂", "不懂", "什么意思", "再说一遍"]
  174. if any(keyword in message_lower for keyword in clarification_keywords):
  175. return DialogueState.CLARIFICATION
  176. # 默认为闲聊状态
  177. return DialogueState.CHITCHAT
  178. def _trigger_human_intervention(self, reason: str) -> None:
  179. """触发人工介入"""
  180. if not self.human_intervention_triggered:
  181. self.human_intervention_triggered = True
  182. # 记录人工介入事件
  183. event = {
  184. "timestamp": int(time.time() * 1000),
  185. "reason": reason,
  186. "dialogue_context": self.dialogue_history[-5:] if len(self.dialogue_history) >= 5 else self.dialogue_history
  187. }
  188. # 更新用户资料中的人工介入历史
  189. if "human_intervention_history" not in self.user_profile:
  190. self.user_profile["human_intervention_history"] = []
  191. self.user_profile["human_intervention_history"].append(event)
  192. self.user_manager.save_user_profile(self.user_profile)
  193. # 发送告警
  194. self._send_human_intervention_alert(reason)
  195. def _send_human_intervention_alert(self, reason: str) -> None:
  196. alert_message = f"""
  197. 人工介入告警
  198. 用户ID: {self.user_id}
  199. 用户昵称: {self.user_profile.get("nickname", "未知")}
  200. 时间: {int(time.time() * 1000)}
  201. 原因: {reason}
  202. 最近对话:
  203. """
  204. # 添加最近的对话记录
  205. recent_dialogues = self.dialogue_history[-5:] if len(self.dialogue_history) >= 5 else self.dialogue_history
  206. for dialogue in recent_dialogues:
  207. alert_message += f"\n{dialogue['role']}: {dialogue['content']}"
  208. # TODO(zhoutian): 实现发送告警的具体逻辑
  209. logger.warning(alert_message)
  210. def resume_from_human_intervention(self) -> None:
  211. """从人工介入状态恢复"""
  212. if self.current_state == DialogueState.HUMAN_INTERVENTION:
  213. self.current_state = DialogueState.GREETING
  214. self.human_intervention_triggered = False
  215. self.consecutive_clarifications = 0
  216. self.complex_request_counter = 0
  217. # 记录恢复事件
  218. self.dialogue_history.append({
  219. "role": "system",
  220. "content": "已从人工介入状态恢复到自动对话",
  221. "timestamp": int(time.time() * 1000),
  222. "state": self.current_state.name
  223. })
  224. def generate_response(self, llm_response: str) -> Optional[str]:
  225. """根据当前状态处理LLM响应,如果处于人工介入状态则返回None"""
  226. # 如果处于人工介入状态,不生成回复
  227. if self.current_state == DialogueState.HUMAN_INTERVENTION:
  228. return None
  229. # 记录响应到对话历史
  230. current_ts = int(time.time() * 1000)
  231. self.dialogue_history.append({
  232. "role": "assistant",
  233. "content": llm_response,
  234. "timestamp": current_ts,
  235. "state": self.current_state.name
  236. })
  237. self.last_interaction_time = current_ts
  238. return llm_response
  239. def _get_hours_since_last_interaction(self, precision: int = -1):
  240. time_diff = (time.time() * 1000) - self.last_interaction_time
  241. hours_passed = time_diff / 1000 / 3600
  242. if precision >= 0:
  243. return round(hours_passed, precision)
  244. return hours_passed
  245. def should_initiate_conversation(self) -> bool:
  246. """判断是否应该主动发起对话"""
  247. # 如果处于人工介入状态,不应主动发起对话
  248. if self.current_state == DialogueState.HUMAN_INTERVENTION:
  249. return False
  250. hours_passed = self._get_hours_since_last_interaction()
  251. # 获取当前时间上下文
  252. time_context = self.get_current_time_context()
  253. # 根据用户交互频率偏好设置不同的阈值
  254. interaction_frequency = self.user_profile.get("interaction_frequency", "medium")
  255. # 设置不同偏好的交互时间阈值(小时)
  256. thresholds = {
  257. "low": 24, # 低频率:一天一次
  258. "medium": 12, # 中频率:半天一次
  259. "high": 6 # 高频率:大约6小时一次
  260. }
  261. threshold = thresholds.get(interaction_frequency, 12)
  262. # 如果足够时间已经过去
  263. if hours_passed >= threshold:
  264. # 根据时间上下文决定主动交互的状态
  265. if time_context in [TimeContext.EARLY_MORNING, TimeContext.MORNING,
  266. TimeContext.NOON, TimeContext.AFTERNOON,
  267. TimeContext.EVENING]:
  268. return True
  269. return False
  270. def is_in_human_intervention(self) -> bool:
  271. """检查是否处于人工介入状态"""
  272. return self.current_state == DialogueState.HUMAN_INTERVENTION
  273. def get_prompt_context(self, user_message) -> Dict:
  274. # 获取当前时间上下文
  275. time_context = self.get_current_time_context()
  276. context = {
  277. "user_profile": self.user_profile,
  278. "current_state": self.current_state.name,
  279. "previous_state": self.previous_state.name if self.previous_state else None,
  280. "current_time_period": time_context.description,
  281. # "dialogue_history": self.dialogue_history[-10:],
  282. "last_interaction_interval": self._get_hours_since_last_interaction(2),
  283. "if_first_interaction": False,
  284. "if_active_greeting": False if user_message else True
  285. }
  286. # 获取长期记忆
  287. relevant_memories = self.vector_memory.retrieve_relevant_memories(user_message)
  288. context["long_term_memory"] = {
  289. "relevant_conversations": relevant_memories
  290. }
  291. return context
  292. def _select_prompt(self, state):
  293. state_to_prompt_map = {
  294. DialogueState.GREETING: GENERAL_GREETING_PROMPT,
  295. DialogueState.CHITCHAT: GENERAL_GREETING_PROMPT,
  296. }
  297. return state_to_prompt_map[state]
  298. def _select_coze_bot(self, state):
  299. state_to_bot_map = {
  300. DialogueState.GREETING: '7479005417885417487',
  301. DialogueState.CHITCHAT: '7479005417885417487'
  302. }
  303. return state_to_bot_map[state]
  304. def _create_system_message(self, prompt_context):
  305. prompt_template = self._select_prompt(self.current_state)
  306. prompt = prompt_template.format(**prompt_context['user_profile'], **prompt_context)
  307. return {'role': 'system', 'content': prompt}
  308. def build_chat_configuration(
  309. self,
  310. user_message: Optional[str] = None,
  311. chat_service_type: ChatServiceType = ChatServiceType.OPENAI_COMPATIBLE
  312. ) -> Dict:
  313. """
  314. 参数:
  315. user_message: 当前用户消息,如果是主动交互则为None
  316. 返回:
  317. 消息列表
  318. """
  319. dialogue_history = self.dialogue_history[-10:] \
  320. if len(self.dialogue_history) > 10 \
  321. else self.dialogue_history
  322. messages = []
  323. config = {}
  324. prompt_context = self.get_prompt_context(user_message)
  325. if chat_service_type == ChatServiceType.OPENAI_COMPATIBLE:
  326. system_message = self._create_system_message(prompt_context)
  327. messages.append(system_message)
  328. for entry in dialogue_history:
  329. role = entry['role']
  330. messages.append({
  331. "role": role,
  332. "content": entry["content"]
  333. })
  334. elif chat_service_type == ChatServiceType.COZE_CHAT:
  335. for entry in dialogue_history:
  336. role = entry['role']
  337. if role == 'user':
  338. messages.append(cozepy.Message.build_user_question_text(entry["content"]))
  339. elif role == 'assistant':
  340. messages.append(cozepy.Message.build_assistant_answer(entry['content']))
  341. custom_variables = {}
  342. for k, v in prompt_context.items():
  343. custom_variables[k] = str(v)
  344. config['custom_variables'] = custom_variables
  345. config['bot_id'] = self._select_coze_bot(self.current_state)
  346. config['messages'] = messages
  347. return config