chat.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. import asyncio
  2. import io
  3. import json
  4. import time
  5. import uuid
  6. import fitz
  7. from fastapi import HTTPException
  8. from sqlalchemy import or_
  9. from Log import logger
  10. from app.config.agent_base_url import RG_CHAT_DIALOG, DF_CHAT_AGENT, DF_CHAT_PARAMETERS, RG_CHAT_SESSIONS, \
  11. DF_CHAT_WORKFLOW, DF_UPLOAD_FILE, RG_ORIGINAL_URL
  12. from app.config.config import settings
  13. from app.config.const import *
  14. from app.models import DialogModel, ApiTokenModel, UserTokenModel, ComplexChatSessionDao, ChatDataRequest, \
  15. ComplexChatDao, KnowledgeModel, UserModel, KnowledgeUserModel
  16. from app.models.v2.session_model import ChatSessionDao, ChatData
  17. from app.service.v2.app_driver.chat_agent import ChatAgent
  18. from app.service.v2.app_driver.chat_data import ChatBaseApply
  19. from app.service.v2.app_driver.chat_dialog import ChatDialog
  20. from app.service.v2.app_driver.chat_workflow import ChatWorkflow
  21. from docx import Document
  22. from dashscope import get_tokenizer # dashscope版本 >= 1.14.0
  23. async def update_session_log(db, session_id: str, message: dict, conversation_id: str):
  24. await ChatSessionDao(db).update_session_by_id(
  25. session_id=session_id,
  26. session=None,
  27. message=message,
  28. conversation_id=conversation_id
  29. )
  30. async def add_session_log(db, session_id: str, question: str, chat_id: str, user_id, event_type: str,
  31. conversation_id: str, agent_type, query: dict=None):
  32. try:
  33. session = await ChatSessionDao(db).update_or_insert_by_id(
  34. session_id=session_id,
  35. name=question[:255],
  36. agent_id=chat_id,
  37. agent_type=agent_type,
  38. tenant_id=user_id,
  39. message={"role": "user", "content": question, "query": query},
  40. conversation_id=conversation_id,
  41. event_type=event_type
  42. )
  43. return session
  44. except Exception as e:
  45. logger.error(e)
  46. return None
  47. async def get_app_token(db, app_id):
  48. app_token = db.query(UserTokenModel).filter_by(id=app_id).first()
  49. if app_token:
  50. return app_token.access_token
  51. return ""
  52. async def get_chat_token(db, app_id):
  53. app_token = db.query(ApiTokenModel).filter_by(app_id=app_id).first()
  54. if app_token:
  55. return app_token.token
  56. return ""
  57. async def add_chat_token(db, data):
  58. try:
  59. api_token = ApiTokenModel(**data)
  60. db.add(api_token)
  61. db.commit()
  62. except Exception as e:
  63. logger.error(e)
  64. async def get_chat_info(db, chat_id: str):
  65. return db.query(DialogModel).filter_by(id=chat_id, status=Dialog_STATSU_ON).first()
  66. async def get_chat_object(mode):
  67. if mode == workflow_chat:
  68. url = settings.dify_base_url + DF_CHAT_WORKFLOW
  69. return ChatWorkflow(), url
  70. else:
  71. url = settings.dify_base_url + DF_CHAT_AGENT
  72. return ChatAgent(), url
  73. async def get_user_kb(db, user_id: int, kb_ids: list) -> list:
  74. res = []
  75. user = db.query(UserModel).filter(UserModel.id == user_id).first()
  76. if user is None:
  77. return res
  78. query = db.query(KnowledgeModel)
  79. if user.permission != "admin":
  80. klg_list = [j.id for i in user.groups for j in i.knowledges]
  81. for i in db.query(KnowledgeUserModel).filter(KnowledgeUserModel.user_id == user_id, KnowledgeUserModel.status == 1).all():
  82. if i.kb_id not in klg_list:
  83. klg_list.append(i.kb_id)
  84. query = query.filter(or_(KnowledgeModel.id.in_(klg_list), KnowledgeModel.tenant_id == str(user_id)))
  85. kb_list= query.all()
  86. for kb in kb_list:
  87. if kb.id in kb_ids:
  88. if kb.permission == "team":
  89. res.append(kb.id)
  90. elif kb.tenant_id == str(user_id):
  91. res.append(kb.id)
  92. return res
  93. else:
  94. return kb_ids
  95. async def service_chat_dialog(db, chat_id: str, question: str, session_id: str, user_id: int, mode: str, kb_ids: list):
  96. conversation_id = ""
  97. token = await get_chat_token(db, rg_api_token)
  98. url = settings.fwr_base_url + RG_CHAT_DIALOG.format(chat_id)
  99. kb_id = await get_user_kb(db, user_id, kb_ids)
  100. if not kb_id:
  101. yield "data: " + json.dumps({"message": smart_message_error,
  102. "error": "\n**ERROR**: The agent has no knowledge base to work with!", "status": http_400},
  103. ensure_ascii=False) + "\n\n"
  104. return
  105. chat = ChatDialog()
  106. session = await add_session_log(db, session_id, question, chat_id, user_id, mode, session_id, RG_TYPE)
  107. if session:
  108. conversation_id = session.conversation_id
  109. message = {"role": "assistant", "answer": "", "reference": {}}
  110. try:
  111. async for ans in chat.chat_completions(url, await chat.complex_request_data(question, kb_id, conversation_id),
  112. await chat.get_headers(token)):
  113. data = {}
  114. error = ""
  115. status = http_200
  116. if ans.get("code", None) == 102:
  117. error = ans.get("message", "error!")
  118. status = http_400
  119. event = smart_message_error
  120. else:
  121. if isinstance(ans.get("data"), bool) and ans.get("data") is True:
  122. event = smart_message_end
  123. else:
  124. data = ans.get("data", {})
  125. # conversation_id = data.get("session_id", "")
  126. if "session_id" in data:
  127. del data["session_id"]
  128. message = data
  129. event = smart_message_cover
  130. message_str = "data: " + json.dumps(
  131. {"event": event, "data": data, "error": error, "status": status, "session_id": session_id},
  132. ensure_ascii=False) + "\n\n"
  133. for i in range(0, len(message_str), max_chunk_size):
  134. chunk = message_str[i:i + max_chunk_size]
  135. # print(chunk)
  136. yield chunk # 发送分块消息
  137. except Exception as e:
  138. logger.error(e)
  139. try:
  140. yield "data: " + json.dumps({"message": smart_message_error,
  141. "error": "\n**ERROR**: " + str(e), "status": http_500},
  142. ensure_ascii=False) + "\n\n"
  143. except:
  144. ...
  145. finally:
  146. message["role"] = "assistant"
  147. await update_session_log(db, session_id, message, conversation_id)
  148. async def data_process(data):
  149. if isinstance(data, str):
  150. return data.replace("dify", "smart")
  151. elif isinstance(data, dict):
  152. for k in list(data.keys()):
  153. if isinstance(k, str) and "dify" in k:
  154. new_k = k.replace("dify", "smart")
  155. data[new_k] = await data_process(data[k])
  156. del data[k]
  157. else:
  158. data[k] = await data_process(data[k])
  159. return data
  160. elif isinstance(data, list):
  161. for i in range(len(data)):
  162. data[i] = await data_process(data[i])
  163. return data
  164. else:
  165. return data
  166. async def service_chat_workflow(db, chat_id: str, chat_data: ChatData, session_id: str, user_id, mode: str):
  167. conversation_id = ""
  168. answer_event = ""
  169. answer_agent = ""
  170. answer_workflow = ""
  171. download_url = ""
  172. message_id = ""
  173. task_id = ""
  174. error = ""
  175. files = []
  176. node_list = []
  177. token = await get_chat_token(db, chat_id)
  178. chat, url = await get_chat_object(mode)
  179. if hasattr(chat_data, "query"):
  180. query = chat_data.query
  181. else:
  182. query = "start new conversation"
  183. session = await add_session_log(db, session_id, query if query else "start new conversation", chat_id, user_id,
  184. mode, conversation_id, DF_TYPE, chat_data.to_dict())
  185. if session:
  186. conversation_id = session.conversation_id
  187. try:
  188. async for ans in chat.chat_completions(url,
  189. await chat.request_data(query, conversation_id, str(user_id), chat_data),
  190. await chat.get_headers(token)):
  191. data = {}
  192. status = http_200
  193. conversation_id = ans.get("conversation_id")
  194. task_id = ans.get("task_id")
  195. if ans.get("event") == message_error:
  196. error = ans.get("message", "参数异常!")
  197. status = http_400
  198. event = smart_message_error
  199. elif ans.get("event") == message_agent:
  200. data = {"answer": ans.get("answer", ""), "id": ans.get("message_id", "")}
  201. answer_agent += ans.get("answer", "")
  202. message_id = ans.get("message_id", "")
  203. event = smart_message_stream
  204. elif ans.get("event") == message_event:
  205. data = {"answer": ans.get("answer", ""), "id": ans.get("message_id", "")}
  206. answer_event += ans.get("answer", "")
  207. message_id = ans.get("message_id", "")
  208. event = smart_message_stream
  209. elif ans.get("event") == message_file:
  210. data = {"url": ans.get("url", ""), "id": ans.get("id", ""),
  211. "type": ans.get("type", "")}
  212. files.append(data)
  213. event = smart_message_file
  214. elif ans.get("event") in [workflow_started, node_started, node_finished]:
  215. data = ans.get("data", {})
  216. data["inputs"] = await data_process(data.get("inputs", {}))
  217. data["outputs"] = await data_process(data.get("outputs", {}))
  218. data["files"] = await data_process(data.get("files", []))
  219. data["process_data"] = ""
  220. if data.get("status") == "failed":
  221. status = http_500
  222. error = data.get("error", "")
  223. node_list.append(ans)
  224. event = [smart_workflow_started, smart_node_started, smart_node_finished][
  225. [workflow_started, node_started, node_finished].index(ans.get("event"))]
  226. elif ans.get("event") == workflow_finished:
  227. data = ans.get("data", {})
  228. answer_workflow = data.get("outputs", {}).get("output", data.get("outputs", {}).get("answer"))
  229. download_url = data.get("outputs", {}).get("download_url")
  230. event = smart_workflow_finished
  231. if data.get("status") == "failed":
  232. status = http_500
  233. error = data.get("error", "")
  234. node_list.append(ans)
  235. elif ans.get("event") == message_end:
  236. event = smart_message_end
  237. else:
  238. continue
  239. yield "data: " + json.dumps(
  240. {"event": event, "data": data, "error": error, "status": status, "task_id": task_id,
  241. "session_id": session_id},
  242. ensure_ascii=False) + "\n\n"
  243. except Exception as e:
  244. logger.error(e)
  245. try:
  246. yield "data: " + json.dumps({"message": smart_message_error,
  247. "error": "\n**ERROR**: " + str(e), "status": http_500},
  248. ensure_ascii=False) + "\n\n"
  249. except:
  250. ...
  251. finally:
  252. await update_session_log(db, session_id, {"role": "assistant",
  253. "answer": answer_event or answer_agent or answer_workflow or error,
  254. "download_url": download_url,
  255. "node_list": node_list, "task_id": task_id, "id": message_id,
  256. "error": error}, conversation_id)
  257. async def service_chat_basic(db, chat_id: str, chat_data: ChatData, session_id: str, user_id, mode: str):
  258. if chat_id == basic_report_talk:
  259. complex_chat = await ComplexChatDao(db).get_complex_chat_by_mode(chat_data.report_mode)
  260. if complex_chat:
  261. ...
  262. async def service_chat_parameters(db, chat_id, user_id):
  263. chat_info = db.query(DialogModel).filter_by(id=chat_id).first()
  264. if not chat_info:
  265. return {}
  266. return chat_info.parameters
  267. async def service_chat_sessions(db, chat_id, name):
  268. token = await get_chat_token(db, rg_api_token)
  269. # print(token)
  270. if not token:
  271. return {}
  272. url = settings.fwr_base_url + RG_CHAT_SESSIONS.format(chat_id)
  273. chat = ChatDialog()
  274. return await chat.chat_sessions(url, {"name": name}, await chat.get_headers(token))
  275. async def service_chat_sessions_list(db, chat_id, current, page_size, user_id, keyword):
  276. total, session_list = await ChatSessionDao(db).get_session_list(
  277. user_id=user_id,
  278. agent_id=chat_id,
  279. keyword=keyword,
  280. page=current,
  281. page_size=page_size
  282. )
  283. return json.dumps({"total": total, "rows": [session.to_dict() for session in session_list]})
  284. async def service_chat_session_log(db, session_id):
  285. session_log = await ChatSessionDao(db).get_session_by_id(session_id)
  286. if not session_log:
  287. return {}
  288. log_info =session_log.log_to_json()
  289. if session_log.event_type == complex_chat:
  290. total, message_list = await ComplexChatSessionDao(db).get_session_list(session_id)
  291. log_info["message"] = [message.log_to_json() for message in message_list[::-1]]
  292. return json.dumps(log_info)
  293. async def service_chat_upload(db, chat_id, file, user_id):
  294. files = []
  295. token = await get_chat_token(db, chat_id)
  296. if not token:
  297. return files
  298. url = settings.dify_base_url + DF_UPLOAD_FILE
  299. chat = ChatBaseApply()
  300. for f in file:
  301. try:
  302. file_content = await f.read()
  303. file_upload = await chat.chat_upload(url, {"file": (f.filename, file_content)}, {"user": str(user_id)},
  304. {'Authorization': f'Bearer {token}'})
  305. try:
  306. tokens = await read_file(file_content, f.filename, f.content_type)
  307. file_upload["tokens"] = tokens
  308. except:
  309. ...
  310. files.append(file_upload)
  311. except Exception as e:
  312. logger.error(e)
  313. return json.dumps(files) if files else ""
  314. async def get_str_token(input_str):
  315. # 获取tokenizer对象,目前只支持通义千问系列模型
  316. tokenizer = get_tokenizer('qwen-turbo')
  317. # 将字符串切分成token并转换为token id
  318. tokens = tokenizer.encode(input_str)
  319. return len(tokens)
  320. async def read_pdf(pdf_stream):
  321. text = ""
  322. with fitz.open(stream=pdf_stream, filetype="pdf") as pdf_document:
  323. for page in pdf_document:
  324. text += page.get_text()
  325. return text
  326. async def read_word(word_stream):
  327. # 使用 python-docx 打开 Word 文件流
  328. doc = Document(io.BytesIO(word_stream))
  329. # 提取每个段落的文本
  330. text = ""
  331. for para in doc.paragraphs:
  332. text += para.text
  333. return text
  334. async def read_file(file, filename, content_type):
  335. text = ""
  336. if content_type == "application/pdf" or filename.endswith('.pdf'):
  337. # 提取 PDF 内容
  338. text = await read_pdf(file)
  339. elif content_type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document" or filename.endswith(
  340. '.docx'):
  341. text = await read_word(file)
  342. return await get_str_token(text)
  343. async def service_chunk_retrieval(query, knowledge_id, top_k, similarity_threshold, api_key):
  344. # print(query)
  345. try:
  346. request_data = json.loads(query)
  347. payload = {
  348. "question": request_data.get("query", ""),
  349. "dataset_ids": request_data.get("dataset_ids", []),
  350. "page_size": top_k,
  351. "similarity_threshold": similarity_threshold if similarity_threshold else 0.2
  352. }
  353. except json.JSONDecodeError as e:
  354. fixed_json = query.replace("'", '"')
  355. try:
  356. request_data = json.loads(fixed_json)
  357. payload = {
  358. "question": request_data.get("query", ""),
  359. "dataset_ids": request_data.get("dataset_ids", []),
  360. "page_size": top_k,
  361. "similarity_threshold": similarity_threshold if similarity_threshold else 0.2
  362. }
  363. except Exception:
  364. payload = {
  365. "question": query,
  366. "dataset_ids": [knowledge_id],
  367. "page_size": top_k,
  368. "similarity_threshold": similarity_threshold if similarity_threshold else 0.2
  369. }
  370. # print(payload)
  371. url = settings.fwr_base_url + RG_ORIGINAL_URL
  372. chat = ChatBaseApply()
  373. response = await chat.chat_post(url, payload, await chat.get_headers(api_key))
  374. if not response:
  375. raise HTTPException(status_code=500, detail="服务异常!")
  376. records = [
  377. {
  378. "content": chunk["content"],
  379. "score": chunk["similarity"],
  380. "title": chunk.get("document_keyword", "Unknown Document"),
  381. "metadata": {"document_id": chunk["document_id"],
  382. "path": f"{settings.fwr_base_url}/document/{chunk['document_id']}?ext={chunk.get('document_keyword').split('.')[-1]}&prefix=document",
  383. 'highlight': chunk.get("highlight"), "image_id": chunk.get("image_id"),
  384. "positions": chunk.get("positions"), }
  385. }
  386. for chunk in response.get("data", {}).get("chunks", [])
  387. ]
  388. # print(len(records))
  389. # print(records)
  390. return records
  391. async def service_base_chunk_retrieval(query, knowledge_id, top_k, similarity_threshold, api_key):
  392. # request_data = json.loads(query)
  393. payload = {
  394. "question": query,
  395. "dataset_ids": [knowledge_id],
  396. "page_size": top_k,
  397. "similarity_threshold": similarity_threshold
  398. }
  399. url = settings.fwr_base_url + RG_ORIGINAL_URL
  400. # url = "http://192.168.20.116:11080/" + RG_ORIGINAL_URL
  401. chat = ChatBaseApply()
  402. response = await chat.chat_post(url, payload, await chat.get_headers(api_key))
  403. if not response:
  404. raise HTTPException(status_code=500, detail="服务异常!")
  405. records = [
  406. {
  407. "content": chunk["content"],
  408. "score": chunk["similarity"],
  409. "title": chunk.get("document_keyword", "Unknown Document"),
  410. "metadata": {"document_id": chunk["document_id"]}
  411. }
  412. for chunk in response.get("data", {}).get("chunks", [])
  413. ]
  414. return records
  415. async def add_complex_log(db, message_id, chat_id, session_id, chat_mode, query, user_id, mode, agent_type, message_type, conversation_id="", node_data=None, query_data=None):
  416. if not node_data:
  417. node_data = []
  418. if not query_data:
  419. query_data = {}
  420. # print(node_data)
  421. # print("--------------------------------------------------------")
  422. # print(query_data)
  423. try:
  424. complex_log = ComplexChatSessionDao(db)
  425. if not conversation_id:
  426. session = await complex_log.get_session_by_session_id(session_id, chat_id)
  427. if session:
  428. conversation_id = session.conversation_id
  429. await complex_log.create_session(message_id,
  430. chat_id=chat_id,
  431. session_id=session_id,
  432. chat_mode=chat_mode,
  433. message_type=message_type,
  434. content=query,
  435. event_type=mode,
  436. tenant_id=user_id,
  437. conversation_id=conversation_id,
  438. node_data=json.dumps(node_data),
  439. query=json.dumps(query_data),
  440. agent_type=agent_type)
  441. return conversation_id, True
  442. except Exception as e:
  443. logger.error(e)
  444. return conversation_id, False
  445. async def add_query_files(db, message_id):
  446. query = {}
  447. complex_log = await ComplexChatSessionDao(db).get_session_by_id(message_id)
  448. if complex_log:
  449. query = json.loads(complex_log.query)
  450. return query.get("files", [])
  451. async def service_complex_chat(db, chat_id, mode, user_id, chat_request: ChatDataRequest):
  452. answer_event = ""
  453. answer_agent = ""
  454. answer_dialog = ""
  455. answer_workflow = ""
  456. download_url = ""
  457. message_id = ""
  458. task_id = ""
  459. error = ""
  460. node_list = []
  461. reference= {}
  462. conversation_id = ""
  463. query_data = chat_request.to_dict()
  464. new_message_id = str(uuid.uuid4())
  465. inputs = {"is_deep": chat_request.isDeep}
  466. files = chat_request.files
  467. if chat_request.chatMode == complex_content_optimization_chat:
  468. inputs["type"] = chat_request.optimizeType
  469. elif chat_request.chatMode == complex_dialog_chat:
  470. if not files and chat_request.parentId:
  471. files = await add_query_files(db, chat_request.parentId)
  472. if chat_request.chatMode != complex_content_optimization_chat:
  473. await add_session_log(db, chat_request.sessionId, chat_request.query if chat_request.query else "未命名会话", chat_id, user_id,
  474. mode, "", DF_TYPE)
  475. conversation_id, message = await add_complex_log(db, new_message_id, chat_id, chat_request.sessionId, chat_request.chatMode, chat_request.query, user_id, mode, DF_TYPE, 1, query_data=query_data)
  476. if not message:
  477. yield "data: " + json.dumps({"message": smart_message_error,
  478. "error": "\n**ERROR**: 创建会话失败!", "status": http_500},
  479. ensure_ascii=False) + "\n\n"
  480. return
  481. query_data["parentId"] = new_message_id
  482. try:
  483. if chat_request.chatMode == complex_knowledge_chat:
  484. if not conversation_id:
  485. session = await service_chat_sessions(db, chat_id, chat_request.query)
  486. # print(session)
  487. if not session or session.get("code") != 0:
  488. yield "data: " + json.dumps(
  489. {"message": smart_message_error, "error": "\n**ERROR**: chat agent error", "status": http_500})
  490. return
  491. conversation_id = session.get("data", {}).get("id")
  492. token = await get_chat_token(db, rg_api_token)
  493. url = settings.fwr_base_url + RG_CHAT_DIALOG.format(chat_id)
  494. chat = ChatDialog()
  495. try:
  496. async for ans in chat.chat_completions(url, await chat.complex_request_data(chat_request.query, chat_request.knowledgeId, conversation_id),
  497. await chat.get_headers(token)):
  498. data = {}
  499. error = ""
  500. status = http_200
  501. if ans.get("code", None) == 102:
  502. error = ans.get("message", "error!")
  503. status = http_400
  504. event = smart_message_error
  505. else:
  506. if isinstance(ans.get("data"), bool) and ans.get("data") is True:
  507. event = smart_message_end
  508. else:
  509. data = ans.get("data", {})
  510. # conversation_id = data.get("session_id", "")
  511. if "session_id" in data:
  512. del data["session_id"]
  513. data["prompt"] = ""
  514. if not message_id:
  515. message_id = data.get("id", "")
  516. answer_dialog = data.get("answer", "")
  517. reference = data.get("reference", {})
  518. event = smart_message_cover
  519. message_str = "data: " + json.dumps(
  520. {"event": event, "data": data, "error": error, "status": status, "message_id":message_id,
  521. "parent_id": new_message_id,
  522. "session_id": chat_request.sessionId},
  523. ensure_ascii=False) + "\n\n"
  524. for i in range(0, len(message_str), max_chunk_size):
  525. chunk = message_str[i:i + max_chunk_size]
  526. # print(chunk)
  527. yield chunk # 发送分块消息
  528. except Exception as e:
  529. logger.error(e)
  530. try:
  531. yield "data: " + json.dumps({"message": smart_message_error,
  532. "error": "\n**ERROR**: " + str(e), "status": http_500},
  533. ensure_ascii=False) + "\n\n"
  534. except:
  535. ...
  536. else:
  537. token = await get_chat_token(db, chat_id)
  538. chat, url = await get_chat_object(mode)
  539. async for ans in chat.chat_completions(url,
  540. await chat.complex_request_data(chat_request.query, conversation_id, str(user_id), files=files, inputs=inputs),
  541. await chat.get_headers(token)):
  542. # print(ans)
  543. data = {}
  544. status = http_200
  545. conversation_id = ans.get("conversation_id")
  546. task_id = ans.get("task_id")
  547. if ans.get("event") == message_error:
  548. error = ans.get("message", "参数异常!")
  549. status = http_400
  550. event = smart_message_error
  551. elif ans.get("event") == message_agent:
  552. data = {"answer": ans.get("answer", ""), "id": ans.get("message_id", "")}
  553. answer_agent += ans.get("answer", "")
  554. message_id = ans.get("message_id", "")
  555. event = smart_message_stream
  556. elif ans.get("event") == message_event:
  557. data = {"answer": ans.get("answer", ""), "id": ans.get("message_id", "")}
  558. answer_event += ans.get("answer", "")
  559. message_id = ans.get("message_id", "")
  560. event = smart_message_stream
  561. elif ans.get("event") == message_file:
  562. data = {"url": ans.get("url", ""), "id": ans.get("id", ""),
  563. "type": ans.get("type", "")}
  564. files.append(data)
  565. event = smart_message_file
  566. elif ans.get("event") in [workflow_started, node_started, node_finished]:
  567. data = ans.get("data", {})
  568. data["inputs"] = await data_process(data.get("inputs", {}))
  569. data["outputs"] = await data_process(data.get("outputs", {}))
  570. data["files"] = await data_process(data.get("files", []))
  571. data["process_data"] = ""
  572. if data.get("status") == "failed":
  573. status = http_500
  574. error = data.get("error", "")
  575. node_list.append(ans)
  576. event = [smart_workflow_started, smart_node_started, smart_node_finished][
  577. [workflow_started, node_started, node_finished].index(ans.get("event"))]
  578. elif ans.get("event") == workflow_finished:
  579. data = ans.get("data", {})
  580. answer_workflow = data.get("outputs", {}).get("output", data.get("outputs", {}).get("answer"))
  581. download_url = data.get("outputs", {}).get("download_url")
  582. event = smart_workflow_finished
  583. if data.get("status") == "failed":
  584. status = http_500
  585. error = data.get("error", "")
  586. node_list.append(ans)
  587. elif ans.get("event") == message_end:
  588. event = smart_message_end
  589. else:
  590. continue
  591. yield "data: " + json.dumps(
  592. {"event": event, "data": data, "error": error, "status": status, "task_id": task_id, "message_id":message_id,
  593. "parent_id": new_message_id,
  594. "session_id": chat_request.sessionId},
  595. ensure_ascii=False) + "\n\n"
  596. except Exception as e:
  597. logger.error(e)
  598. try:
  599. yield "data: " + json.dumps({"message": smart_message_error,
  600. "error": "\n**ERROR**: " + str(e), "status": http_500},
  601. ensure_ascii=False) + "\n\n"
  602. except:
  603. ...
  604. finally:
  605. # await update_session_log(db, session_id, {"role": "assistant",
  606. # "answer": answer_event or answer_agent or answer_workflow or error,
  607. # "download_url": download_url,
  608. # "node_list": node_list, "task_id": task_id, "id": message_id,
  609. # "error": error}, conversation_id)
  610. if message_id:
  611. await add_complex_log(db, message_id, chat_id, chat_request.sessionId, chat_request.chatMode, answer_event or answer_agent or answer_workflow or answer_dialog or error, user_id, mode, DF_TYPE, 2, conversation_id, node_data=node_list or reference, query_data=query_data)
  612. async def service_complex_upload(db, chat_id, file, user_id):
  613. files = []
  614. token = await get_chat_token(db, chat_id)
  615. if not token:
  616. return files
  617. url = settings.dify_base_url + DF_UPLOAD_FILE
  618. chat = ChatBaseApply()
  619. for f in file:
  620. try:
  621. file_content = await f.read()
  622. file_upload = await chat.chat_upload(url, {"file": (f.filename, file_content)}, {"user": str(user_id)},
  623. {'Authorization': f'Bearer {token}'})
  624. # try:
  625. # tokens = await read_file(file_content, f.filename, f.content_type)
  626. # file_upload["tokens"] = tokens
  627. # except:
  628. # ...
  629. files.append(file_upload)
  630. except Exception as e:
  631. logger.error(e)
  632. return json.dumps(files) if files else ""
  633. if __name__ == "__main__":
  634. q = json.dumps({"query": "设备", "dataset_ids": ["fc68db52f43111efb94a0242ac120004"]})
  635. top_k = 2
  636. similarity_threshold = 0.5
  637. api_key = "ragflow-Y4MGYwY2JlZjM2YjExZWY4ZWU5MDI0Mm"
  638. # a = service_chunk_retrieval(q, top_k, similarity_threshold, api_key)
  639. # print(a)
  640. async def a():
  641. b = await service_chunk_retrieval(q, top_k, similarity_threshold, api_key)
  642. print(b)
  643. asyncio.run(a())