agent_service.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. #! /usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # vim:fenc=utf-8
  4. import sys
  5. import time
  6. from typing import Dict, List, Tuple, Any, Optional
  7. import logging
  8. from datetime import datetime, timedelta
  9. import apscheduler.triggers.cron
  10. from apscheduler.schedulers.background import BackgroundScheduler
  11. import chat_service
  12. import configs
  13. import global_flags
  14. import logging_service
  15. from chat_service import CozeChat, ChatServiceType
  16. from dialogue_manager import DialogueManager, DialogueState
  17. from user_manager import UserManager, LocalUserManager, MySQLUserManager
  18. from openai import OpenAI
  19. from message_queue_backend import MessageQueueBackend, MemoryQueueBackend, AliyunRocketMQQueueBackend
  20. from user_profile_extractor import UserProfileExtractor
  21. import threading
  22. from message import MessageType, Message, MessageChannel
  23. from logging_service import ColoredFormatter
  24. class AgentService:
  25. def __init__(
  26. self,
  27. receive_backend: MessageQueueBackend,
  28. send_backend: MessageQueueBackend,
  29. human_backend: MessageQueueBackend,
  30. user_manager: UserManager,
  31. chat_service_type: ChatServiceType = ChatServiceType.OPENAI_COMPATIBLE
  32. ):
  33. self.receive_queue = receive_backend
  34. self.send_queue = send_backend
  35. self.human_queue = human_backend
  36. # 核心服务模块
  37. self.user_manager = user_manager
  38. self.user_profile_extractor = UserProfileExtractor()
  39. self.agent_registry: Dict[str, DialogueManager] = {}
  40. self.llm_client = OpenAI(
  41. api_key=chat_service.VOLCENGINE_API_TOKEN,
  42. base_url=chat_service.VOLCENGINE_BASE_URL
  43. )
  44. # DeepSeek on Volces
  45. self.model_name = chat_service.VOLCENGINE_MODEL_DEEPSEEK_V3
  46. self.coze_client = CozeChat(
  47. token=chat_service.COZE_API_TOKEN,
  48. base_url=chat_service.COZE_CN_BASE_URL
  49. )
  50. self.chat_service_type = chat_service_type
  51. # 定时任务调度器
  52. self.scheduler = BackgroundScheduler()
  53. self.scheduler.start()
  54. def setup_initiative_conversations(self, schedule_params: Optional[Dict] = None):
  55. if not schedule_params:
  56. schedule_params = {'hour': '8,16,20'}
  57. self.scheduler.add_job(
  58. self._check_initiative_conversations,
  59. apscheduler.triggers.cron.CronTrigger(**schedule_params)
  60. )
  61. def _get_agent_instance(self, staff_id: str, user_id: str) -> DialogueManager:
  62. """获取Agent实例"""
  63. agent_key = 'agent_{}_{}'.format(staff_id, user_id)
  64. if agent_key not in self.agent_registry:
  65. self.agent_registry[agent_key] = DialogueManager(
  66. staff_id, user_id, self.user_manager)
  67. return self.agent_registry[agent_key]
  68. def process_messages(self):
  69. """持续处理接收队列消息"""
  70. while True:
  71. message = self.receive_queue.consume()
  72. if message:
  73. try:
  74. self.process_single_message(message)
  75. except Exception as e:
  76. logging.error("Error processing message: {}".format(e))
  77. # 无论处理是否有异常,都ACK消息
  78. self.receive_queue.ack(message)
  79. time.sleep(1)
  80. def _update_user_profile(self, user_id, user_profile, message: str):
  81. profile_to_update = self.user_profile_extractor.extract_profile_info(user_profile, message)
  82. if not profile_to_update:
  83. logging.debug("user_id: {}, no profile info extracted".format(user_id))
  84. return
  85. logging.warning("update user profile: {}".format(profile_to_update))
  86. merged_profile = self.user_profile_extractor.merge_profile_info(user_profile, profile_to_update)
  87. self.user_manager.save_user_profile(user_id, merged_profile)
  88. return merged_profile
  89. def _schedule_aggregation_trigger(self, staff_id: str, user_id: str, delay_sec: int):
  90. logging.debug("user: {}, schedule trigger message after {} seconds".format(user_id, delay_sec))
  91. message_ts = int((time.time() + delay_sec) * 1000)
  92. message = Message.build(MessageType.AGGREGATION_TRIGGER, MessageChannel.SYSTEM, user_id, staff_id, None, message_ts)
  93. # 系统消息使用特定的msgId,无实际意义
  94. message.msgId = -MessageType.AGGREGATION_TRIGGER.value
  95. self.scheduler.add_job(lambda: self.receive_queue.produce(message),
  96. 'date',
  97. run_date=datetime.now() + timedelta(seconds=delay_sec))
  98. def process_single_message(self, message: Message):
  99. user_id = message.sender
  100. staff_id = message.receiver
  101. # 获取用户信息和Agent实例
  102. user_profile = self.user_manager.get_user_profile(user_id)
  103. agent = self._get_agent_instance(staff_id, user_id)
  104. # 更新对话状态
  105. logging.debug("process message: {}".format(message))
  106. dialogue_state, message_text = agent.update_state(message)
  107. logging.debug("user: {}, next state: {}".format(user_id, dialogue_state))
  108. # 根据状态路由消息
  109. if agent.is_in_human_intervention():
  110. self._route_to_human_intervention(user_id, message)
  111. elif dialogue_state == DialogueState.MESSAGE_AGGREGATING:
  112. if message.type != MessageType.AGGREGATION_TRIGGER:
  113. # 产生一个触发器,但是不能由触发器递归产生
  114. logging.debug("user: {}, waiting next message for aggregation".format(user_id))
  115. self._schedule_aggregation_trigger(staff_id, user_id, agent.message_aggregation_sec)
  116. return
  117. else:
  118. # 先更新用户画像再处理回复
  119. self._update_user_profile(user_id, user_profile, message_text)
  120. self._get_chat_response(user_id, agent, message_text)
  121. def _route_to_human_intervention(self, user_id: str, origin_message: Message):
  122. """路由到人工干预"""
  123. self.human_queue.produce(Message.build(
  124. MessageType.TEXT,
  125. origin_message.channel,
  126. origin_message.sender,
  127. origin_message.receiver,
  128. "用户对话需人工介入,用户名:{}".format(user_id),
  129. int(time.time() * 1000)
  130. ))
  131. def _check_initiative_conversations(self):
  132. """定时检查主动发起对话"""
  133. for user_id in self.user_manager.list_all_users():
  134. #FIXME(zhoutian): 需要企微账号与用户关系
  135. agent = self._get_agent_instance('staff_id_0', user_id)
  136. should_initiate = agent.should_initiate_conversation()
  137. if should_initiate:
  138. logging.warning("user: {}, initiate conversation".format(user_id))
  139. self._get_chat_response(user_id, agent, None)
  140. else:
  141. logging.debug("user: {}, do not initiate conversation".format(user_id))
  142. def _get_chat_response(self, user_id: str, agent: DialogueManager,
  143. user_message: str):
  144. """处理LLM响应"""
  145. chat_config = agent.build_chat_configuration(user_message, self.chat_service_type)
  146. logging.debug(chat_config)
  147. chat_response = self._call_chat_api(chat_config)
  148. if response := agent.generate_response(chat_response):
  149. logging.warning("user: {}, response: {}".format(user_id, response))
  150. current_ts = int(time.time() * 1000)
  151. self.send_queue.produce(
  152. Message.build(MessageType.TEXT, MessageChannel.CORP_WECHAT,
  153. agent.staff_id, user_id, response, current_ts)
  154. )
  155. def _call_chat_api(self, chat_config: Dict) -> str:
  156. if configs.get().get('debug_flags', {}).get('disable_llm_api_call', False):
  157. return 'LLM模拟回复 {}'.format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  158. if self.chat_service_type == ChatServiceType.OPENAI_COMPATIBLE:
  159. chat_completion = self.llm_client.chat.completions.create(
  160. messages=chat_config['messages'],
  161. model=self.model_name,
  162. )
  163. response = chat_completion.choices[0].message.content
  164. elif self.chat_service_type == ChatServiceType.COZE_CHAT:
  165. bot_user_id = 'dev_user'
  166. response = self.coze_client.create(
  167. chat_config['bot_id'], bot_user_id, chat_config['messages'],
  168. chat_config['custom_variables']
  169. )
  170. else:
  171. raise Exception('Unsupported chat service type: {}'.format(self.chat_service_type))
  172. return response
  173. if __name__ == "__main__":
  174. config = configs.get()
  175. logging_service.setup_root_logger()
  176. scheduler_logger = logging.getLogger('apscheduler')
  177. scheduler_logger.setLevel(logging.WARNING)
  178. use_aliyun_mq = config['use_aliyun_mq']
  179. # 初始化不同队列的后端
  180. if use_aliyun_mq:
  181. receive_queue = AliyunRocketMQQueueBackend(
  182. config['mq']['endpoints'],
  183. config['mq']['instance_id'],
  184. config['mq']['receive_topic'],
  185. has_consumer=True, has_producer=True,
  186. group_id=config['mq']['receive_group']
  187. )
  188. send_queue = AliyunRocketMQQueueBackend(
  189. config['mq']['endpoints'],
  190. config['mq']['instance_id'],
  191. config['mq']['send_topic'],
  192. has_consumer=False, has_producer=True
  193. )
  194. else:
  195. receive_queue = MemoryQueueBackend()
  196. send_queue = MemoryQueueBackend()
  197. human_queue = MemoryQueueBackend()
  198. # 初始化用户管理服务
  199. if config['debug_flags'].get('use_local_user_manager', False):
  200. user_manager = LocalUserManager()
  201. else:
  202. db_config = config['storage']['user']
  203. user_manager = MySQLUserManager(db_config['mysql'], db_config['table'])
  204. # 创建Agent服务
  205. service = AgentService(
  206. receive_backend=receive_queue,
  207. send_backend=send_queue,
  208. human_backend=human_queue,
  209. user_manager=user_manager,
  210. chat_service_type=ChatServiceType.COZE_CHAT
  211. )
  212. # 只有企微场景需要主动发起
  213. # service.setup_initiative_conversations({'second': '5,35'})
  214. process_thread = threading.Thread(target=service.process_messages)
  215. process_thread.start()
  216. console_input = True
  217. if not console_input:
  218. process_thread.join()
  219. sys.exit(0)
  220. message_id = 0
  221. while True:
  222. print("Input next message: ")
  223. text = sys.stdin.readline().strip()
  224. if not text:
  225. continue
  226. message_id += 1
  227. message = Message.build(MessageType.TEXT, MessageChannel.CORP_WECHAT,
  228. '7881302581935903','1688854492669990', text, int(time.time() * 1000)
  229. )
  230. message.msgId = message_id
  231. receive_queue.produce(message)
  232. time.sleep(0.1)
  233. process_thread.join()