Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

conversation_app.py 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import re
  17. from flask import request
  18. from flask_login import login_required
  19. from api.db.services.dialog_service import DialogService, ConversationService
  20. from api.db import LLMType
  21. from api.db.services.knowledgebase_service import KnowledgebaseService
  22. from api.db.services.llm_service import LLMService, LLMBundle
  23. from api.settings import access_logger
  24. from api.utils.api_utils import server_error_response, get_data_error_result, validate_request
  25. from api.utils import get_uuid
  26. from api.utils.api_utils import get_json_result
  27. from rag.llm import ChatModel
  28. from rag.nlp import retrievaler
  29. from rag.nlp.search import index_name
  30. from rag.utils import num_tokens_from_string, encoder
  31. @manager.route('/set', methods=['POST'])
  32. @login_required
  33. @validate_request("dialog_id")
  34. def set():
  35. req = request.json
  36. conv_id = req.get("conversation_id")
  37. if conv_id:
  38. del req["conversation_id"]
  39. try:
  40. if not ConversationService.update_by_id(conv_id, req):
  41. return get_data_error_result(retmsg="Conversation not found!")
  42. e, conv = ConversationService.get_by_id(conv_id)
  43. if not e:
  44. return get_data_error_result(
  45. retmsg="Fail to update a conversation!")
  46. conv = conv.to_dict()
  47. return get_json_result(data=conv)
  48. except Exception as e:
  49. return server_error_response(e)
  50. try:
  51. e, dia = DialogService.get_by_id(req["dialog_id"])
  52. if not e:
  53. return get_data_error_result(retmsg="Dialog not found")
  54. conv = {
  55. "id": get_uuid(),
  56. "dialog_id": req["dialog_id"],
  57. "name": "New conversation",
  58. "message": [{"role": "assistant", "content": dia.prompt_config["prologue"]}]
  59. }
  60. ConversationService.save(**conv)
  61. e, conv = ConversationService.get_by_id(conv["id"])
  62. if not e:
  63. return get_data_error_result(retmsg="Fail to new a conversation!")
  64. conv = conv.to_dict()
  65. return get_json_result(data=conv)
  66. except Exception as e:
  67. return server_error_response(e)
  68. @manager.route('/get', methods=['GET'])
  69. @login_required
  70. def get():
  71. conv_id = request.args["conversation_id"]
  72. try:
  73. e, conv = ConversationService.get_by_id(conv_id)
  74. if not e:
  75. return get_data_error_result(retmsg="Conversation not found!")
  76. conv = conv.to_dict()
  77. return get_json_result(data=conv)
  78. except Exception as e:
  79. return server_error_response(e)
  80. @manager.route('/rm', methods=['POST'])
  81. @login_required
  82. def rm():
  83. conv_ids = request.json["conversation_ids"]
  84. try:
  85. for cid in conv_ids:
  86. ConversationService.delete_by_id(cid)
  87. return get_json_result(data=True)
  88. except Exception as e:
  89. return server_error_response(e)
  90. @manager.route('/list', methods=['GET'])
  91. @login_required
  92. def list():
  93. dialog_id = request.args["dialog_id"]
  94. try:
  95. convs = ConversationService.query(dialog_id=dialog_id)
  96. convs = [d.to_dict() for d in convs]
  97. return get_json_result(data=convs)
  98. except Exception as e:
  99. return server_error_response(e)
  100. def message_fit_in(msg, max_length=4000):
  101. def count():
  102. nonlocal msg
  103. tks_cnts = []
  104. for m in msg:tks_cnts.append({"role": m["role"], "count": num_tokens_from_string(m["content"])})
  105. total = 0
  106. for m in tks_cnts: total += m["count"]
  107. return total
  108. c = count()
  109. if c < max_length: return c, msg
  110. msg = [m for m in msg if m.role in ["system", "user"]]
  111. c = count()
  112. if c < max_length:return c, msg
  113. msg_ = [m for m in msg[:-1] if m.role == "system"]
  114. msg_.append(msg[-1])
  115. msg = msg_
  116. c = count()
  117. if c < max_length:return c, msg
  118. ll = num_tokens_from_string(msg_[0].content)
  119. l = num_tokens_from_string(msg_[-1].content)
  120. if ll/(ll + l) > 0.8:
  121. m = msg_[0].content
  122. m = encoder.decode(encoder.encode(m)[:max_length-l])
  123. msg[0].content = m
  124. return max_length, msg
  125. m = msg_[1].content
  126. m = encoder.decode(encoder.encode(m)[:max_length-l])
  127. msg[1].content = m
  128. return max_length, msg
  129. @manager.route('/completion', methods=['POST'])
  130. @login_required
  131. @validate_request("dialog_id", "messages")
  132. def completion():
  133. req = request.json
  134. msg = []
  135. for m in req["messages"]:
  136. if m["role"] == "system":continue
  137. if m["role"] == "assistant" and not msg:continue
  138. msg.append({"role": m["role"], "content": m["content"]})
  139. try:
  140. e, dia = DialogService.get_by_id(req["dialog_id"])
  141. if not e:
  142. return get_data_error_result(retmsg="Dialog not found!")
  143. del req["dialog_id"]
  144. del req["messages"]
  145. return get_json_result(data=chat(dia, msg, **req))
  146. except Exception as e:
  147. return server_error_response(e)
  148. def chat(dialog, messages, **kwargs):
  149. assert messages[-1]["role"] == "user", "The last content of this conversation is not from user."
  150. llm = LLMService.query(llm_name=dialog.llm_id)
  151. if not llm:
  152. raise LookupError("LLM(%s) not found"%dialog.llm_id)
  153. llm = llm[0]
  154. question = messages[-1]["content"]
  155. embd_mdl = LLMBundle(dialog.tenant_id, LLMType.EMBEDDING)
  156. chat_mdl = LLMBundle(dialog.tenant_id, LLMType.CHAT, dialog.llm_id)
  157. field_map = KnowledgebaseService.get_field_map(dialog.kb_ids)
  158. ## try to use sql if field mapping is good to go
  159. if field_map:
  160. markdown_tbl,chunks = use_sql(question, field_map, dialog.tenant_id, chat_mdl)
  161. if markdown_tbl:
  162. return {"answer": markdown_tbl, "retrieval": {"chunks": chunks}}
  163. prompt_config = dialog.prompt_config
  164. for p in prompt_config["parameters"]:
  165. if p["key"] == "knowledge":continue
  166. if p["key"] not in kwargs and not p["optional"]:raise KeyError("Miss parameter: " + p["key"])
  167. if p["key"] not in kwargs:
  168. prompt_config["system"] = prompt_config["system"].replace("{%s}"%p["key"], " ")
  169. kbinfos = retrievaler.retrieval(question, embd_mdl, dialog.tenant_id, dialog.kb_ids, 1, dialog.top_n, dialog.similarity_threshold,
  170. dialog.vector_similarity_weight, top=1024, aggs=False)
  171. knowledges = [ck["content_with_weight"] for ck in kbinfos["chunks"]]
  172. if not knowledges and prompt_config["empty_response"]:
  173. return {"answer": prompt_config["empty_response"], "retrieval": kbinfos}
  174. kwargs["knowledge"] = "\n".join(knowledges)
  175. gen_conf = dialog.llm_setting[dialog.llm_setting_type]
  176. msg = [{"role": m["role"], "content": m["content"]} for m in messages if m["role"] != "system"]
  177. used_token_count, msg = message_fit_in(msg, int(llm.max_tokens * 0.97))
  178. if "max_tokens" in gen_conf:
  179. gen_conf["max_tokens"] = min(gen_conf["max_tokens"], llm.max_tokens - used_token_count)
  180. answer = chat_mdl.chat(prompt_config["system"].format(**kwargs), msg, gen_conf)
  181. answer = retrievaler.insert_citations(answer,
  182. [ck["content_ltks"] for ck in kbinfos["chunks"]],
  183. [ck["vector"] for ck in kbinfos["chunks"]],
  184. embd_mdl,
  185. tkweight=1-dialog.vector_similarity_weight,
  186. vtweight=dialog.vector_similarity_weight)
  187. for c in kbinfos["chunks"]:
  188. if c.get("vector"):del c["vector"]
  189. return {"answer": answer, "retrieval": kbinfos}
  190. def use_sql(question,field_map, tenant_id, chat_mdl):
  191. sys_prompt = "你是一个DBA。你需要这对以下表的字段结构,根据我的问题写出sql。"
  192. user_promt = """
  193. 表名:{};
  194. 数据库表字段说明如下:
  195. {}
  196. 问题:{}
  197. 请写出SQL。
  198. """.format(
  199. index_name(tenant_id),
  200. "\n".join([f"{k}: {v}" for k,v in field_map.items()]),
  201. question
  202. )
  203. sql = chat_mdl.chat(sys_prompt, [{"role": "user", "content": user_promt}], {"temperature": 0.1})
  204. sql = re.sub(r".*?select ", "select ", sql, flags=re.IGNORECASE)
  205. sql = re.sub(r" +", " ", sql)
  206. sql = re.sub(r"[;;].*", "", sql)
  207. if sql[:len("select ")].lower() != "select ":
  208. return None, None
  209. if sql[:len("select *")].lower() != "select *":
  210. sql = "select doc_id,docnm_kwd," + sql[6:]
  211. tbl = retrievaler.sql_retrieval(sql)
  212. if not tbl: return None, None
  213. docid_idx = set([ii for ii, c in enumerate(tbl["columns"]) if c["name"] == "doc_id"])
  214. docnm_idx = set([ii for ii, c in enumerate(tbl["columns"]) if c["name"] == "docnm_kwd"])
  215. clmn_idx = [ii for ii in range(len(tbl["columns"])) if ii not in (docid_idx|docnm_idx)]
  216. # compose markdown table
  217. clmns = "|".join([re.sub(r"/.*", "", field_map.get(tbl["columns"][i]["name"], f"C{i}")) for i in clmn_idx]) + "|原文"
  218. line = "|".join(["------" for _ in range(len(clmn_idx))]) + "|------"
  219. rows = ["|".join([str(r[i]) for i in clmn_idx])+"|" for r in tbl["rows"]]
  220. if not docid_idx or not docnm_idx:
  221. access_logger.error("SQL missing field: " + sql)
  222. return "\n".join([clmns, line, "\n".join(rows)]), []
  223. rows = "\n".join([r+f"##{ii}$$" for ii,r in enumerate(rows)])
  224. docid_idx = list(docid_idx)[0]
  225. docnm_idx = list(docnm_idx)[0]
  226. return "\n".join([clmns, line, rows]), [{"doc_id": r[docid_idx], "docnm_kwd": r[docnm_idx]} for r in tbl["rows"]]