dialogue_manager.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. #! /usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # vim:fenc=utf-8
  4. import random
  5. from enum import Enum
  6. from typing import Dict, List, Optional, Tuple, Any
  7. from datetime import datetime
  8. import time
  9. import textwrap
  10. import pymysql.cursors
  11. import cozepy
  12. from pqai_agent import configs
  13. from pqai_agent.logging_service import logger
  14. from pqai_agent.database import MySQLManager
  15. from pqai_agent import chat_service, prompt_templates
  16. from pqai_agent.history_dialogue_service import HistoryDialogueService
  17. from pqai_agent.chat_service import ChatServiceType
  18. from pqai_agent.message import MessageType, Message
  19. from pqai_agent.toolkit.lark_alert_for_human_intervention import LarkAlertForHumanIntervention
  20. from pqai_agent.toolkit.lark_sheet_record_for_human_intervention import LarkSheetRecordForHumanIntervention
  21. from pqai_agent.user_manager import UserManager
  22. from pqai_agent.utils import prompt_utils
  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 DialogueStateChangeType(int, Enum):
  48. STATE = 0
  49. INTERACTION_TIME = 1
  50. DIALOGUE_HISTORY = 2
  51. class DialogueStateChange:
  52. def __init__(self, event_type: DialogueStateChangeType,old: Any, new: Any):
  53. self.event_type = event_type
  54. self.old = old
  55. self.new = new
  56. class DialogueStateCache:
  57. def __init__(self):
  58. self.config = configs.get()
  59. self.db = MySQLManager(self.config['storage']['agent_state']['mysql'])
  60. self.table = self.config['storage']['agent_state']['table']
  61. def get_state(self, staff_id: str, user_id: str) -> Tuple[DialogueState, DialogueState]:
  62. query = f"SELECT current_state, previous_state FROM {self.table} WHERE staff_id=%s AND user_id=%s"
  63. data = self.db.select(query, pymysql.cursors.DictCursor, (staff_id, user_id))
  64. if not data:
  65. logger.warning(f"staff[{staff_id}], user[{user_id}]: agent state not found")
  66. state = DialogueState.INITIALIZED
  67. previous_state = DialogueState.INITIALIZED
  68. self.set_state(staff_id, user_id, state, previous_state)
  69. else:
  70. state = DialogueState(data[0]['current_state'])
  71. previous_state = DialogueState(data[0]['previous_state'])
  72. return state, previous_state
  73. def set_state(self, staff_id: str, user_id: str, state: DialogueState, previous_state: DialogueState):
  74. if self.config.get('debug_flags', {}).get('disable_database_write', False):
  75. return
  76. query = f"INSERT INTO {self.table} (staff_id, user_id, current_state, previous_state)" \
  77. f" VALUES (%s, %s, %s, %s) " \
  78. f"ON DUPLICATE KEY UPDATE current_state=%s, previous_state=%s"
  79. rows = self.db.execute(query, (staff_id, user_id, state.value, previous_state.value, state.value, previous_state.value))
  80. logger.debug("staff[{}], user[{}]: set state: {}, previous state: {}, rows affected: {}"
  81. .format(staff_id, user_id, state, previous_state, rows))
  82. class DialogueManager:
  83. def __init__(self, staff_id: str, user_id: str, user_manager: UserManager, state_cache: DialogueStateCache):
  84. config = configs.get()
  85. self.staff_id = staff_id
  86. self.user_id = user_id
  87. self.user_manager = user_manager
  88. self.state_cache = state_cache
  89. self.current_state = DialogueState.GREETING
  90. self.previous_state = DialogueState.INITIALIZED
  91. # 目前实际仅用作调试,拼装prompt时使用history_dialogue_service获取
  92. self.dialogue_history = []
  93. self.user_profile = self.user_manager.get_user_profile(user_id)
  94. self.staff_profile = self.user_manager.get_staff_profile(staff_id)
  95. # FIXME: 交互时间和对话记录都涉及到回滚
  96. self.last_interaction_time = 0
  97. self.human_intervention_triggered = False
  98. self.vector_memory = DummyVectorMemoryManager(user_id)
  99. self.message_aggregation_sec = config.get('agent_behavior', {}).get('message_aggregation_sec', 5)
  100. self.unprocessed_messages = []
  101. self.history_dialogue_service = HistoryDialogueService(
  102. config['storage']['history_dialogue']['api_base_url']
  103. )
  104. self._recover_state()
  105. # 由于本地状态管理过于复杂,引入事务机制做状态回滚
  106. self._uncommited_state_change = []
  107. @staticmethod
  108. def get_time_context(current_hour=None) -> TimeContext:
  109. """获取当前时间上下文"""
  110. if not current_hour:
  111. current_hour = datetime.now().hour
  112. if 5 <= current_hour < 7:
  113. return TimeContext.EARLY_MORNING
  114. elif 7 <= current_hour < 11:
  115. return TimeContext.MORNING
  116. elif 11 <= current_hour < 14:
  117. return TimeContext.NOON
  118. elif 14 <= current_hour < 18:
  119. return TimeContext.AFTERNOON
  120. elif 18 <= current_hour < 22:
  121. return TimeContext.EVENING
  122. else:
  123. return TimeContext.NIGHT
  124. def is_valid(self):
  125. if not self.staff_profile.get('name', None) and not self.staff_profile.get('agent_name', None):
  126. return False
  127. return True
  128. def refresh_profile(self):
  129. self.staff_profile = self.user_manager.get_staff_profile(self.staff_id)
  130. def _recover_state(self):
  131. self.current_state, self.previous_state = self.state_cache.get_state(self.staff_id, self.user_id)
  132. # 从数据库恢复对话状态
  133. minutes_to_get = 5 * 24 * 60
  134. self.dialogue_history = self.history_dialogue_service.get_dialogue_history(
  135. self.staff_id, self.user_id, minutes_to_get)
  136. if self.dialogue_history:
  137. self.last_interaction_time = self.dialogue_history[-1]['timestamp']
  138. if self.current_state == DialogueState.MESSAGE_AGGREGATING:
  139. # 需要恢复未处理对话,找到dialogue_history中最后未处理的user消息
  140. for entry in reversed(self.dialogue_history):
  141. if entry['role'] == 'user':
  142. self.unprocessed_messages.append(entry['content'])
  143. break
  144. else:
  145. # 默认设置
  146. self.last_interaction_time = int(time.time() * 1000) - minutes_to_get * 60 * 1000
  147. time_for_read = datetime.fromtimestamp(self.last_interaction_time / 1000).strftime("%Y-%m-%d %H:%M:%S")
  148. logger.debug(f"staff[{self.staff_id}], user[{self.user_id}]: state: {self.current_state.name}, last_interaction: {time_for_read}")
  149. def update_interaction_time(self, timestamp_ms: int):
  150. self._uncommited_state_change.append(DialogueStateChange(
  151. DialogueStateChangeType.INTERACTION_TIME,
  152. self.last_interaction_time,
  153. timestamp_ms
  154. ))
  155. self.last_interaction_time = timestamp_ms
  156. def append_dialogue_history(self, message: Dict):
  157. self._uncommited_state_change.append(DialogueStateChange(
  158. DialogueStateChangeType.DIALOGUE_HISTORY,
  159. None,
  160. 1
  161. ))
  162. self.dialogue_history.append(message)
  163. def persist_state(self):
  164. """持久化对话状态,只有当前状态处理成功后才应该做持久化"""
  165. self.commit()
  166. config = configs.get()
  167. if config.get('debug_flags', {}).get('disable_database_write', False):
  168. return
  169. self.state_cache.set_state(self.staff_id, self.user_id, self.current_state, self.previous_state)
  170. def rollback_state(self):
  171. logger.info(f"staff[{self.staff_id}], user[{self.user_id}]: reverse state")
  172. for entry in reversed(self._uncommited_state_change):
  173. if entry.event_type == DialogueStateChangeType.STATE:
  174. self.current_state, self.previous_state = entry.old
  175. elif entry.event_type == DialogueStateChangeType.INTERACTION_TIME:
  176. self.last_interaction_time = entry.old
  177. elif entry.event_type == DialogueStateChangeType.DIALOGUE_HISTORY:
  178. self.dialogue_history.pop()
  179. else:
  180. logger.error(f"unimplemented type: [{entry.event_type}]")
  181. self._uncommited_state_change.clear()
  182. def commit(self):
  183. self._uncommited_state_change.clear()
  184. def do_state_change(self, state: DialogueState):
  185. state_backup = (self.current_state, self.previous_state)
  186. if self.current_state == DialogueState.MESSAGE_AGGREGATING:
  187. # MESSAGE_AGGREGATING不能成为previous_state,仅使用state_backup做回退
  188. self.current_state = state
  189. else:
  190. self.previous_state = self.current_state
  191. self.current_state = state
  192. self._uncommited_state_change.append(DialogueStateChange(
  193. DialogueStateChangeType.STATE,
  194. state_backup,
  195. (self.current_state, self.previous_state)
  196. ))
  197. def update_state(self, message: Message) -> Tuple[bool, Optional[str]]:
  198. """根据用户消息更新对话状态,并返回是否需要发起回复 及下一条需处理的用户消息"""
  199. message_text = message.content
  200. message_ts = message.sendTime
  201. # 如果当前已经是人工介入状态,根据消息类型决定保持/退出
  202. if self.current_state == DialogueState.HUMAN_INTERVENTION:
  203. if message.type == MessageType.HUMAN_INTERVENTION_END:
  204. self.resume_from_human_intervention()
  205. # 恢复状态,但无需Agent产生回复
  206. return False, None
  207. else:
  208. self.append_dialogue_history({
  209. "role": "user",
  210. "content": message_text,
  211. "timestamp": int(time.time() * 1000),
  212. "state": self.current_state.name
  213. })
  214. return False, message_text
  215. if message.type == MessageType.ENTER_HUMAN_INTERVENTION:
  216. logger.info(f"staff[{self.staff_id}], user[{self.user_id}]: human intervention triggered")
  217. self.do_state_change(DialogueState.HUMAN_INTERVENTION)
  218. return False, None
  219. # 检查是否处于消息聚合状态
  220. if self.current_state == DialogueState.MESSAGE_AGGREGATING:
  221. # 收到的是特殊定时触发的空消息,且在聚合中,且已经超时,继续处理
  222. if message.type == MessageType.AGGREGATION_TRIGGER:
  223. if message_ts - self.last_interaction_time > self.message_aggregation_sec * 1000:
  224. logger.debug(f"staff[{self.staff_id}], user[{self.user_id}]: exit aggregation waiting")
  225. else:
  226. logger.debug(f"staff[{self.staff_id}], user[{self.user_id}]: continue aggregation waiting")
  227. return False, message_text
  228. else:
  229. # 非空消息,更新最后交互时间,保持消息聚合状态
  230. if message_text:
  231. self.unprocessed_messages.append(message_text)
  232. self.update_interaction_time(message_ts)
  233. return False, message_text
  234. else:
  235. if message.type == MessageType.AGGREGATION_TRIGGER:
  236. # 未在聚合状态中,收到的聚合触发消息为过时消息,不应当处理
  237. logger.warning(f"staff[{self.staff_id}], user[{self.user_id}]: received {message.type} in state {self.current_state}")
  238. return False, None
  239. if message.type == MessageType.HUMAN_INTERVENTION_END:
  240. # 未在人工介入状态中,收到的人工介入结束事件为过时消息,不应当处理
  241. logger.warning(f"staff[{self.staff_id}], user[{self.user_id}]: received {message.type} in state {self.current_state}")
  242. return False, None
  243. if message.type != MessageType.AGGREGATION_TRIGGER and self.message_aggregation_sec > 0:
  244. # 收到有内容的用户消息,切换到消息聚合状态
  245. self.do_state_change(DialogueState.MESSAGE_AGGREGATING)
  246. self.unprocessed_messages.append(message_text)
  247. # 更新最后交互时间
  248. if message_text:
  249. self.update_interaction_time(message_ts)
  250. return False, message_text
  251. # 获得未处理的聚合消息,并清空未处理队列
  252. if message_text:
  253. self.unprocessed_messages.append(message_text)
  254. if self.unprocessed_messages:
  255. message_text = '\n'.join(self.unprocessed_messages)
  256. self.unprocessed_messages.clear()
  257. # 实际上这里message_text并不会被最终送入LLM,只是用来做状态判断
  258. # 根据消息内容和当前状态确定新状态
  259. new_state = self._determine_state_from_message(message_text)
  260. # 更新状态
  261. self.do_state_change(new_state)
  262. if message_text:
  263. self.update_interaction_time(message_ts)
  264. self.append_dialogue_history({
  265. "role": "user",
  266. "content": message_text,
  267. "timestamp": message_ts,
  268. "state": self.current_state.name
  269. })
  270. return True, message_text
  271. def _determine_state_from_message(self, message_text: Optional[str]) -> DialogueState:
  272. """根据消息内容确定对话状态"""
  273. if not message_text:
  274. logger.warning(f"staff[{self.staff_id}], user[{self.user_id}]: empty message")
  275. return self.current_state
  276. # 简单的规则-关键词匹配
  277. message_lower = message_text.lower()
  278. # 问候检测
  279. greeting_keywords = ["你好", "早上好", "中午好", "晚上好", "嗨", "在吗"]
  280. if any(keyword in message_lower for keyword in greeting_keywords):
  281. return DialogueState.GREETING
  282. # 告别检测
  283. farewell_keywords = ["再见", "拜拜", "晚安", "明天见", "回头见"]
  284. if any(keyword in message_lower for keyword in farewell_keywords):
  285. return DialogueState.FAREWELL
  286. # 澄清请求
  287. # clarification_keywords = ["没明白", "不明白", "没听懂", "不懂", "什么意思", "再说一遍"]
  288. # if any(keyword in message_lower for keyword in clarification_keywords):
  289. # return DialogueState.CLARIFICATION
  290. # 默认为闲聊状态
  291. return DialogueState.CHITCHAT
  292. def _send_alert(self, alert_type: str, reason: Optional[str] = None) -> None:
  293. time_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  294. staff_info = f"{self.staff_profile.get('name', '未知')}[{self.staff_id}]"
  295. user_info = f"{self.user_profile.get('nickname', '未知')}[{self.user_id}]"
  296. alert_message = f"""
  297. {alert_type}告警
  298. 员工: {staff_info}
  299. 用户: {user_info}
  300. 时间: {time_str}
  301. 原因:{reason if reason else "未知"}
  302. 最近对话:
  303. """
  304. alert_message = textwrap.dedent(alert_message).strip()
  305. # 添加最近的对话记录
  306. recent_dialogues = self.dialogue_history[-5:]
  307. dialogue_to_send = []
  308. role_map = {'assistant': '客服', 'user': '用户'}
  309. for dialogue in recent_dialogues:
  310. if not dialogue['content']:
  311. continue
  312. role = dialogue['role']
  313. if role not in role_map:
  314. continue
  315. dialogue_to_send.append(f"[{role_map[role]}]{dialogue['content']}")
  316. alert_message += '\n'.join(dialogue_to_send)
  317. if alert_type == '人工介入':
  318. ack_url = "http://ai-wechat-hook.piaoquantv.com/manage/insertEvent?" \
  319. f"sender={self.user_id}&receiver={self.staff_id}&type={MessageType.HUMAN_INTERVENTION_END.value}&content=OPERATION"
  320. else:
  321. ack_url = None
  322. LarkAlertForHumanIntervention().send_lark_alert_for_human_intervention(alert_message, ack_url)
  323. if alert_type == '人工介入':
  324. LarkSheetRecordForHumanIntervention().send_lark_sheet_record_for_human_intervention(
  325. staff_info, user_info, '\n'.join(dialogue_to_send), reason
  326. )
  327. def resume_from_human_intervention(self) -> None:
  328. """从人工介入状态恢复"""
  329. if self.current_state == DialogueState.HUMAN_INTERVENTION:
  330. self.do_state_change(DialogueState.CHITCHAT)
  331. def generate_response(self, llm_response: str) -> Optional[str]:
  332. """
  333. 处理LLM的响应,更新对话状态和对话历史。
  334. 注意:所有的LLM响应都必须经过这个函数来处理!
  335. :param llm_response:
  336. :return:
  337. """
  338. if '<人工介入>' in llm_response:
  339. reason = llm_response.replace('<人工介入>', '')
  340. logger.warning(f'staff[{self.staff_id}], user[{self.user_id}]: human intervention triggered, reason: {reason}')
  341. self.do_state_change(DialogueState.HUMAN_INTERVENTION)
  342. self._send_alert('人工介入', reason)
  343. return None
  344. if '<结束>' in llm_response or '<负向情绪结束>' in llm_response:
  345. logger.warning(f'staff[{self.staff_id}], user[{self.user_id}]: conversation ended')
  346. self.do_state_change(DialogueState.FAREWELL)
  347. if '<负向情绪结束>' in llm_response:
  348. self._send_alert("用户负向情绪")
  349. return None
  350. """根据当前状态处理LLM响应,如果处于人工介入状态则返回None"""
  351. # 如果处于人工介入状态,不生成回复
  352. if self.current_state == DialogueState.HUMAN_INTERVENTION:
  353. return None
  354. # 记录响应到对话历史
  355. message_ts = int(time.time() * 1000)
  356. self.append_dialogue_history({
  357. "role": "assistant",
  358. "content": llm_response,
  359. "timestamp": message_ts,
  360. "state": self.current_state.name
  361. })
  362. self.update_interaction_time(message_ts)
  363. return llm_response
  364. def _get_hours_since_last_interaction(self, precision: int = -1):
  365. time_diff = (time.time() * 1000) - self.last_interaction_time
  366. hours_passed = time_diff / 1000 / 3600
  367. if precision >= 0:
  368. return round(hours_passed, precision)
  369. return hours_passed
  370. def should_initiate_conversation(self) -> bool:
  371. """判断是否应该主动发起对话"""
  372. # 如果处于人工介入状态,不应主动发起对话
  373. if self.current_state == DialogueState.HUMAN_INTERVENTION:
  374. return False
  375. hours_passed = self._get_hours_since_last_interaction()
  376. # 获取当前时间上下文
  377. time_context = self.get_time_context()
  378. # 根据用户交互频率偏好设置不同的阈值
  379. interaction_frequency = self.user_profile.get("interaction_frequency", "medium")
  380. if interaction_frequency == 'stopped':
  381. return False
  382. # 设置不同偏好的交互时间阈值(小时)
  383. thresholds = {
  384. "low": 48,
  385. "medium": 24,
  386. "high": 12
  387. }
  388. threshold = thresholds.get(interaction_frequency, 12)
  389. if hours_passed < threshold:
  390. return False
  391. # 根据时间上下文决定主动交互的状态
  392. if self.is_time_suitable_for_active_conversation(time_context):
  393. return True
  394. return False
  395. @staticmethod
  396. def is_time_suitable_for_active_conversation(time_context=None) -> bool:
  397. if configs.get_env() == 'dev':
  398. return True
  399. if not time_context:
  400. time_context = DialogueManager.get_time_context()
  401. if time_context in [TimeContext.MORNING,
  402. TimeContext.NOON, TimeContext.AFTERNOON]:
  403. return True
  404. return False
  405. def is_in_human_intervention(self) -> bool:
  406. """检查是否处于人工介入状态"""
  407. return self.current_state == DialogueState.HUMAN_INTERVENTION
  408. def get_prompt_context(self, user_message) -> Dict:
  409. # 获取当前时间上下文
  410. time_context = self.get_time_context()
  411. # 刷新用户画像
  412. self.user_profile = self.user_manager.get_user_profile(self.user_id)
  413. # 刷新员工画像(不一定需要)
  414. self.staff_profile = self.user_manager.get_staff_profile(self.staff_id)
  415. # 员工画像添加前缀,避免冲突,实现Coze Prompt模板的平滑升级
  416. legacy_staff_profile = {}
  417. for key in self.staff_profile:
  418. legacy_staff_profile[f'agent_{key}'] = self.staff_profile[key]
  419. current_datetime = datetime.now()
  420. context = {
  421. "current_state": self.current_state.name,
  422. "previous_state": self.previous_state.name,
  423. "current_time_period": time_context.description,
  424. "current_hour": current_datetime.hour,
  425. "current_time": current_datetime.strftime("%H:%M:%S"),
  426. "current_date": current_datetime.strftime("%Y-%m-%d"),
  427. "current_datetime": current_datetime.strftime("%Y-%m-%d %H:%M:%S"),
  428. "last_interaction_interval": self._get_hours_since_last_interaction(2),
  429. "if_first_interaction": True if self.previous_state == DialogueState.INITIALIZED else False,
  430. "if_active_greeting": False if user_message else True,
  431. "formatted_staff_profile": prompt_utils.format_agent_profile(self.staff_profile),
  432. **self.user_profile,
  433. **legacy_staff_profile
  434. }
  435. # 获取长期记忆
  436. relevant_memories = self.vector_memory.retrieve_relevant_memories(user_message)
  437. context["long_term_memory"] = {
  438. "relevant_conversations": relevant_memories
  439. }
  440. return context
  441. @staticmethod
  442. def _select_prompt(state):
  443. state_to_prompt_map = {
  444. DialogueState.GREETING: prompt_templates.GENERAL_GREETING_PROMPT,
  445. DialogueState.CHITCHAT: prompt_templates.CHITCHAT_PROMPT_COZE,
  446. DialogueState.FAREWELL: prompt_templates.GENERAL_GREETING_PROMPT
  447. }
  448. return state_to_prompt_map[state]
  449. @staticmethod
  450. def _select_coze_bot(state, dialogue: List[Dict], multimodal=False):
  451. state_to_bot_map = {
  452. DialogueState.GREETING: '7486112546798780425',
  453. DialogueState.CHITCHAT: '7491300566573301770',
  454. DialogueState.FAREWELL: '7491300566573301770',
  455. }
  456. if multimodal:
  457. state_to_bot_map = {
  458. DialogueState.GREETING: '7496772218198900770',
  459. DialogueState.CHITCHAT: '7495692989504438308',
  460. DialogueState.FAREWELL: '7491300566573301770',
  461. }
  462. return state_to_bot_map[state]
  463. @staticmethod
  464. def need_multimodal_model(dialogue: List[Dict], max_message_to_use: int = 10):
  465. # 当前仅为简单实现
  466. recent_messages = dialogue[-max_message_to_use:]
  467. ret = False
  468. for entry in recent_messages:
  469. if entry.get('type') in (MessageType.IMAGE_GW, MessageType.IMAGE_QW, MessageType.GIF):
  470. ret = True
  471. break
  472. return ret
  473. def _create_system_message(self, prompt_context):
  474. prompt_template = self._select_prompt(self.current_state)
  475. prompt = prompt_template.format(**prompt_context)
  476. return {'role': 'system', 'content': prompt}
  477. @staticmethod
  478. def compose_chat_messages_openai_compatible(dialogue_history, current_time, multimodal=False):
  479. messages = []
  480. for entry in dialogue_history:
  481. role = entry['role']
  482. msg_type = entry.get('type', MessageType.TEXT)
  483. fmt_time = DialogueManager.format_timestamp(entry['timestamp'])
  484. if msg_type in (MessageType.IMAGE_GW, MessageType.IMAGE_QW, MessageType.GIF):
  485. if multimodal:
  486. messages.append({
  487. "role": role,
  488. "content": [
  489. {"type": "image_url", "image_url": {"url": entry["content"]}}
  490. ]
  491. })
  492. else:
  493. logger.warning("Image in non-multimodal mode")
  494. messages.append({
  495. "role": role,
  496. "content": "[{}] {}".format(fmt_time, '[图片]')
  497. })
  498. else:
  499. messages.append({
  500. "role": role,
  501. "content": '[{}] {}'.format(fmt_time, entry["content"])
  502. })
  503. # 添加一条前缀用于 约束时间场景
  504. msg_prefix = '[{}]'.format(current_time)
  505. messages.append({'role': 'assistant', 'content': msg_prefix})
  506. return messages
  507. @staticmethod
  508. def compose_chat_messages_coze(dialogue_history, current_time, staff_id, user_id):
  509. messages = []
  510. # 如果system后的第1条消息不为user,需要在最开始补一条user消息,否则会吞assistant消息
  511. if len(dialogue_history) > 0 and dialogue_history[0]['role'] != 'user':
  512. fmt_time = DialogueManager.format_timestamp(dialogue_history[0]['timestamp'])
  513. messages.append(cozepy.Message.build_user_question_text(f'[{fmt_time}] '))
  514. # coze最后一条消息必须为user,且可能吞掉连续的user消息,故强制增加一条空消息(可参与合并)
  515. dialogue_history.append({
  516. 'role': 'user',
  517. 'content': ' ',
  518. 'timestamp': int(datetime.strptime(current_time, '%Y-%m-%d %H:%M:%S').timestamp() * 1000),
  519. })
  520. # 将连续的同一角色的消息做聚合,避免coze吞消息
  521. messages_to_aggr = []
  522. objects_to_aggr = []
  523. last_message_role = None
  524. for entry in dialogue_history:
  525. if not entry['content']:
  526. logger.warning("staff[{}], user[{}], role[{}]: empty content in dialogue history".format(
  527. staff_id, user_id, entry['role']
  528. ))
  529. continue
  530. role = entry['role']
  531. if role != last_message_role:
  532. if objects_to_aggr:
  533. if last_message_role != 'user':
  534. pass
  535. else:
  536. text_message = '\n'.join(messages_to_aggr)
  537. object_string_list = []
  538. for object_entry in objects_to_aggr:
  539. # FIXME: 其它消息类型的支持
  540. object_string_list.append(cozepy.MessageObjectString.build_image(file_url=object_entry['content']))
  541. object_string_list.append(cozepy.MessageObjectString.build_text(text_message))
  542. messages.append(cozepy.Message.build_user_question_objects(object_string_list))
  543. elif messages_to_aggr:
  544. aggregated_message = '\n'.join(messages_to_aggr)
  545. messages.append(DialogueManager.build_chat_message(
  546. last_message_role, aggregated_message, ChatServiceType.COZE_CHAT))
  547. objects_to_aggr = []
  548. messages_to_aggr = []
  549. last_message_role = role
  550. if entry.get('type', MessageType.TEXT) in (MessageType.IMAGE_GW, MessageType.IMAGE_QW, MessageType.GIF):
  551. # 多模态消息必须用特殊的聚合方式,一个object_string数组中只能有一个文字消息,但可以有多个图片
  552. if role == 'user':
  553. objects_to_aggr.append(entry)
  554. else:
  555. logger.warning("staff[{}], user[{}]: unsupported message type [{}] in assistant role".format(
  556. staff_id, user_id, entry['type']
  557. ))
  558. else:
  559. messages_to_aggr.append(DialogueManager.format_dialogue_content(entry))
  560. # 如果有未聚合的object消息,需要特殊处理
  561. if objects_to_aggr:
  562. if last_message_role != 'user':
  563. pass
  564. else:
  565. text_message = '\n'.join(messages_to_aggr)
  566. object_string_list = []
  567. for object_entry in objects_to_aggr:
  568. # FIXME: 其它消息类型的支持
  569. object_string_list.append(cozepy.MessageObjectString.build_image(file_url=object_entry['content']))
  570. object_string_list.append(cozepy.MessageObjectString.build_text(text_message))
  571. messages.append(cozepy.Message.build_user_question_objects(object_string_list))
  572. elif messages_to_aggr:
  573. aggregated_message = '\n'.join(messages_to_aggr)
  574. messages.append(DialogueManager.build_chat_message(
  575. last_message_role, aggregated_message, ChatServiceType.COZE_CHAT))
  576. # 从末尾开始往前遍历,如果assistant曾经回复“无法回答”,则清除当前消息和前一条用户消息
  577. idx = len(messages) - 1
  578. while idx >= 0:
  579. if messages[idx].role == 'assistant' and '无法回答' in messages[idx].content:
  580. messages.pop(idx)
  581. idx -= 1
  582. if idx >= 0:
  583. messages.pop(idx)
  584. idx -= 1
  585. else:
  586. idx -= 1
  587. return messages
  588. def build_active_greeting_config(self, user_tags: List[str]):
  589. # FIXME: 这里的抽象不好,短期支持人为配置实验
  590. # 由于产运要求,指定使用GPT-4o模型
  591. chat_config = {'user_id': self.user_id, 'model_name': chat_service.OPENAI_MODEL_GPT_4o}
  592. prompt_context = self.get_prompt_context(None)
  593. current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  594. system_message = {'role': 'system', 'content': 'You are a helpful AI assistant.'}
  595. # TODO: 随机选择一个prompt 或 带策略选择 或根据用户标签选择
  596. # TODO:需要区分用户是否有历史交互、是否发送过相似内容
  597. greeting_prompts = [
  598. prompt_templates.GREETING_WITH_IMAGE_GAME,
  599. prompt_templates.GREETING_WITH_NAME_POETRY,
  600. prompt_templates.GREETING_WITH_AVATAR_STORY
  601. ]
  602. # 默认随机选择
  603. selected_prompt = greeting_prompts[random.randint(0, len(greeting_prompts) - 1)]
  604. # 实验配置
  605. tag_to_greeting_map = {
  606. '04W4-AA-1': prompt_templates.GREETING_WITH_NAME_POETRY,
  607. '04W4-AA-2': prompt_templates.GREETING_WITH_AVATAR_STORY,
  608. '04W4-AA-3': prompt_templates.GREETING_WITH_INTEREST_QUERY,
  609. '04W4-AA-4': prompt_templates.GREETING_WITH_CALENDAR,
  610. }
  611. for tag in user_tags:
  612. if tag in tag_to_greeting_map:
  613. selected_prompt = tag_to_greeting_map[tag]
  614. prompt = selected_prompt.format(**prompt_context)
  615. user_message = {'role': 'user', 'content': prompt}
  616. messages = [system_message, user_message]
  617. if selected_prompt in (
  618. prompt_templates.GREETING_WITH_AVATAR_STORY,
  619. prompt_templates.GREETING_WITH_INTEREST_QUERY,
  620. ):
  621. messages.append({
  622. "role": 'user',
  623. "content": [
  624. {"type": "image_url", "image_url": {"url": self.user_profile['avatar']}}
  625. ]
  626. })
  627. chat_config['use_multimodal_model'] = True
  628. chat_config['messages'] = messages
  629. return chat_config
  630. def build_chat_configuration(
  631. self,
  632. user_message: Optional[str] = None,
  633. chat_service_type: ChatServiceType = ChatServiceType.OPENAI_COMPATIBLE,
  634. overwrite_context: Optional[Dict] = None
  635. ) -> Dict:
  636. """
  637. 参数:
  638. user_message: 当前用户消息,如果是主动交互则为None
  639. 返回:
  640. 消息列表
  641. """
  642. dialogue_history = self.history_dialogue_service.get_dialogue_history(self.staff_id, self.user_id)
  643. logger.debug("staff[{}], user[{}], recent dialogue_history: {}".format(
  644. self.staff_id, self.user_id, dialogue_history[-20:]
  645. ))
  646. messages = []
  647. config = {
  648. 'user_id': self.user_id
  649. }
  650. prompt_context = self.get_prompt_context(user_message)
  651. if overwrite_context:
  652. prompt_context.update(overwrite_context)
  653. # FIXME(zhoutian): time in string type
  654. current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  655. if overwrite_context and 'current_time' in overwrite_context:
  656. current_time = overwrite_context.get('current_time')
  657. need_multimodal = self.need_multimodal_model(dialogue_history)
  658. config['use_multimodal_model'] = need_multimodal
  659. if chat_service_type == ChatServiceType.OPENAI_COMPATIBLE:
  660. system_message = self._create_system_message(prompt_context)
  661. messages.append(system_message)
  662. messages.extend(self.compose_chat_messages_openai_compatible(dialogue_history, current_time, need_multimodal))
  663. elif chat_service_type == ChatServiceType.COZE_CHAT:
  664. dialogue_history = dialogue_history[-95:] # Coze最多支持100条,还需要附加系统消息
  665. messages = self.compose_chat_messages_coze(dialogue_history, current_time, self.staff_id, self.user_id)
  666. custom_variables = {}
  667. for k, v in prompt_context.items():
  668. custom_variables[k] = str(v)
  669. custom_variables.pop('user_profile', None)
  670. config['custom_variables'] = custom_variables
  671. config['bot_id'] = self._select_coze_bot(self.current_state, dialogue_history, need_multimodal)
  672. #FIXME(zhoutian): 临时报警
  673. if user_message and not messages:
  674. logger.error(f"staff[{self.staff_id}], user[{self.user_id}]: inconsistency in messages")
  675. config['messages'] = messages
  676. return config
  677. @staticmethod
  678. def format_timestamp(timestamp_ms):
  679. return datetime.fromtimestamp(timestamp_ms / 1000).strftime("%Y-%m-%d %H:%M:%S")
  680. @staticmethod
  681. def format_dialogue_content(dialogue_entry):
  682. fmt_time = DialogueManager.format_timestamp(dialogue_entry['timestamp'])
  683. content = '[{}] {}'.format(fmt_time, dialogue_entry['content'])
  684. return content
  685. @staticmethod
  686. def build_chat_message(role, content, chat_service_type: ChatServiceType):
  687. if chat_service_type == ChatServiceType.COZE_CHAT:
  688. if role == 'user':
  689. return cozepy.Message.build_user_question_text(content)
  690. elif role == 'assistant':
  691. return cozepy.Message.build_assistant_answer(content)
  692. else:
  693. return {'role': role, 'content': content}
  694. if __name__ == '__main__':
  695. state_cache = DialogueStateCache()
  696. state_cache.set_state('1688854492669990', '7881302581935903', DialogueState.CHITCHAT, DialogueState.GREETING)