dialogue_manager.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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 pymysql.cursors
  10. import configs
  11. import cozepy
  12. from database import MySQLManager
  13. from history_dialogue_service import HistoryDialogueService
  14. from chat_service import ChatServiceType
  15. from message import MessageType, Message
  16. # from vector_memory_manager import VectorMemoryManager
  17. from structured_memory_manager import StructuredMemoryManager
  18. from user_manager import UserManager
  19. from prompt_templates import *
  20. # 配置日志
  21. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(funcName)s[%(lineno)d] - %(levelname)s - %(message)s')
  22. logger = logging.getLogger(__name__)
  23. class DummyVectorMemoryManager:
  24. def __init__(self, user_id):
  25. pass
  26. def add_to_memory(self, conversation):
  27. pass
  28. def retrieve_relevant_memories(self, query, k=3):
  29. return []
  30. class DialogueState(int, Enum):
  31. INITIALIZED = 0
  32. GREETING = 1 # 问候状态
  33. CHITCHAT = 2 # 闲聊状态
  34. CLARIFICATION = 3 # 澄清状态
  35. FAREWELL = 4 # 告别状态
  36. HUMAN_INTERVENTION = 5 # 人工介入状态
  37. MESSAGE_AGGREGATING = 6 # 等待消息状态
  38. class TimeContext(Enum):
  39. EARLY_MORNING = "清晨" # 清晨 (5:00-7:59)
  40. MORNING = "上午" # 上午 (8:00-11:59)
  41. NOON = "中午" # 中午 (12:00-13:59)
  42. AFTERNOON = "下午" # 下午 (14:00-17:59)
  43. EVENING = "晚上" # 晚上 (18:00-21:59)
  44. NIGHT = "深夜" # 夜晚 (22:00-4:59)
  45. def __init__(self, description):
  46. self.description = description
  47. class DialogueStateCache:
  48. def __init__(self):
  49. config = configs.get()
  50. self.db = MySQLManager(config['storage']['agent_state']['mysql'])
  51. self.table = config['storage']['agent_state']['table']
  52. def get_state(self, staff_id: str, user_id: str) -> Tuple[DialogueState, DialogueState]:
  53. query = f"SELECT current_state, previous_state FROM {self.table} WHERE staff_id=%s AND user_id=%s"
  54. data = self.db.select(query, pymysql.cursors.DictCursor, (staff_id, user_id))
  55. if not data:
  56. logging.warning(f"staff[{staff_id}], user[{user_id}]: agent state not found")
  57. state = DialogueState.CHITCHAT
  58. previous_state = DialogueState.INITIALIZED
  59. self.set_state(staff_id, user_id, state, previous_state)
  60. else:
  61. state = DialogueState(data[0]['current_state'])
  62. previous_state = DialogueState(data[0]['previous_state'])
  63. return state, previous_state
  64. def set_state(self, staff_id: str, user_id: str, state: DialogueState, previous_state: DialogueState):
  65. query = f"INSERT INTO {self.table} (staff_id, user_id, current_state, previous_state)" \
  66. f" VALUES (%s, %s, %s, %s) " \
  67. f"ON DUPLICATE KEY UPDATE current_state=%s, previous_state=%s"
  68. self.db.execute(query, (staff_id, user_id, state.value, previous_state.value, state.value, previous_state.value))
  69. class DialogueManager:
  70. def __init__(self, staff_id: str, user_id: str, user_manager: UserManager, state_cache: DialogueStateCache):
  71. config = configs.get()
  72. self.staff_id = staff_id
  73. self.user_id = user_id
  74. self.user_manager = user_manager
  75. self.state_cache = state_cache
  76. self.current_state = DialogueState.GREETING
  77. self.previous_state = DialogueState.INITIALIZED
  78. # 目前实际仅用作调试,拼装prompt时使用history_dialogue_service获取
  79. self.dialogue_history = []
  80. self.user_profile = self.user_manager.get_user_profile(user_id)
  81. self.staff_profile = self.user_manager.get_staff_profile(staff_id)
  82. self.last_interaction_time = 0
  83. self.consecutive_clarifications = 0
  84. self.complex_request_counter = 0
  85. self.human_intervention_triggered = False
  86. self.vector_memory = DummyVectorMemoryManager(user_id)
  87. self.message_aggregation_sec = config.get('message_aggregation_sec', 5)
  88. self.unprocessed_messages = []
  89. self.history_dialogue_service = HistoryDialogueService(
  90. config['storage']['history_dialogue']['api_base_url']
  91. )
  92. self._recover_state()
  93. def _recover_state(self):
  94. self.current_state, self.previous_state = self.state_cache.get_state(self.staff_id, self.user_id)
  95. # 从数据库恢复对话状态
  96. last_message = self.history_dialogue_service.get_dialogue_history(self.staff_id, self.user_id, 1)
  97. if last_message:
  98. self.last_interaction_time = last_message[0]['timestamp']
  99. else:
  100. # 默认设置为24小时前
  101. self.last_interaction_time = int(time.time() * 1000) - 24 * 3600 * 1000
  102. time_for_read = datetime.fromtimestamp(self.last_interaction_time / 1000).strftime("%Y-%m-%d %H:%M:%S")
  103. logging.debug(f"staff[{self.staff_id}], user[{self.user_id}]: state: {self.current_state.name}, last_interaction: {time_for_read}")
  104. def persist_state(self):
  105. """持久化对话状态"""
  106. self.state_cache.set_state(self.staff_id, self.user_id, self.current_state, self.previous_state)
  107. @staticmethod
  108. def get_current_time_context() -> TimeContext:
  109. """获取当前时间上下文"""
  110. current_hour = datetime.now().hour
  111. if 5 <= current_hour < 8:
  112. return TimeContext.EARLY_MORNING
  113. elif 8 <= current_hour < 12:
  114. return TimeContext.MORNING
  115. elif 12 <= current_hour < 14:
  116. return TimeContext.NOON
  117. elif 14 <= current_hour < 18:
  118. return TimeContext.AFTERNOON
  119. elif 18 <= current_hour < 22:
  120. return TimeContext.EVENING
  121. else:
  122. return TimeContext.NIGHT
  123. def update_state(self, message: Message) -> Tuple[bool, Optional[str]]:
  124. """根据用户消息更新对话状态,并返回是否需要发起回复 及下一条需处理的用户消息"""
  125. message_text = message.content
  126. message_ts = message.sendTime
  127. # 如果当前已经是人工介入状态,保持该状态
  128. if self.current_state == DialogueState.HUMAN_INTERVENTION:
  129. # 记录对话历史,但不改变状态
  130. self.dialogue_history.append({
  131. "role": "user",
  132. "content": message_text,
  133. "timestamp": int(time.time() * 1000),
  134. "state": self.current_state.name
  135. })
  136. return False, message_text
  137. # 检查是否处于消息聚合状态
  138. if self.current_state == DialogueState.MESSAGE_AGGREGATING:
  139. # 收到的是特殊定时触发的空消息,且在聚合中,且已经超时,恢复之前状态,继续处理
  140. if message.type == MessageType.AGGREGATION_TRIGGER \
  141. and message_ts - self.last_interaction_time > self.message_aggregation_sec * 1000:
  142. logging.debug("user_id: {}, last interaction time: {}".format(
  143. self.user_id, datetime.fromtimestamp(self.last_interaction_time / 1000)))
  144. self.current_state = self.previous_state
  145. else:
  146. # 非空消息,更新最后交互时间,保持消息聚合状态
  147. if message_text:
  148. self.unprocessed_messages.append(message_text)
  149. self.last_interaction_time = message_ts
  150. return False, message_text
  151. else:
  152. if message.type == MessageType.AGGREGATION_TRIGGER:
  153. # 未在聚合状态中,收到的聚合触发消息为过时消息,不应当处理
  154. return False, None
  155. if message.type != MessageType.AGGREGATION_TRIGGER and self.message_aggregation_sec > 0:
  156. # 收到有内容的用户消息,切换到消息聚合状态
  157. self.previous_state = self.current_state
  158. self.current_state = DialogueState.MESSAGE_AGGREGATING
  159. self.unprocessed_messages.append(message_text)
  160. # 更新最后交互时间
  161. if message_text:
  162. self.last_interaction_time = message_ts
  163. self.persist_state()
  164. return False, message_text
  165. # 保存前一个状态
  166. self.previous_state = self.current_state
  167. # 检查是否长时间未交互(超过3小时)
  168. if self._get_hours_since_last_interaction() > 3:
  169. self.current_state = DialogueState.GREETING
  170. self.dialogue_history = [] # 重置对话历史
  171. self.consecutive_clarifications = 0 # 重置澄清计数
  172. self.complex_request_counter = 0 # 重置复杂请求计数
  173. # 获得未处理的聚合消息,并清空未处理队列
  174. if message_text:
  175. self.unprocessed_messages.append(message_text)
  176. if self.unprocessed_messages:
  177. message_text = '\n'.join(self.unprocessed_messages)
  178. self.unprocessed_messages.clear()
  179. # 根据消息内容和当前状态确定新状态
  180. new_state = self._determine_state_from_message(message_text)
  181. # 处理连续澄清的情况
  182. if new_state == DialogueState.CLARIFICATION:
  183. self.consecutive_clarifications += 1
  184. if self.consecutive_clarifications >= 2:
  185. new_state = DialogueState.HUMAN_INTERVENTION
  186. # self._trigger_human_intervention("连续多次澄清请求")
  187. else:
  188. self.consecutive_clarifications = 0
  189. # 更新状态并持久化
  190. self.current_state = new_state
  191. self.persist_state()
  192. # 更新最后交互时间
  193. if message_text:
  194. self.last_interaction_time = message_ts
  195. # 记录对话历史
  196. if message_text:
  197. self.dialogue_history.append({
  198. "role": "user",
  199. "content": message_text,
  200. "timestamp": message_ts,
  201. "state": self.current_state.name
  202. })
  203. return True, message_text
  204. def _determine_state_from_message(self, message_text: Optional[str]) -> DialogueState:
  205. """根据消息内容确定对话状态"""
  206. if not message_text:
  207. return self.current_state
  208. # 简单的规则-关键词匹配
  209. message_lower = message_text.lower()
  210. # 判断是否是复杂请求
  211. complex_request_keywords = ["帮我", "怎么办", "我需要", "麻烦你", "请帮助", "急", "紧急"]
  212. if any(keyword in message_lower for keyword in complex_request_keywords):
  213. self.complex_request_counter += 1
  214. # 如果检测到困难请求且计数达到阈值,触发人工介入
  215. if self.complex_request_counter >= 1:
  216. # self._trigger_human_intervention("检测到复杂请求")
  217. return DialogueState.HUMAN_INTERVENTION
  218. else:
  219. # 如果不是复杂请求,重置计数器
  220. self.complex_request_counter = 0
  221. # 问候检测
  222. greeting_keywords = ["你好", "早上好", "中午好", "晚上好", "嗨", "在吗"]
  223. if any(keyword in message_lower for keyword in greeting_keywords):
  224. return DialogueState.GREETING
  225. # 告别检测
  226. farewell_keywords = ["再见", "拜拜", "晚安", "明天见", "回头见"]
  227. if any(keyword in message_lower for keyword in farewell_keywords):
  228. return DialogueState.FAREWELL
  229. # 澄清请求
  230. clarification_keywords = ["没明白", "不明白", "没听懂", "不懂", "什么意思", "再说一遍"]
  231. if any(keyword in message_lower for keyword in clarification_keywords):
  232. return DialogueState.CLARIFICATION
  233. # 默认为闲聊状态
  234. return DialogueState.CHITCHAT
  235. def _trigger_human_intervention(self, reason: str) -> None:
  236. """触发人工介入"""
  237. if not self.human_intervention_triggered:
  238. self.human_intervention_triggered = True
  239. # 记录人工介入事件
  240. event = {
  241. "timestamp": int(time.time() * 1000),
  242. "reason": reason,
  243. "dialogue_context": self.history_dialogue_service.get_dialogue_history(self.staff_id, self.user_id, 5)
  244. }
  245. # 更新用户资料中的人工介入历史
  246. if "human_intervention_history" not in self.user_profile:
  247. self.user_profile["human_intervention_history"] = []
  248. self.user_profile["human_intervention_history"].append(event)
  249. self.user_manager.save_user_profile(self.user_id, self.user_profile)
  250. # 发送告警
  251. self._send_human_intervention_alert(reason)
  252. def _send_human_intervention_alert(self, reason: str) -> None:
  253. alert_message = f"""
  254. 人工介入告警
  255. 用户ID: {self.user_id}
  256. 用户昵称: {self.user_profile.get("nickname", "未知")}
  257. 时间: {int(time.time() * 1000)}
  258. 原因: {reason}
  259. 最近对话:
  260. """
  261. # 添加最近的对话记录
  262. recent_dialogues = self.history_dialogue_service.get_dialogue_history(self.staff_id, self.user_id, 5)
  263. for dialogue in recent_dialogues:
  264. alert_message += f"\n{dialogue['role']}: {dialogue['content']}"
  265. # TODO(zhoutian): 实现发送告警的具体逻辑
  266. logger.warning(alert_message)
  267. def resume_from_human_intervention(self) -> None:
  268. """从人工介入状态恢复"""
  269. if self.current_state == DialogueState.HUMAN_INTERVENTION:
  270. self.current_state = DialogueState.GREETING
  271. self.human_intervention_triggered = False
  272. self.consecutive_clarifications = 0
  273. self.complex_request_counter = 0
  274. # 记录恢复事件
  275. self.dialogue_history.append({
  276. "role": "system",
  277. "content": "已从人工介入状态恢复到自动对话",
  278. "timestamp": int(time.time() * 1000),
  279. "state": self.current_state.name
  280. })
  281. def generate_response(self, llm_response: str) -> Optional[str]:
  282. """根据当前状态处理LLM响应,如果处于人工介入状态则返回None"""
  283. # 如果处于人工介入状态,不生成回复
  284. if self.current_state == DialogueState.HUMAN_INTERVENTION:
  285. return None
  286. # 记录响应到对话历史
  287. current_ts = int(time.time() * 1000)
  288. self.dialogue_history.append({
  289. "role": "assistant",
  290. "content": llm_response,
  291. "timestamp": current_ts,
  292. "state": self.current_state.name
  293. })
  294. self.last_interaction_time = current_ts
  295. return llm_response
  296. def _get_hours_since_last_interaction(self, precision: int = -1):
  297. time_diff = (time.time() * 1000) - self.last_interaction_time
  298. hours_passed = time_diff / 1000 / 3600
  299. if precision >= 0:
  300. return round(hours_passed, precision)
  301. return hours_passed
  302. def should_initiate_conversation(self) -> bool:
  303. """判断是否应该主动发起对话"""
  304. # 如果处于人工介入状态,不应主动发起对话
  305. if self.current_state == DialogueState.HUMAN_INTERVENTION:
  306. return False
  307. hours_passed = self._get_hours_since_last_interaction()
  308. # 获取当前时间上下文
  309. time_context = self.get_current_time_context()
  310. # 根据用户交互频率偏好设置不同的阈值
  311. interaction_frequency = self.user_profile.get("interaction_frequency", "medium")
  312. # 设置不同偏好的交互时间阈值(小时)
  313. thresholds = {
  314. "low": 24, # 低频率:一天一次
  315. "medium": 12, # 中频率:半天一次
  316. "high": 6 # 高频率:大约6小时一次
  317. }
  318. threshold = thresholds.get(interaction_frequency, 12)
  319. if hours_passed < threshold:
  320. return False
  321. # 根据时间上下文决定主动交互的状态
  322. if time_context in [TimeContext.EARLY_MORNING, TimeContext.MORNING,
  323. TimeContext.NOON, TimeContext.AFTERNOON,
  324. TimeContext.EVENING]:
  325. self.previous_state = self.current_state
  326. self.current_state = DialogueState.GREETING
  327. self.persist_state()
  328. return True
  329. return False
  330. def is_in_human_intervention(self) -> bool:
  331. """检查是否处于人工介入状态"""
  332. return self.current_state == DialogueState.HUMAN_INTERVENTION
  333. def get_prompt_context(self, user_message) -> Dict:
  334. # 获取当前时间上下文
  335. time_context = self.get_current_time_context()
  336. # 刷新用户画像
  337. self.user_profile = self.user_manager.get_user_profile(self.user_id)
  338. # 刷新员工画像(不一定需要)
  339. self.staff_profile = self.user_manager.get_staff_profile(self.staff_id)
  340. context = {
  341. "user_profile": self.user_profile,
  342. "current_state": self.current_state.name,
  343. "previous_state": self.previous_state.name,
  344. "current_time_period": time_context.description,
  345. # "dialogue_history": self.dialogue_history[-10:],
  346. "last_interaction_interval": self._get_hours_since_last_interaction(2),
  347. "if_first_interaction": False,
  348. "if_active_greeting": False if user_message else True,
  349. **self.user_profile,
  350. **self.staff_profile
  351. }
  352. # 获取长期记忆
  353. relevant_memories = self.vector_memory.retrieve_relevant_memories(user_message)
  354. context["long_term_memory"] = {
  355. "relevant_conversations": relevant_memories
  356. }
  357. return context
  358. def _select_prompt(self, state):
  359. state_to_prompt_map = {
  360. DialogueState.GREETING: GENERAL_GREETING_PROMPT,
  361. DialogueState.CHITCHAT: GENERAL_GREETING_PROMPT,
  362. DialogueState.FAREWELL: GENERAL_GREETING_PROMPT
  363. }
  364. return state_to_prompt_map[state]
  365. def _select_coze_bot(self, state):
  366. state_to_bot_map = {
  367. DialogueState.GREETING: '7479005417885417487',
  368. DialogueState.CHITCHAT: '7479005417885417487',
  369. DialogueState.FAREWELL: '7479005417885417487'
  370. }
  371. return state_to_bot_map[state]
  372. def _create_system_message(self, prompt_context):
  373. prompt_template = self._select_prompt(self.current_state)
  374. prompt = prompt_template.format(**prompt_context)
  375. return {'role': 'system', 'content': prompt}
  376. def build_chat_configuration(
  377. self,
  378. user_message: Optional[str] = None,
  379. chat_service_type: ChatServiceType = ChatServiceType.OPENAI_COMPATIBLE
  380. ) -> Dict:
  381. """
  382. 参数:
  383. user_message: 当前用户消息,如果是主动交互则为None
  384. 返回:
  385. 消息列表
  386. """
  387. dialogue_history = self.history_dialogue_service.get_dialogue_history(self.staff_id, self.user_id)
  388. logging.debug("staff[{}], user[{}], dialogue_history: {}".format(
  389. self.staff_id, self.user_id, dialogue_history
  390. ))
  391. messages = []
  392. config = {}
  393. prompt_context = self.get_prompt_context(user_message)
  394. if chat_service_type == ChatServiceType.OPENAI_COMPATIBLE:
  395. system_message = self._create_system_message(prompt_context)
  396. messages.append(system_message)
  397. for entry in dialogue_history:
  398. role = entry['role']
  399. messages.append({
  400. "role": role,
  401. "content": entry["content"]
  402. })
  403. elif chat_service_type == ChatServiceType.COZE_CHAT:
  404. for entry in dialogue_history:
  405. if not entry['content']:
  406. logging.warning("staff[{}], user[{}], role[{}]: empty content in dialogue history".format(
  407. self.staff_id, self.user_id, entry['role']
  408. ))
  409. continue
  410. role = entry['role']
  411. if role == 'user':
  412. messages.append(cozepy.Message.build_user_question_text(entry["content"]))
  413. elif role == 'assistant':
  414. messages.append(cozepy.Message.build_assistant_answer(entry['content']))
  415. custom_variables = {}
  416. for k, v in prompt_context.items():
  417. custom_variables[k] = str(v)
  418. custom_variables.pop('user_profile', None)
  419. config['custom_variables'] = custom_variables
  420. config['bot_id'] = self._select_coze_bot(self.current_state)
  421. #FIXME(zhoutian): 这种方法并不可靠,需要结合状态来判断
  422. if self.current_state == DialogueState.GREETING and not messages:
  423. messages.append(cozepy.Message.build_user_question_text('请开始对话'))
  424. #FIXME(zhoutian): 临时报警
  425. if user_message and not messages:
  426. logging.error(f"staff[{self.staff_id}], user[{self.user_id}]: inconsistency in messages")
  427. config['messages'] = messages
  428. return config