task_server.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. import json
  2. import threading
  3. import concurrent.futures
  4. import time
  5. import traceback
  6. from concurrent.futures import ThreadPoolExecutor
  7. from datetime import datetime
  8. from typing import Dict
  9. from sqlalchemy import func
  10. from pqai_agent import logging_service
  11. from pqai_agent.agents.message_push_agent import MessagePushAgent
  12. from pqai_agent.agents.multimodal_chat_agent import MultiModalChatAgent
  13. from pqai_agent.data_models.agent_configuration import AgentConfiguration
  14. from pqai_agent.data_models.agent_test_task import AgentTestTask
  15. from pqai_agent.data_models.agent_test_task_conversations import AgentTestTaskConversations
  16. from pqai_agent.data_models.service_module import ServiceModule
  17. from pqai_agent.utils.prompt_utils import format_agent_profile
  18. from pqai_agent_server.const.status_enum import TestTaskConversationsStatus, TestTaskStatus, get_test_task_status_desc
  19. from concurrent.futures import ThreadPoolExecutor
  20. from scripts.evaluate_agent import evaluate_agent
  21. logger = logging_service.logger
  22. class TaskManager:
  23. """任务管理器"""
  24. def __init__(self, session_maker, dataset_service):
  25. self.session_maker = session_maker
  26. self.dataset_service = dataset_service
  27. self.task_events = {} # 任务ID -> Event (用于取消任务)
  28. self.task_locks = {} # 任务ID -> Lock (用于任务状态同步)
  29. self.running_tasks = set()
  30. self.executor = ThreadPoolExecutor(max_workers=20, thread_name_prefix='TaskWorker')
  31. self.create_task_executor = ThreadPoolExecutor(max_workers=10, thread_name_prefix='CreateTaskWorker')
  32. self.task_futures = {} # 任务ID -> Future
  33. def get_test_task_list(self, page_num: int, page_size: int) -> Dict:
  34. with self.session_maker() as session:
  35. # 计算偏移量
  36. offset = (page_num - 1) * page_size
  37. # 查询分页数据
  38. result = (session.query(AgentTestTask, AgentConfiguration)
  39. .outerjoin(AgentConfiguration, AgentTestTask.agent_id == AgentConfiguration.id)
  40. .limit(page_size).offset(offset).all())
  41. # 查询总记录数
  42. total = session.query(func.count(AgentTestTask.id)).scalar()
  43. total_page = total // page_size + 1 if total % page_size > 0 else total // page_size
  44. total_page = 1 if total_page <= 0 else total_page
  45. response_data = [
  46. {
  47. "id": agent_test_task.id,
  48. "agentName": agent_configuration.name,
  49. "createUser": agent_test_task.create_user,
  50. "updateUser": agent_test_task.update_user,
  51. "statusName": get_test_task_status_desc(agent_test_task.status),
  52. "createTime": agent_test_task.create_time.strftime("%Y-%m-%d %H:%M:%S"),
  53. "updateTime": agent_test_task.update_time.strftime("%Y-%m-%d %H:%M:%S")
  54. }
  55. for agent_test_task, agent_configuration in result
  56. ]
  57. return {
  58. "currentPage": page_num,
  59. "pageSize": page_size,
  60. "totalSize": total_page,
  61. "total": total,
  62. "list": response_data,
  63. }
  64. def get_test_task_conversations(self, task_id: int, page_num: int, page_size: int) -> Dict:
  65. with self.session_maker() as session:
  66. # 计算偏移量
  67. offset = (page_num - 1) * page_size
  68. # 查询分页数据
  69. result = (session.query(AgentTestTaskConversations, AgentConfiguration)
  70. .outerjoin(AgentConfiguration, AgentTestTaskConversations.agent_id == AgentConfiguration.id)
  71. .filter(AgentTestTaskConversations.task_id == task_id)
  72. .limit(page_size).offset(offset).all())
  73. # 查询总记录数
  74. total = session.query(func.count(AgentTestTaskConversations.id)).scalar()
  75. total_page = total // page_size + 1 if total % page_size > 0 else total // page_size
  76. total_page = 1 if total_page <= 0 else total_page
  77. response_data = [
  78. {
  79. "id": agent_test_task_conversation.id,
  80. "agentName": agent_configuration.name,
  81. "input": MultiModalChatAgent.compose_dialogue(json.loads(agent_test_task_conversation.input)),
  82. "output": agent_test_task_conversation.output,
  83. "score": agent_test_task_conversation.score,
  84. "statusName": get_test_task_status_desc(agent_test_task_conversation.status),
  85. "createTime": agent_test_task_conversation.create_time.strftime("%Y-%m-%d %H:%M:%S"),
  86. "updateTime": agent_test_task_conversation.update_time.strftime("%Y-%m-%d %H:%M:%S")
  87. }
  88. for agent_test_task_conversation, agent_configuration in result
  89. ]
  90. return {
  91. "currentPage": page_num,
  92. "pageSize": page_size,
  93. "totalSize": total_page,
  94. "total": total,
  95. "list": response_data,
  96. }
  97. def create_task(self, agent_id: int, module_id: int, evaluate_type: int) -> Dict:
  98. """创建新任务"""
  99. with self.session_maker() as session:
  100. agent_test_task = AgentTestTask(agent_id=agent_id, module_id=module_id, evaluate_type=evaluate_type,
  101. status=TestTaskStatus.CREATING.value)
  102. session.add(agent_test_task)
  103. session.commit() # 显式提交
  104. task_id = agent_test_task.id
  105. # 异步执行创建任务
  106. self.create_task_executor.submit(self._generate_agent_test_task_conversation_batch, task_id, agent_id,
  107. module_id)
  108. return self.get_task(task_id)
  109. def _generate_agent_test_task_conversation_batch(self, task_id: int, agent_id: int, module_id: int):
  110. """异步生成子任务"""
  111. try:
  112. # 获取数据集列表
  113. dataset_module_list = self.dataset_service.get_dataset_module_list_by_module(module_id)
  114. # 批量处理数据集 - 减少数据库交互
  115. batch_size = 100 # 每批处理100个子任务
  116. agent_test_task_conversation_batch = []
  117. for dataset_module in dataset_module_list:
  118. # 获取对话数据列表
  119. conversation_datas = self.dataset_service.get_conversation_data_list_by_dataset(
  120. dataset_module.dataset_id)
  121. for conversation_data in conversation_datas:
  122. # 创建子任务对象
  123. agent_test_task_conversation = AgentTestTaskConversations(
  124. task_id=task_id,
  125. agent_id=agent_id,
  126. dataset_id=dataset_module.dataset_id,
  127. conversation_id=conversation_data.id,
  128. status=TestTaskConversationsStatus.PENDING.value
  129. )
  130. agent_test_task_conversation_batch.append(agent_test_task_conversation)
  131. # 批量提交
  132. if len(agent_test_task_conversation_batch) >= batch_size:
  133. self.save_agent_test_task_conversation_batch(agent_test_task_conversation_batch)
  134. agent_test_task_conversation_batch = []
  135. # 提交剩余的子任务
  136. if agent_test_task_conversation_batch:
  137. self.save_agent_test_task_conversation_batch(agent_test_task_conversation_batch)
  138. # 更新主任务状态为未开始
  139. self.update_task_status(task_id, TestTaskStatus.NOT_STARTED.value)
  140. # 自动提交任务执行
  141. self._execute_task(task_id)
  142. except Exception as e:
  143. logger.error(f"生成子任务失败: {str(e)}")
  144. # 更新任务状态为失败
  145. self.update_task_status(task_id, TestTaskStatus.CREATED_FAIL.value)
  146. def save_agent_test_task_conversation_batch(self, agent_test_task_conversation_batch: list):
  147. """批量保存子任务到数据库"""
  148. try:
  149. with self.session_maker() as session:
  150. with session.begin():
  151. session.add_all(agent_test_task_conversation_batch)
  152. except Exception as e:
  153. logger.error(e)
  154. def get_agent_configuration_by_task_id(self, task_id: int):
  155. """获取指定任务ID对应的Agent配置信息"""
  156. with self.session_maker() as session:
  157. return session.query(AgentConfiguration) \
  158. .join(AgentTestTask, AgentTestTask.agent_id == AgentConfiguration.id) \
  159. .filter(AgentTestTask.id == task_id) \
  160. .one_or_none() # 返回单个对象或None(如果未找到)
  161. def get_service_module_by_task_id(self, task_id: int):
  162. """获取指定任务ID对应的Agent配置信息"""
  163. with self.session_maker() as session:
  164. return session.query(ServiceModule) \
  165. .join(AgentTestTask, AgentTestTask.module_id == ServiceModule.id) \
  166. .filter(AgentTestTask.id == task_id) \
  167. .one_or_none() # 返回单个对象或None(如果未找到)
  168. def get_task(self, task_id: int):
  169. """获取任务信息"""
  170. with self.session_maker() as session:
  171. return session.query(AgentTestTask).filter(AgentTestTask.id == task_id).one()
  172. def get_in_progress_task(self):
  173. """获取执行中任务"""
  174. with self.session_maker() as session:
  175. return session.query(AgentTestTask).filter(AgentTestTask.status == TestTaskStatus.IN_PROGRESS.value).all()
  176. def get_creating_task(self):
  177. """获取执行中任务"""
  178. with self.session_maker() as session:
  179. return session.query(AgentTestTask).filter(AgentTestTask.status == TestTaskStatus.CREATING.value).all()
  180. def get_task_conversations(self, task_id: int):
  181. """获取任务的所有子任务"""
  182. with self.session_maker() as session:
  183. return session.query(AgentTestTaskConversations).filter(AgentTestTaskConversations.task_id == task_id).all()
  184. def del_task_conversations(self, task_id: int):
  185. with self.session_maker() as session:
  186. session.query(AgentTestTaskConversations).filter(AgentTestTaskConversations.task_id == task_id).delete()
  187. # 提交事务生效
  188. session.commit()
  189. def get_pending_task_conversations(self, task_id: int):
  190. """获取待处理的子任务"""
  191. with self.session_maker() as session:
  192. return session.query(AgentTestTaskConversations).filter(
  193. AgentTestTaskConversations.task_id == task_id).filter(
  194. AgentTestTaskConversations.status.in_([
  195. TestTaskConversationsStatus.PENDING.value,
  196. TestTaskConversationsStatus.RUNNING.value
  197. ])).all()
  198. def update_task_status(self, task_id: int, status: int):
  199. """更新任务状态"""
  200. with self.session_maker() as session:
  201. session.query(AgentTestTask).filter(AgentTestTask.id == task_id).update(
  202. {"status": status, "update_time": datetime.now()})
  203. session.commit()
  204. def update_task_conversations_status(self, task_conversations_id: int, status: int):
  205. """更新子任务状态"""
  206. with self.session_maker() as session:
  207. session.query(AgentTestTaskConversations).filter(
  208. AgentTestTaskConversations.id == task_conversations_id).update(
  209. {"status": status, "update_time": datetime.now()})
  210. session.commit()
  211. def update_task_conversations_res(self, task_conversations_id: int, status: int, input: str, output: str,
  212. score: str):
  213. """更新子任务结果"""
  214. with self.session_maker() as session:
  215. session.query(AgentTestTaskConversations).filter(
  216. AgentTestTaskConversations.id == task_conversations_id).update(
  217. {"status": status, "input": input, "output": output, "score": score, "update_time": datetime.now()})
  218. session.commit()
  219. def cancel_task(self, task_id: int):
  220. """取消任务(带事务支持)"""
  221. # 设置取消事件
  222. if task_id in self.task_events:
  223. self.task_events[task_id].set()
  224. # 如果任务正在执行,尝试取消Future
  225. if task_id in self.task_futures:
  226. self.task_futures[task_id].cancel()
  227. with self.session_maker() as session:
  228. with session.begin():
  229. session.query(AgentTestTask).filter(AgentTestTask.id == task_id).update(
  230. {"status": TestTaskStatus.CANCELLED.value})
  231. session.query(AgentTestTaskConversations).filter(AgentTestTaskConversations.task_id == task_id).filter(
  232. AgentTestTaskConversations.status == TestTaskConversationsStatus.PENDING.value).update(
  233. {"status": TestTaskConversationsStatus.CANCELLED.value})
  234. session.commit()
  235. def resume_task(self, task_id: int) -> bool:
  236. """恢复已取消的任务"""
  237. task = self.get_task(task_id)
  238. if not task or task.status != TestTaskStatus.CANCELLED.value:
  239. return False
  240. with self.session_maker() as session:
  241. with session.begin():
  242. session.query(AgentTestTask).filter(AgentTestTask.id == task_id).update(
  243. {"status": TestTaskStatus.NOT_STARTED.value})
  244. session.query(AgentTestTaskConversations).filter(AgentTestTaskConversations.task_id == task_id).filter(
  245. AgentTestTaskConversations.status == TestTaskConversationsStatus.CANCELLED.value).update(
  246. {"status": TestTaskConversationsStatus.PENDING.value})
  247. session.commit()
  248. # 重新执行任务
  249. self._execute_task(task_id)
  250. logger.info(f"Resumed task {task_id}")
  251. return True
  252. def recover_tasks(self):
  253. """服务启动时恢复未完成的任务"""
  254. creating = self.get_creating_task()
  255. for task in creating:
  256. task_id = task.id
  257. agent_id = task.agent_id
  258. module_id = task.module_id
  259. self.del_task_conversations(task_id)
  260. # 重新提交任务
  261. # 异步执行创建任务
  262. self.create_task_executor.submit(self._generate_agent_test_task_conversation_batch, task_id, agent_id,
  263. module_id)
  264. # 获取所有进行中的任务ID(根据实际状态定义查询)
  265. in_progress_tasks = self.get_in_progress_task()
  266. for task in in_progress_tasks:
  267. task_id = task.id
  268. # 重新提交任务
  269. self._execute_task(task_id)
  270. def _execute_task(self, task_id: int):
  271. """提交任务到线程池执行"""
  272. # 确保任务状态一致性
  273. if task_id in self.running_tasks:
  274. return
  275. # 创建任务事件和锁
  276. if task_id not in self.task_events:
  277. self.task_events[task_id] = threading.Event()
  278. if task_id not in self.task_locks:
  279. self.task_locks[task_id] = threading.Lock()
  280. # 提交到线程池
  281. future = self.executor.submit(self._process_task, task_id)
  282. self.task_futures[task_id] = future
  283. # 标记任务为运行中
  284. with self.task_locks[task_id]:
  285. self.running_tasks.add(task_id)
  286. def _process_task(self, task_id: int):
  287. """处理任务的所有子任务(并发执行)"""
  288. try:
  289. self.update_task_status(task_id, TestTaskStatus.IN_PROGRESS.value)
  290. task_conversations = self.get_pending_task_conversations(task_id)
  291. if not task_conversations:
  292. self.update_task_status(task_id, TestTaskStatus.COMPLETED.value)
  293. return
  294. agent_configuration = self.get_agent_configuration_by_task_id(task_id)
  295. query_prompt_template = agent_configuration.task_prompt
  296. task = self.get_task(task_id)
  297. # 使用线程池执行子任务
  298. with ThreadPoolExecutor(max_workers=8) as executor: # 可根据需要调整并发数
  299. futures = {}
  300. for task_conversation in task_conversations:
  301. if self.task_events[task_id].is_set():
  302. break # 检查任务取消事件
  303. # 提交子任务到线程池
  304. future = executor.submit(
  305. self._process_single_conversation,
  306. task_id,
  307. task,
  308. task_conversation,
  309. query_prompt_template,
  310. agent_configuration
  311. )
  312. futures[future] = task_conversation.id
  313. # 等待所有子任务完成或取消
  314. for future in concurrent.futures.as_completed(futures):
  315. conv_id = futures[future]
  316. try:
  317. future.result() # 获取结果(如有异常会在此抛出)
  318. except Exception as e:
  319. logger.error(f"Subtask {conv_id} failed: {str(e)}")
  320. self.update_task_conversations_status(
  321. conv_id,
  322. TestTaskConversationsStatus.FAILED.value
  323. )
  324. # 检查最终任务状态
  325. self._update_final_task_status(task_id)
  326. except Exception as e:
  327. logger.error(f"Error processing task {task_id}: {str(e)}")
  328. self.update_task_status(task_id, TestTaskStatus.FAILED.value)
  329. finally:
  330. self._cleanup_task_resources(task_id)
  331. def _process_single_conversation(self, task_id, task, task_conversation, query_prompt_template,
  332. agent_configuration):
  333. """处理单个对话子任务(线程安全)"""
  334. # 检查任务是否被取消
  335. if self.task_events[task_id].is_set():
  336. return
  337. # 更新子任务状态
  338. if task_conversation.status == TestTaskConversationsStatus.PENDING.value:
  339. self.update_task_conversations_status(
  340. task_conversation.id,
  341. TestTaskConversationsStatus.RUNNING.value
  342. )
  343. try:
  344. # 创建独立的agent实例(确保线程安全)
  345. agent = MultiModalChatAgent(
  346. model=agent_configuration.execution_model,
  347. system_prompt=agent_configuration.system_prompt,
  348. tools=json.loads(agent_configuration.tools)
  349. )
  350. # 获取对话数据
  351. conversation_data = self.dataset_service.get_conversation_data_by_id(
  352. task_conversation.conversation_id)
  353. user_profile_data = self.dataset_service.get_user_profile_data(
  354. conversation_data.user_id,
  355. conversation_data.version_date.replace("-", ""))
  356. user_profile = json.loads(user_profile_data['profile_data_v1'])
  357. avatar = user_profile_data['iconurl']
  358. staff_profile = self.dataset_service.get_staff_profile_data(
  359. conversation_data.staff_id).agent_profile
  360. conversations = self.dataset_service.get_chat_conversation_list_by_ids(
  361. json.loads(conversation_data.conversation),
  362. conversation_data.staff_id
  363. )
  364. conversations = sorted(conversations, key=lambda i: i['timestamp'], reverse=False)
  365. # 生成推送消息
  366. last_timestamp = int(conversations[-1]["timestamp"])
  367. match task.evaluate_type:
  368. case 0:
  369. send_timestamp = int(last_timestamp / 1000) + 10
  370. case 1:
  371. send_timestamp = int(last_timestamp / 1000) + 24 * 3600
  372. case _:
  373. raise ValueError("evaluate_type must be 0 or 1")
  374. send_time = datetime.fromtimestamp(send_timestamp).strftime('%Y-%m-%d %H:%M:%S')
  375. message = agent._generate_message(
  376. context={
  377. "formatted_staff_profile": staff_profile,
  378. "nickname": user_profile['nickname'],
  379. "name": user_profile['name'],
  380. "avatar": avatar,
  381. "preferred_nickname": user_profile['preferred_nickname'],
  382. "gender": user_profile['gender'],
  383. "age": user_profile['age'],
  384. "region": user_profile['region'],
  385. "health_conditions": user_profile['health_conditions'],
  386. "medications": user_profile['medications'],
  387. "interests": user_profile['interests'],
  388. "current_datetime": send_time
  389. },
  390. dialogue_history=conversations,
  391. query_prompt_template=query_prompt_template
  392. )
  393. if not message:
  394. self.update_task_conversations_status(
  395. task_conversation.id,
  396. TestTaskConversationsStatus.MESSAGE_FAILED.value
  397. )
  398. return
  399. param = {}
  400. param["dialogue_history"] = conversations
  401. param["message"] = message
  402. param["send_time"] = send_time
  403. param["agent_profile"] = json.loads(staff_profile)
  404. param["user_profile"] = user_profile
  405. score = evaluate_agent(param, task.evaluate_type)
  406. if not score:
  407. self.update_task_conversations_status(
  408. task_conversation.id,
  409. TestTaskConversationsStatus.SCORE_FAILED.value
  410. )
  411. return
  412. # 更新子任务结果
  413. self.update_task_conversations_res(
  414. task_conversation.id,
  415. TestTaskConversationsStatus.SUCCESS.value,
  416. json.dumps(conversations, ensure_ascii=False),
  417. json.dumps(message, ensure_ascii=False),
  418. json.dumps(score)
  419. )
  420. except Exception as e:
  421. logger.error(f"Subtask {task_conversation.id} failed: {str(e)}")
  422. self.update_task_conversations_status(
  423. task_conversation.id,
  424. TestTaskConversationsStatus.FAILED.value
  425. )
  426. raise # 重新抛出异常以便主线程捕获
  427. def _update_final_task_status(self, task_id):
  428. """更新任务的最终状态"""
  429. task_conversations = self.get_task_conversations(task_id)
  430. all_completed = all(
  431. conv.status in (TestTaskConversationsStatus.SUCCESS.value,
  432. TestTaskConversationsStatus.FAILED.value)
  433. for conv in task_conversations
  434. )
  435. if all_completed:
  436. self.update_task_status(task_id, TestTaskStatus.COMPLETED.value)
  437. logger.info(f"Task {task_id} completed")
  438. elif not any(
  439. conv.status in (TestTaskConversationsStatus.PENDING.value,
  440. TestTaskConversationsStatus.RUNNING.value)
  441. for conv in task_conversations
  442. ):
  443. current_status = self.get_task(task_id).status
  444. if current_status != TestTaskStatus.CANCELLED.value:
  445. new_status = TestTaskStatus.COMPLETED.value if all_completed else TestTaskStatus.CANCELLED.value
  446. self.update_task_status(task_id, new_status)
  447. def _cleanup_task_resources(self, task_id):
  448. """清理任务资源(线程安全)"""
  449. with self.task_locks[task_id]:
  450. if task_id in self.running_tasks:
  451. self.running_tasks.remove(task_id)
  452. if task_id in self.task_events:
  453. del self.task_events[task_id]
  454. if task_id in self.task_futures:
  455. del self.task_futures[task_id]
  456. def shutdown(self):
  457. """关闭执行器"""
  458. self.executor.shutdown(wait=False)
  459. logger.info("Task executor shutdown")