dialogue_manager.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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.INITIALIZED
  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. # 用于消息处理失败时回滚
  76. self.state_backup = (DialogueState.INITIALIZED, DialogueState.INITIALIZED)
  77. # 目前实际仅用作调试,拼装prompt时使用history_dialogue_service获取
  78. self.dialogue_history = []
  79. self.user_profile = self.user_manager.get_user_profile(user_id)
  80. self.staff_profile = self.user_manager.get_staff_profile(staff_id)
  81. self.last_interaction_time = 0
  82. self.consecutive_clarifications = 0
  83. self.complex_request_counter = 0
  84. self.human_intervention_triggered = False
  85. self.vector_memory = DummyVectorMemoryManager(user_id)
  86. self.message_aggregation_sec = config.get('agent_behavior', {}).get('message_aggregation_sec', 5)
  87. self.unprocessed_messages = []
  88. self.history_dialogue_service = HistoryDialogueService(
  89. config['storage']['history_dialogue']['api_base_url']
  90. )
  91. self._recover_state()
  92. def _recover_state(self):
  93. self.current_state, self.previous_state = self.state_cache.get_state(self.staff_id, self.user_id)
  94. # 从数据库恢复对话状态
  95. self.dialogue_history = self.history_dialogue_service.get_dialogue_history(self.staff_id, self.user_id)
  96. if self.dialogue_history:
  97. self.last_interaction_time = self.dialogue_history[-1]['timestamp']
  98. else:
  99. # 默认设置为24小时前
  100. self.last_interaction_time = int(time.time() * 1000) - 24 * 3600 * 1000
  101. time_for_read = datetime.fromtimestamp(self.last_interaction_time / 1000).strftime("%Y-%m-%d %H:%M:%S")
  102. logger.debug(f"staff[{self.staff_id}], user[{self.user_id}]: state: {self.current_state.name}, last_interaction: {time_for_read}")
  103. def persist_state(self):
  104. """持久化对话状态,只有当前状态处理成功后才应该做持久化"""
  105. config = configs.get()
  106. if config.get('debug_flags', {}).get('disable_state_persistence', False):
  107. return
  108. self.state_cache.set_state(self.staff_id, self.user_id, self.current_state, self.previous_state)
  109. def rollback_state(self):
  110. logger.debug("staff[{}], user[{}]: rollback state: {}, previous state: {}".format(
  111. self.staff_id, self.user_id, self.state_backup, self.current_state
  112. ))
  113. self.current_state, self.previous_state = self.state_backup
  114. @staticmethod
  115. def get_time_context(current_hour=None) -> TimeContext:
  116. """获取当前时间上下文"""
  117. if not current_hour:
  118. current_hour = datetime.now().hour
  119. if 5 <= current_hour < 8:
  120. return TimeContext.EARLY_MORNING
  121. elif 8 <= current_hour < 12:
  122. return TimeContext.MORNING
  123. elif 12 <= current_hour < 14:
  124. return TimeContext.NOON
  125. elif 14 <= current_hour < 18:
  126. return TimeContext.AFTERNOON
  127. elif 18 <= current_hour < 22:
  128. return TimeContext.EVENING
  129. else:
  130. return TimeContext.NIGHT
  131. def do_state_change(self, state: DialogueState):
  132. self.state_backup = (self.current_state, self.previous_state)
  133. if self.current_state == DialogueState.MESSAGE_AGGREGATING:
  134. # 不需要更新previous_state
  135. self.current_state = state
  136. else:
  137. self.previous_state = self.current_state
  138. self.current_state = state
  139. def update_state(self, message: Message) -> Tuple[bool, Optional[str]]:
  140. """根据用户消息更新对话状态,并返回是否需要发起回复 及下一条需处理的用户消息"""
  141. message_text = message.content
  142. message_ts = message.sendTime
  143. # 如果当前已经是人工介入状态,保持该状态
  144. if self.current_state == DialogueState.HUMAN_INTERVENTION:
  145. # 记录对话历史,但不改变状态
  146. self.dialogue_history.append({
  147. "role": "user",
  148. "content": message_text,
  149. "timestamp": int(time.time() * 1000),
  150. "state": self.current_state.name
  151. })
  152. return False, message_text
  153. # 检查是否处于消息聚合状态
  154. if self.current_state == DialogueState.MESSAGE_AGGREGATING:
  155. # 收到的是特殊定时触发的空消息,且在聚合中,且已经超时,恢复之前状态,继续处理
  156. if message.type == MessageType.AGGREGATION_TRIGGER \
  157. and message_ts - self.last_interaction_time > self.message_aggregation_sec * 1000:
  158. logger.debug("user_id: {}, last interaction time: {}".format(
  159. self.user_id, datetime.fromtimestamp(self.last_interaction_time / 1000)))
  160. self.do_state_change(self.previous_state)
  161. else:
  162. # 非空消息,更新最后交互时间,保持消息聚合状态
  163. if message_text:
  164. self.unprocessed_messages.append(message_text)
  165. self.last_interaction_time = message_ts
  166. return False, message_text
  167. else:
  168. if message.type == MessageType.AGGREGATION_TRIGGER:
  169. # 未在聚合状态中,收到的聚合触发消息为过时消息,不应当处理
  170. return False, None
  171. if message.type != MessageType.AGGREGATION_TRIGGER and self.message_aggregation_sec > 0:
  172. # 收到有内容的用户消息,切换到消息聚合状态
  173. self.do_state_change(DialogueState.MESSAGE_AGGREGATING)
  174. self.unprocessed_messages.append(message_text)
  175. # 更新最后交互时间
  176. if message_text:
  177. self.last_interaction_time = message_ts
  178. return False, message_text
  179. # 获得未处理的聚合消息,并清空未处理队列
  180. if message_text:
  181. self.unprocessed_messages.append(message_text)
  182. if self.unprocessed_messages:
  183. message_text = '\n'.join(self.unprocessed_messages)
  184. self.unprocessed_messages.clear()
  185. # 根据消息内容和当前状态确定新状态
  186. new_state = self._determine_state_from_message(message_text)
  187. # 处理连续澄清的情况
  188. if new_state == DialogueState.CLARIFICATION:
  189. self.consecutive_clarifications += 1
  190. # FIXME(zhoutian): 规则过于简单
  191. if self.consecutive_clarifications >= 10000:
  192. new_state = DialogueState.HUMAN_INTERVENTION
  193. # self._trigger_human_intervention("连续多次澄清请求")
  194. else:
  195. self.consecutive_clarifications = 0
  196. # 更新状态
  197. self.do_state_change(new_state)
  198. if message_text:
  199. self.last_interaction_time = message_ts
  200. self.dialogue_history.append({
  201. "role": "user",
  202. "content": message_text,
  203. "timestamp": message_ts,
  204. "state": self.current_state.name
  205. })
  206. return True, message_text
  207. def _determine_state_from_message(self, message_text: Optional[str]) -> DialogueState:
  208. """根据消息内容确定对话状态"""
  209. if not message_text:
  210. return self.current_state
  211. # 简单的规则-关键词匹配
  212. message_lower = message_text.lower()
  213. # 判断是否是复杂请求
  214. # FIXME(zhoutian): 规则过于简单
  215. # complex_request_keywords = ["帮我", "怎么办", "我需要", "麻烦你", "请帮助", "急", "紧急"]
  216. # if any(keyword in message_lower for keyword in complex_request_keywords):
  217. # self.complex_request_counter += 1
  218. #
  219. # # 如果检测到困难请求且计数达到阈值,触发人工介入
  220. # if self.complex_request_counter >= 1:
  221. # # self._trigger_human_intervention("检测到复杂请求")
  222. # return DialogueState.HUMAN_INTERVENTION
  223. # else:
  224. # # 如果不是复杂请求,重置计数器
  225. # self.complex_request_counter = 0
  226. # 问候检测
  227. greeting_keywords = ["你好", "早上好", "中午好", "晚上好", "嗨", "在吗"]
  228. if any(keyword in message_lower for keyword in greeting_keywords):
  229. return DialogueState.GREETING
  230. # 告别检测
  231. farewell_keywords = ["再见", "拜拜", "晚安", "明天见", "回头见"]
  232. if any(keyword in message_lower for keyword in farewell_keywords):
  233. return DialogueState.FAREWELL
  234. # 澄清请求
  235. clarification_keywords = ["没明白", "不明白", "没听懂", "不懂", "什么意思", "再说一遍"]
  236. if any(keyword in message_lower for keyword in clarification_keywords):
  237. return DialogueState.CLARIFICATION
  238. # 默认为闲聊状态
  239. return DialogueState.CHITCHAT
  240. def _trigger_human_intervention(self, reason: str) -> None:
  241. """触发人工介入"""
  242. if not self.human_intervention_triggered:
  243. self.human_intervention_triggered = True
  244. # 记录人工介入事件
  245. event = {
  246. "timestamp": int(time.time() * 1000),
  247. "reason": reason,
  248. "dialogue_context": self.history_dialogue_service.get_dialogue_history(self.staff_id, self.user_id, 60)
  249. }
  250. # 更新用户资料中的人工介入历史
  251. if "human_intervention_history" not in self.user_profile:
  252. self.user_profile["human_intervention_history"] = []
  253. self.user_profile["human_intervention_history"].append(event)
  254. self.user_manager.save_user_profile(self.user_id, self.user_profile)
  255. # 发送告警
  256. self._send_human_intervention_alert(reason)
  257. def _send_human_intervention_alert(self, reason: str) -> None:
  258. alert_message = f"""
  259. 人工介入告警
  260. 用户ID: {self.user_id}
  261. 用户昵称: {self.user_profile.get("nickname", "未知")}
  262. 时间: {int(time.time() * 1000)}
  263. 原因: {reason}
  264. 最近对话:
  265. """
  266. # 添加最近的对话记录
  267. recent_dialogues = self.history_dialogue_service.get_dialogue_history(self.staff_id, self.user_id, 10)
  268. for dialogue in recent_dialogues:
  269. alert_message += f"\n{dialogue['role']}: {dialogue['content']}"
  270. # TODO(zhoutian): 实现发送告警的具体逻辑
  271. logger.warning(alert_message)
  272. def resume_from_human_intervention(self) -> None:
  273. """从人工介入状态恢复"""
  274. if self.current_state == DialogueState.HUMAN_INTERVENTION:
  275. self.current_state = DialogueState.GREETING
  276. self.human_intervention_triggered = False
  277. self.consecutive_clarifications = 0
  278. self.complex_request_counter = 0
  279. # 记录恢复事件
  280. self.dialogue_history.append({
  281. "role": "system",
  282. "content": "已从人工介入状态恢复到自动对话",
  283. "timestamp": int(time.time() * 1000),
  284. "state": self.current_state.name
  285. })
  286. def generate_response(self, llm_response: str) -> Optional[str]:
  287. """根据当前状态处理LLM响应,如果处于人工介入状态则返回None"""
  288. # 如果处于人工介入状态,不生成回复
  289. if self.current_state == DialogueState.HUMAN_INTERVENTION:
  290. return None
  291. # 记录响应到对话历史
  292. current_ts = int(time.time() * 1000)
  293. self.dialogue_history.append({
  294. "role": "assistant",
  295. "content": llm_response,
  296. "timestamp": current_ts,
  297. "state": self.current_state.name
  298. })
  299. self.last_interaction_time = current_ts
  300. return llm_response
  301. def _get_hours_since_last_interaction(self, precision: int = -1):
  302. time_diff = (time.time() * 1000) - self.last_interaction_time
  303. hours_passed = time_diff / 1000 / 3600
  304. if precision >= 0:
  305. return round(hours_passed, precision)
  306. return hours_passed
  307. def should_initiate_conversation(self) -> bool:
  308. """判断是否应该主动发起对话"""
  309. # 如果处于人工介入状态,不应主动发起对话
  310. if self.current_state == DialogueState.HUMAN_INTERVENTION:
  311. return False
  312. hours_passed = self._get_hours_since_last_interaction()
  313. # 获取当前时间上下文
  314. time_context = self.get_time_context()
  315. # 根据用户交互频率偏好设置不同的阈值
  316. interaction_frequency = self.user_profile.get("interaction_frequency", "medium")
  317. if interaction_frequency == 'stopped':
  318. return False
  319. # 设置不同偏好的交互时间阈值(小时)
  320. thresholds = {
  321. "low": 24, # 低频率:一天一次
  322. "medium": 12, # 中频率:半天一次
  323. "high": 6 # 高频率:大约6小时一次
  324. }
  325. threshold = thresholds.get(interaction_frequency, 12)
  326. if hours_passed < threshold:
  327. return False
  328. # 根据时间上下文决定主动交互的状态
  329. if time_context in [TimeContext.MORNING,
  330. TimeContext.NOON, TimeContext.AFTERNOON]:
  331. self.previous_state = self.current_state
  332. self.current_state = DialogueState.GREETING
  333. return True
  334. return False
  335. def is_in_human_intervention(self) -> bool:
  336. """检查是否处于人工介入状态"""
  337. return self.current_state == DialogueState.HUMAN_INTERVENTION
  338. def get_prompt_context(self, user_message) -> Dict:
  339. # 获取当前时间上下文
  340. time_context = self.get_time_context()
  341. # 刷新用户画像
  342. self.user_profile = self.user_manager.get_user_profile(self.user_id)
  343. # 刷新员工画像(不一定需要)
  344. self.staff_profile = self.user_manager.get_staff_profile(self.staff_id)
  345. context = {
  346. "user_profile": self.user_profile,
  347. "current_state": self.current_state.name,
  348. "previous_state": self.previous_state.name,
  349. "current_time_period": time_context.description,
  350. "current_hour": datetime.now().hour,
  351. "last_interaction_interval": self._get_hours_since_last_interaction(2),
  352. "if_first_interaction": True if self.previous_state == DialogueState.INITIALIZED else False,
  353. "if_active_greeting": False if user_message else True,
  354. **self.user_profile,
  355. **self.staff_profile
  356. }
  357. # 获取长期记忆
  358. relevant_memories = self.vector_memory.retrieve_relevant_memories(user_message)
  359. context["long_term_memory"] = {
  360. "relevant_conversations": relevant_memories
  361. }
  362. return context
  363. @staticmethod
  364. def _select_prompt(state):
  365. state_to_prompt_map = {
  366. DialogueState.GREETING: GENERAL_GREETING_PROMPT,
  367. DialogueState.CHITCHAT: CHITCHAT_PROMPT_COZE,
  368. DialogueState.FAREWELL: GENERAL_GREETING_PROMPT
  369. }
  370. return state_to_prompt_map[state]
  371. @staticmethod
  372. def _select_coze_bot(state):
  373. state_to_bot_map = {
  374. DialogueState.GREETING: '7486112546798780425',
  375. DialogueState.CHITCHAT: '7491300566573301770',
  376. DialogueState.FAREWELL: '7491300566573301770'
  377. }
  378. return state_to_bot_map[state]
  379. def _create_system_message(self, prompt_context):
  380. prompt_template = self._select_prompt(self.current_state)
  381. prompt = prompt_template.format(**prompt_context)
  382. return {'role': 'system', 'content': prompt}
  383. @staticmethod
  384. def compose_chat_messages_openai_compatible(dialogue_history, current_time):
  385. messages = []
  386. for entry in dialogue_history:
  387. role = entry['role']
  388. fmt_time = DialogueManager.format_timestamp(entry['timestamp'])
  389. messages.append({
  390. "role": role,
  391. "content": '[{}] {}'.format(fmt_time, entry["content"])
  392. })
  393. # 添加一条前缀用于 约束时间场景
  394. msg_prefix = '[{}]'.format(current_time)
  395. messages.append({'role': 'assistant', 'content': msg_prefix})
  396. return messages
  397. @staticmethod
  398. def compose_chat_messages_coze(dialogue_history, current_time, staff_id, user_id):
  399. messages = []
  400. # 如果system后的第1条消息不为user,需要补一条user消息
  401. if len(dialogue_history) > 0 and dialogue_history[0]['role'] != 'user':
  402. fmt_time = DialogueManager.format_timestamp(dialogue_history[0]['timestamp'])
  403. messages.append(cozepy.Message.build_user_question_text(f'[{fmt_time}] '))
  404. # coze最后一条消息必须为user,且可能吞掉连续的user消息,故强制增加一条空消息(可参与合并)
  405. dialogue_history.append({
  406. 'role': 'user',
  407. 'content': ' ',
  408. 'timestamp': int(datetime.strptime(current_time, '%Y-%m-%d %H:%M:%S').timestamp() * 1000),
  409. })
  410. # 将连续的同一角色的消息做聚合,避免coze吞消息
  411. messages_to_aggr = []
  412. last_message_role = None
  413. for entry in dialogue_history:
  414. if not entry['content']:
  415. logger.warning("staff[{}], user[{}], role[{}]: empty content in dialogue history".format(
  416. staff_id, user_id, entry['role']
  417. ))
  418. continue
  419. role = entry['role']
  420. if role != last_message_role:
  421. if messages_to_aggr:
  422. aggregated_message = '\n'.join(messages_to_aggr)
  423. messages.append(DialogueManager.build_chat_message(
  424. last_message_role, aggregated_message, ChatServiceType.COZE_CHAT))
  425. messages_to_aggr = []
  426. last_message_role = role
  427. messages_to_aggr.append(DialogueManager.format_dialogue_content(entry))
  428. if messages_to_aggr:
  429. aggregated_message = '\n'.join(messages_to_aggr)
  430. messages.append(DialogueManager.build_chat_message(
  431. last_message_role, aggregated_message, ChatServiceType.COZE_CHAT))
  432. return messages
  433. def build_chat_configuration(
  434. self,
  435. user_message: Optional[str] = None,
  436. chat_service_type: ChatServiceType = ChatServiceType.OPENAI_COMPATIBLE,
  437. overwrite_context: Optional[Dict] = None
  438. ) -> Dict:
  439. """
  440. 参数:
  441. user_message: 当前用户消息,如果是主动交互则为None
  442. 返回:
  443. 消息列表
  444. """
  445. dialogue_history = self.history_dialogue_service.get_dialogue_history(self.staff_id, self.user_id)
  446. logger.debug("staff[{}], user[{}], dialogue_history: {}".format(
  447. self.staff_id, self.user_id, dialogue_history
  448. ))
  449. messages = []
  450. config = {}
  451. prompt_context = self.get_prompt_context(user_message)
  452. if overwrite_context:
  453. prompt_context.update(overwrite_context)
  454. # FIXME(zhoutian): time in string type
  455. current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  456. if overwrite_context and 'current_time' in overwrite_context:
  457. current_time = overwrite_context.get('current_time')
  458. if chat_service_type == ChatServiceType.OPENAI_COMPATIBLE:
  459. system_message = self._create_system_message(prompt_context)
  460. messages.append(system_message)
  461. messages.extend(self.compose_chat_messages_openai_compatible(dialogue_history, current_time))
  462. elif chat_service_type == ChatServiceType.COZE_CHAT:
  463. dialogue_history = dialogue_history[-95:] # Coze最多支持100条,还需要附加系统消息
  464. messages = self.compose_chat_messages_coze(dialogue_history, current_time, self.staff_id, self.user_id)
  465. custom_variables = {}
  466. for k, v in prompt_context.items():
  467. custom_variables[k] = str(v)
  468. custom_variables.pop('user_profile', None)
  469. config['custom_variables'] = custom_variables
  470. config['bot_id'] = self._select_coze_bot(self.current_state)
  471. #FIXME(zhoutian): 临时报警
  472. if user_message and not messages:
  473. logger.error(f"staff[{self.staff_id}], user[{self.user_id}]: inconsistency in messages")
  474. config['messages'] = messages
  475. return config
  476. @staticmethod
  477. def format_timestamp(timestamp_ms):
  478. return datetime.fromtimestamp(timestamp_ms / 1000).strftime("%Y-%m-%d %H:%M:%S")
  479. @staticmethod
  480. def format_dialogue_content(dialogue_entry):
  481. fmt_time = DialogueManager.format_timestamp(dialogue_entry['timestamp'])
  482. content = '[{}] {}'.format(fmt_time, dialogue_entry['content'])
  483. return content
  484. @staticmethod
  485. def build_chat_message(role, content, chat_service_type: ChatServiceType):
  486. if chat_service_type == ChatServiceType.COZE_CHAT:
  487. if role == 'user':
  488. return cozepy.Message.build_user_question_text(content)
  489. elif role == 'assistant':
  490. return cozepy.Message.build_assistant_answer(content)
  491. else:
  492. return {'role': role, 'content': content}
  493. if __name__ == '__main__':
  494. state_cache = DialogueStateCache()
  495. state_cache.set_state('1688854492669990', '7881302581935903', DialogueState.CHITCHAT, DialogueState.GREETING)