mindmap.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. import json
  2. from Log import logger
  3. from app.config.agent_base_url import DF_CHAT_AGENT, RG_CHAT_DIALOG
  4. from app.config.config import settings
  5. from app.config.const import message_error, message_event, complex_knowledge_chat, rg_api_token, workflow_finished
  6. from app.models import ComplexChatSessionDao, ChatData
  7. from app.service.v2.app_driver.chat_agent import ChatAgent
  8. from app.service.v2.app_driver.chat_dialog import ChatDialog
  9. from app.service.v2.chat import get_chat_token
  10. async def service_chat_mindmap_v1(db, message_id, message, mindmap_chat_id, user_id):
  11. res = {}
  12. mindmap_query = ""
  13. complex_log = ComplexChatSessionDao(db)
  14. session = await complex_log.get_session_by_id(message_id)
  15. if session:
  16. token = await get_chat_token(db, session.chat_id)
  17. chat = ChatAgent()
  18. url = settings.dify_base_url + DF_CHAT_AGENT
  19. if session.mindmap:
  20. chat_request = json.loads(session.query)
  21. try:
  22. async for ans in chat.chat_completions(url,
  23. await chat.request_data(message, session.conversation_id,
  24. str(user_id), ChatData(), chat_request.get("files", [])),
  25. await chat.get_headers(token)):
  26. if ans.get("event") == message_error:
  27. return res
  28. elif ans.get("event") == message_event:
  29. mindmap_query += ans.get("answer", "")
  30. else:
  31. continue
  32. except Exception as e:
  33. logger.error(e)
  34. return res
  35. else:
  36. mindmap_query = session.content
  37. try:
  38. mindmap_str = ""
  39. token = await get_chat_token(db, mindmap_chat_id)
  40. async for ans in chat.chat_completions(url,
  41. await chat.request_data(mindmap_query, "",
  42. str(user_id), ChatData()),
  43. await chat.get_headers(token)):
  44. if ans.get("event") == message_error:
  45. return res
  46. elif ans.get("event") == message_event:
  47. mindmap_str += ans.get("answer", "")
  48. else:
  49. continue
  50. except Exception as e:
  51. logger.error(e)
  52. return res
  53. mindmap_list = mindmap_str.split("```")
  54. mindmap_str = mindmap_list[1].lstrip("markdown\n")
  55. if session.mindmap:
  56. node_list = await mindmap_to_merge(session.mindmap, mindmap_str, f"- {message}")
  57. mindmap_str = "\n".join(node_list)
  58. res["mindmap"] = mindmap_str
  59. await complex_log.update_mindmap_by_id(message_id, mindmap_str)
  60. return res
  61. async def service_chat_mindmap(db, message_id, message, mindmap_chat_id, user_id):
  62. res = {}
  63. mindmap_query = ""
  64. complex_log = ComplexChatSessionDao(db)
  65. session = await complex_log.get_session_by_id(message_id)
  66. if session:
  67. token = await get_chat_token(db, session.chat_id)
  68. chat = ChatAgent()
  69. url = settings.dify_base_url + DF_CHAT_AGENT
  70. chat_request = json.loads(session.query)
  71. if session.mindmap:
  72. inputs = {"is_deep": chat_request.get("isDeep", 1)}
  73. if session.chat_mode == complex_knowledge_chat:
  74. token = await get_chat_token(db, rg_api_token)
  75. # print(token)
  76. dialog_url = settings.fwr_base_url + RG_CHAT_DIALOG.format(session.chat_id)
  77. dialog_chat = ChatDialog()
  78. try:
  79. async for ans in dialog_chat.chat_completions(dialog_url, await dialog_chat.complex_request_data(f"简要总结:{message}",
  80. chat_request["knowledgeId"],
  81. session.conversation_id),
  82. await dialog_chat.get_headers(token)):
  83. if ans.get("code", None) == 102:
  84. return res
  85. else:
  86. if isinstance(ans.get("data"), bool) and ans.get("data") is True:
  87. break
  88. else:
  89. data = ans.get("data", {})
  90. mindmap_query = data.get("answer", "")
  91. except Exception as e:
  92. logger.error(e)
  93. else:
  94. try:
  95. async for ans in chat.chat_completions(url,
  96. await chat.complex_request_data(message, session.conversation_id,
  97. str(user_id), files=chat_request.get("files", []), inputs=inputs),
  98. await chat.get_headers(token)):
  99. if ans.get("event") == message_error:
  100. return res
  101. elif ans.get("event") == workflow_finished:
  102. mindmap_query = ans.get("data", {}).get("outputs", {}).get("answer", "")
  103. else:
  104. continue
  105. except Exception as e:
  106. logger.error(e)
  107. return res
  108. else:
  109. mindmap_query = session.content
  110. # print("-----------------", mindmap_query)
  111. try:
  112. if chat_request.get("isDeep", 1) == 2:
  113. mindmap_query = mindmap_query.split("</think>")[-1]
  114. mindmap_str = ""
  115. # print("mindmap_query", mindmap_query)
  116. token = await get_chat_token(db, mindmap_chat_id)
  117. async for ans in chat.chat_completions(url,
  118. await chat.complex_request_data(mindmap_query, "",
  119. str(user_id)),
  120. await chat.get_headers(token)):
  121. # print(ans)
  122. if ans.get("event") == message_error:
  123. return res
  124. elif ans.get("event") == message_event:
  125. mindmap_str += ans.get("answer", "")
  126. else:
  127. continue
  128. except Exception as e:
  129. logger.error(e)
  130. return res
  131. # print(mindmap_str)
  132. if "```json" in mindmap_str:
  133. mindmap_list = mindmap_str.split("```")
  134. mindmap_str = mindmap_list[1].lstrip("json")
  135. mindmap_str = mindmap_str.replace("\n", "")
  136. if session.mindmap:
  137. mindmap_str = await mindmap_merge_dict(session.mindmap, mindmap_str, message)
  138. try:
  139. res_str = await mindmap_join_str(mindmap_str)
  140. res["mindmap"] = res_str
  141. except Exception as e:
  142. logger.error(e)
  143. return res
  144. await complex_log.update_mindmap_by_id(message_id, mindmap_str)
  145. return res
  146. async def mindmap_merge_dict(parent, child, target_node):
  147. parent_dict = json.loads(parent)
  148. if child:
  149. child_dict = json.loads(child)
  150. def iter_dict(node):
  151. if "items" not in node:
  152. if node["title"] == target_node:
  153. node["items"] = child_dict["items"]
  154. return
  155. else:
  156. for i in node["items"]:
  157. iter_dict(i)
  158. iter_dict(parent_dict)
  159. return json.dumps(parent_dict)
  160. async def mindmap_join_str(mindmap_json):
  161. try:
  162. parent_dict = json.loads(mindmap_json)
  163. except Exception as e:
  164. logger.error(e)
  165. return ""
  166. def join_node(node, level):
  167. mindmap_str = ""
  168. if level <= 2:
  169. mindmap_str += f"{'#'*level} {node['title']}\n"
  170. else:
  171. mindmap_str += f"{' '*(level-3)*2}- {node['title']}\n"
  172. for i in node.get("items", []):
  173. mindmap_str += join_node(i, level+1)
  174. return mindmap_str
  175. return join_node(parent_dict, 1)
  176. async def mindmap_to_merge(parent, child, target_node):
  177. level = 0
  178. index = 0
  179. new_node_list = []
  180. parent_list= parent.split("\n")
  181. child_list= child.split("\n")
  182. child_list[0] = target_node
  183. for i, node in enumerate(parent_list):
  184. if node.endswith(target_node):
  185. level = len(node) - len(target_node)
  186. index = i
  187. break
  188. tmp_level = 0
  189. for child in child_list:
  190. if "#" in child:
  191. childs = child.split("#")
  192. tmp_level = len(childs) - 2
  193. new_node_list.append(" "*(level+tmp_level)+ "-"+childs[-1])
  194. elif len(child) == 0:
  195. continue
  196. else:
  197. new_node_list.append(" "*(level+tmp_level)+child)
  198. return parent_list[:index]+new_node_list+parent_list[index+1:]
  199. async def service_message_mindmap_parse(db, message_id, user_id):
  200. res = {}
  201. complex_log = ComplexChatSessionDao(db)
  202. session = await complex_log.get_session_by_id(message_id)
  203. if session.mindmap:
  204. try:
  205. res_str = await mindmap_join_str(session.mindmap)
  206. res["mindmap"] = res_str
  207. except Exception as e:
  208. logger.error(e)
  209. return res
  210. if __name__ == '__main__':
  211. a = '{ "title": "全生命周期管理", "items": [ { "title": "设备规划与采购", "items": [ { "title": "需求分析与选型" ,"items": [{"title": "rererer"}, {"title": "trtrtrtrt"}] }, { "title": "供应商选择与合同管理" } ] }, { "title": "设备安装与调试", "items": [ { "title": "安装规范" }, { "title": "调试测试" } ] }, { "title": "设备使用", "items": [ { "title": "操作培训" }, { "title": "操作规程与记录" } ] }, { "title": "设备维护与维修", "items": [ { "title": "定期维护" }, { "title": "故障诊断" }, { "title": "备件管理" } ] }, { "title": "设备更新与改造", "items": [ { "title": "技术评估" }, { "title": "更新计划" }, { "title": "改造方案" } ] }, { "title": "设备报废", "items": [ { "title": "报废评估" }, { "title": "报废处理" } ] }, { "title": "信息化管理", "items": [ { "title": "设备管理系统" }, { "title": "数据分析" }, { "title": "远程监控" } ] }, { "title": "安全管理", "items": [ { "title": "安全培训" }, { "title": "安全检查" }, { "title": "应急预案" } ] }, { "title": "环境保护", "items": [ { "title": "环保设备" }, { "title": "废物处理" }, { "title": "节能减排" } ] }, { "title": "具体实践案例", "items": [ { "title": "高压开关设备润滑脂选用研究" }, { "title": "环保型 C4 混气 GIS 设备运维技术研究" } ] }, { "title": "总结", "items": [ { "title": "提高运营效率和竞争力" } ] } ]}'
  212. b = mindmap_merge_dict(a, {}, "设备规划与采购")
  213. print(b)