dialogue_manager.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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. from logging_service import logger
  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 user_manager import UserManager
  17. from prompt_templates import *
  18. class DummyVectorMemoryManager:
  19. def __init__(self, user_id):
  20. pass
  21. def add_to_memory(self, conversation):
  22. pass
  23. def retrieve_relevant_memories(self, query, k=3):
  24. return []
  25. class DialogueState(int, Enum):
  26. INITIALIZED = 0
  27. GREETING = 1 # 问候状态
  28. CHITCHAT = 2 # 闲聊状态
  29. CLARIFICATION = 3 # 澄清状态
  30. FAREWELL = 4 # 告别状态
  31. HUMAN_INTERVENTION = 5 # 人工介入状态
  32. MESSAGE_AGGREGATING = 6 # 等待消息状态
  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 DialogueStateCache:
  43. def __init__(self):
  44. config = configs.get()
  45. self.db = MySQLManager(config['storage']['agent_state']['mysql'])
  46. self.table = config['storage']['agent_state']['table']
  47. def get_state(self, staff_id: str, user_id: str) -> Tuple[DialogueState, DialogueState]:
  48. query = f"SELECT current_state, previous_state FROM {self.table} WHERE staff_id=%s AND user_id=%s"
  49. data = self.db.select(query, pymysql.cursors.DictCursor, (staff_id, user_id))
  50. if not data:
  51. logger.warning(f"staff[{staff_id}], user[{user_id}]: agent state not found")
  52. state = DialogueState.CHITCHAT
  53. previous_state = DialogueState.INITIALIZED
  54. self.set_state(staff_id, user_id, state, previous_state)
  55. else:
  56. state = DialogueState(data[0]['current_state'])
  57. previous_state = DialogueState(data[0]['previous_state'])
  58. return state, previous_state
  59. def set_state(self, staff_id: str, user_id: str, state: DialogueState, previous_state: DialogueState):
  60. query = f"INSERT INTO {self.table} (staff_id, user_id, current_state, previous_state)" \
  61. f" VALUES (%s, %s, %s, %s) " \
  62. f"ON DUPLICATE KEY UPDATE current_state=%s, previous_state=%s"
  63. rows = self.db.execute(query, (staff_id, user_id, state.value, previous_state.value, state.value, previous_state.value))
  64. logger.debug("staff[{}], user[{}]: set state: {}, previous state: {}, rows affected: {}"
  65. .format(staff_id, user_id, state, previous_state, rows))
  66. class DialogueManager:
  67. def __init__(self, staff_id: str, user_id: str, user_manager: UserManager, state_cache: DialogueStateCache):
  68. config = configs.get()
  69. self.staff_id = staff_id
  70. self.user_id = user_id
  71. self.user_manager = user_manager
  72. self.state_cache = state_cache
  73. self.current_state = DialogueState.GREETING
  74. self.previous_state = DialogueState.INITIALIZED
  75. # 目前实际仅用作调试,拼装prompt时使用history_dialogue_service获取
  76. self.dialogue_history = []
  77. self.user_profile = self.user_manager.get_user_profile(user_id)
  78. self.staff_profile = self.user_manager.get_staff_profile(staff_id)
  79. self.last_interaction_time = 0
  80. self.consecutive_clarifications = 0
  81. self.complex_request_counter = 0
  82. self.human_intervention_triggered = False
  83. self.vector_memory = DummyVectorMemoryManager(user_id)
  84. self.message_aggregation_sec = config.get('message_aggregation_sec', 5)
  85. self.unprocessed_messages = []
  86. self.history_dialogue_service = HistoryDialogueService(
  87. config['storage']['history_dialogue']['api_base_url']
  88. )
  89. self._recover_state()
  90. def _recover_state(self):
  91. self.current_state, self.previous_state = self.state_cache.get_state(self.staff_id, self.user_id)
  92. # 从数据库恢复对话状态
  93. last_message = self.history_dialogue_service.get_dialogue_history(self.staff_id, self.user_id)
  94. if last_message:
  95. self.last_interaction_time = last_message[-1]['timestamp']
  96. else:
  97. # 默认设置为24小时前
  98. self.last_interaction_time = int(time.time() * 1000) - 24 * 3600 * 1000
  99. time_for_read = datetime.fromtimestamp(self.last_interaction_time / 1000).strftime("%Y-%m-%d %H:%M:%S")
  100. logger.debug(f"staff[{self.staff_id}], user[{self.user_id}]: state: {self.current_state.name}, last_interaction: {time_for_read}")
  101. def persist_state(self):
  102. """持久化对话状态"""
  103. self.state_cache.set_state(self.staff_id, self.user_id, self.current_state, self.previous_state)
  104. @staticmethod
  105. def get_current_time_context() -> TimeContext:
  106. """获取当前时间上下文"""
  107. current_hour = datetime.now().hour
  108. if 5 <= current_hour < 8:
  109. return TimeContext.EARLY_MORNING
  110. elif 8 <= current_hour < 12:
  111. return TimeContext.MORNING
  112. elif 12 <= current_hour < 14:
  113. return TimeContext.NOON
  114. elif 14 <= current_hour < 18:
  115. return TimeContext.AFTERNOON
  116. elif 18 <= current_hour < 22:
  117. return TimeContext.EVENING
  118. else:
  119. return TimeContext.NIGHT
  120. def update_state(self, message: Message) -> Tuple[bool, Optional[str]]:
  121. """根据用户消息更新对话状态,并返回是否需要发起回复 及下一条需处理的用户消息"""
  122. message_text = message.content
  123. message_ts = message.sendTime
  124. # 如果当前已经是人工介入状态,保持该状态
  125. if self.current_state == DialogueState.HUMAN_INTERVENTION:
  126. # 记录对话历史,但不改变状态
  127. self.dialogue_history.append({
  128. "role": "user",
  129. "content": message_text,
  130. "timestamp": int(time.time() * 1000),
  131. "state": self.current_state.name
  132. })
  133. return False, message_text
  134. # 检查是否处于消息聚合状态
  135. if self.current_state == DialogueState.MESSAGE_AGGREGATING:
  136. # 收到的是特殊定时触发的空消息,且在聚合中,且已经超时,恢复之前状态,继续处理
  137. if message.type == MessageType.AGGREGATION_TRIGGER \
  138. and message_ts - self.last_interaction_time > self.message_aggregation_sec * 1000:
  139. logger.debug("user_id: {}, last interaction time: {}".format(
  140. self.user_id, datetime.fromtimestamp(self.last_interaction_time / 1000)))
  141. self.current_state = self.previous_state
  142. else:
  143. # 非空消息,更新最后交互时间,保持消息聚合状态
  144. if message_text:
  145. self.unprocessed_messages.append(message_text)
  146. self.last_interaction_time = message_ts
  147. return False, message_text
  148. else:
  149. if message.type == MessageType.AGGREGATION_TRIGGER:
  150. # 未在聚合状态中,收到的聚合触发消息为过时消息,不应当处理
  151. return False, None
  152. if message.type != MessageType.AGGREGATION_TRIGGER and self.message_aggregation_sec > 0:
  153. # 收到有内容的用户消息,切换到消息聚合状态
  154. self.previous_state = self.current_state
  155. self.current_state = DialogueState.MESSAGE_AGGREGATING
  156. self.unprocessed_messages.append(message_text)
  157. # 更新最后交互时间
  158. if message_text:
  159. self.last_interaction_time = message_ts
  160. self.persist_state()
  161. return False, message_text
  162. # 保存前一个状态
  163. self.previous_state = self.current_state
  164. # 检查是否长时间未交互(超过3小时)
  165. if self._get_hours_since_last_interaction() > 3:
  166. self.current_state = DialogueState.GREETING
  167. self.dialogue_history = [] # 重置对话历史
  168. self.consecutive_clarifications = 0 # 重置澄清计数
  169. self.complex_request_counter = 0 # 重置复杂请求计数
  170. # 获得未处理的聚合消息,并清空未处理队列
  171. if message_text:
  172. self.unprocessed_messages.append(message_text)
  173. if self.unprocessed_messages:
  174. message_text = '\n'.join(self.unprocessed_messages)
  175. self.unprocessed_messages.clear()
  176. # 根据消息内容和当前状态确定新状态
  177. new_state = self._determine_state_from_message(message_text)
  178. # 处理连续澄清的情况
  179. if new_state == DialogueState.CLARIFICATION:
  180. self.consecutive_clarifications += 1
  181. # FIXME(zhoutian): 规则过于简单
  182. if self.consecutive_clarifications >= 10000:
  183. new_state = DialogueState.HUMAN_INTERVENTION
  184. # self._trigger_human_intervention("连续多次澄清请求")
  185. else:
  186. self.consecutive_clarifications = 0
  187. # 更新状态并持久化
  188. self.current_state = new_state
  189. self.persist_state()
  190. # 更新最后交互时间
  191. if message_text:
  192. self.last_interaction_time = message_ts
  193. # 记录对话历史
  194. if message_text:
  195. self.dialogue_history.append({
  196. "role": "user",
  197. "content": message_text,
  198. "timestamp": message_ts,
  199. "state": self.current_state.name
  200. })
  201. return True, message_text
  202. def _determine_state_from_message(self, message_text: Optional[str]) -> DialogueState:
  203. """根据消息内容确定对话状态"""
  204. if not message_text:
  205. return self.current_state
  206. # 简单的规则-关键词匹配
  207. message_lower = message_text.lower()
  208. # 判断是否是复杂请求
  209. # FIXME(zhoutian): 规则过于简单
  210. # complex_request_keywords = ["帮我", "怎么办", "我需要", "麻烦你", "请帮助", "急", "紧急"]
  211. # if any(keyword in message_lower for keyword in complex_request_keywords):
  212. # self.complex_request_counter += 1
  213. #
  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, 60)
  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, 10)
  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.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. "current_hour": datetime.now().hour,
  346. # "dialogue_history": self.dialogue_history[-10:],
  347. "last_interaction_interval": self._get_hours_since_last_interaction(2),
  348. "if_first_interaction": True if self.previous_state == DialogueState.INITIALIZED else False,
  349. "if_active_greeting": False if user_message else True,
  350. **self.user_profile,
  351. **self.staff_profile
  352. }
  353. # 获取长期记忆
  354. relevant_memories = self.vector_memory.retrieve_relevant_memories(user_message)
  355. context["long_term_memory"] = {
  356. "relevant_conversations": relevant_memories
  357. }
  358. return context
  359. def _select_prompt(self, state):
  360. state_to_prompt_map = {
  361. DialogueState.GREETING: GENERAL_GREETING_PROMPT,
  362. DialogueState.CHITCHAT: GENERAL_GREETING_PROMPT,
  363. DialogueState.FAREWELL: GENERAL_GREETING_PROMPT
  364. }
  365. return state_to_prompt_map[state]
  366. def _select_coze_bot(self, state):
  367. state_to_bot_map = {
  368. DialogueState.GREETING: '7486112546798780425',
  369. DialogueState.CHITCHAT: '7491300566573301770',
  370. DialogueState.FAREWELL: '7491300566573301770'
  371. }
  372. return state_to_bot_map[state]
  373. def _create_system_message(self, prompt_context):
  374. prompt_template = self._select_prompt(self.current_state)
  375. prompt = prompt_template.format(**prompt_context)
  376. return {'role': 'system', 'content': prompt}
  377. def build_chat_configuration(
  378. self,
  379. user_message: Optional[str] = None,
  380. chat_service_type: ChatServiceType = ChatServiceType.OPENAI_COMPATIBLE
  381. ) -> Dict:
  382. """
  383. 参数:
  384. user_message: 当前用户消息,如果是主动交互则为None
  385. 返回:
  386. 消息列表
  387. """
  388. dialogue_history = self.history_dialogue_service.get_dialogue_history(self.staff_id, self.user_id)
  389. logger.debug("staff[{}], user[{}], dialogue_history: {}".format(
  390. self.staff_id, self.user_id, dialogue_history
  391. ))
  392. messages = []
  393. config = {}
  394. prompt_context = self.get_prompt_context(user_message)
  395. if chat_service_type == ChatServiceType.OPENAI_COMPATIBLE:
  396. system_message = self._create_system_message(prompt_context)
  397. messages.append(system_message)
  398. for entry in dialogue_history:
  399. role = entry['role']
  400. messages.append({
  401. "role": role,
  402. "content": entry["content"]
  403. })
  404. elif chat_service_type == ChatServiceType.COZE_CHAT:
  405. for entry in dialogue_history:
  406. if not entry['content']:
  407. logger.warning("staff[{}], user[{}], role[{}]: empty content in dialogue history".format(
  408. self.staff_id, self.user_id, entry['role']
  409. ))
  410. continue
  411. role = entry['role']
  412. if role == 'user':
  413. messages.append(cozepy.Message.build_user_question_text(entry["content"]))
  414. elif role == 'assistant':
  415. messages.append(cozepy.Message.build_assistant_answer(entry['content']))
  416. custom_variables = {}
  417. for k, v in prompt_context.items():
  418. custom_variables[k] = str(v)
  419. custom_variables.pop('user_profile', None)
  420. config['custom_variables'] = custom_variables
  421. config['bot_id'] = self._select_coze_bot(self.current_state)
  422. #FIXME(zhoutian): 这种方法并不可靠,需要结合状态来判断
  423. if self.current_state == DialogueState.GREETING and not messages:
  424. messages.append(cozepy.Message.build_user_question_text('请开始对话'))
  425. #FIXME(zhoutian): 临时报警
  426. if user_message and not messages:
  427. logger.error(f"staff[{self.staff_id}], user[{self.user_id}]: inconsistency in messages")
  428. config['messages'] = messages
  429. return config
  430. if __name__ == '__main__':
  431. state_cache = DialogueStateCache()
  432. state_cache.set_state('1688854492669990', '7881302581935903', DialogueState.CHITCHAT, DialogueState.GREETING)