您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

dialog_service.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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 copy import deepcopy
  18. from api.db import LLMType
  19. from api.db.db_models import Dialog, Conversation
  20. from api.db.services.common_service import CommonService
  21. from api.db.services.knowledgebase_service import KnowledgebaseService
  22. from api.db.services.llm_service import LLMService, TenantLLMService, LLMBundle
  23. from api.settings import chat_logger, retrievaler
  24. from rag.app.resume import forbidden_select_fields4resume
  25. from rag.nlp.search import index_name
  26. from rag.utils import rmSpace, num_tokens_from_string, encoder
  27. class DialogService(CommonService):
  28. model = Dialog
  29. class ConversationService(CommonService):
  30. model = Conversation
  31. def message_fit_in(msg, max_length=4000):
  32. def count():
  33. nonlocal msg
  34. tks_cnts = []
  35. for m in msg:
  36. tks_cnts.append(
  37. {"role": m["role"], "count": num_tokens_from_string(m["content"])})
  38. total = 0
  39. for m in tks_cnts:
  40. total += m["count"]
  41. return total
  42. c = count()
  43. if c < max_length:
  44. return c, msg
  45. msg_ = [m for m in msg[:-1] if m["role"] == "system"]
  46. msg_.append(msg[-1])
  47. msg = msg_
  48. c = count()
  49. if c < max_length:
  50. return c, msg
  51. ll = num_tokens_from_string(msg_[0].content)
  52. l = num_tokens_from_string(msg_[-1].content)
  53. if ll / (ll + l) > 0.8:
  54. m = msg_[0].content
  55. m = encoder.decode(encoder.encode(m)[:max_length - l])
  56. msg[0].content = m
  57. return max_length, msg
  58. m = msg_[1].content
  59. m = encoder.decode(encoder.encode(m)[:max_length - l])
  60. msg[1].content = m
  61. return max_length, msg
  62. def chat(dialog, messages, stream=True, **kwargs):
  63. assert messages[-1]["role"] == "user", "The last content of this conversation is not from user."
  64. llm = LLMService.query(llm_name=dialog.llm_id)
  65. if not llm:
  66. llm = TenantLLMService.query(tenant_id=dialog.tenant_id, llm_name=dialog.llm_id)
  67. if not llm:
  68. raise LookupError("LLM(%s) not found" % dialog.llm_id)
  69. max_tokens = 1024
  70. else: max_tokens = llm[0].max_tokens
  71. kbs = KnowledgebaseService.get_by_ids(dialog.kb_ids)
  72. embd_nms = list(set([kb.embd_id for kb in kbs]))
  73. if len(embd_nms) != 1:
  74. if stream:
  75. yield {"answer": "**ERROR**: Knowledge bases use different embedding models.", "reference": []}
  76. return {"answer": "**ERROR**: Knowledge bases use different embedding models.", "reference": []}
  77. questions = [m["content"] for m in messages if m["role"] == "user"]
  78. embd_mdl = LLMBundle(dialog.tenant_id, LLMType.EMBEDDING, embd_nms[0])
  79. chat_mdl = LLMBundle(dialog.tenant_id, LLMType.CHAT, dialog.llm_id)
  80. prompt_config = dialog.prompt_config
  81. field_map = KnowledgebaseService.get_field_map(dialog.kb_ids)
  82. # try to use sql if field mapping is good to go
  83. if field_map:
  84. chat_logger.info("Use SQL to retrieval:{}".format(questions[-1]))
  85. ans = use_sql(questions[-1], field_map, dialog.tenant_id, chat_mdl, prompt_config.get("quote", True))
  86. if ans:
  87. yield ans
  88. return
  89. for p in prompt_config["parameters"]:
  90. if p["key"] == "knowledge":
  91. continue
  92. if p["key"] not in kwargs and not p["optional"]:
  93. raise KeyError("Miss parameter: " + p["key"])
  94. if p["key"] not in kwargs:
  95. prompt_config["system"] = prompt_config["system"].replace(
  96. "{%s}" % p["key"], " ")
  97. for _ in range(len(questions) // 2):
  98. questions.append(questions[-1])
  99. if "knowledge" not in [p["key"] for p in prompt_config["parameters"]]:
  100. kbinfos = {"total": 0, "chunks": [], "doc_aggs": []}
  101. else:
  102. kbinfos = retrievaler.retrieval(" ".join(questions), embd_mdl, dialog.tenant_id, dialog.kb_ids, 1, dialog.top_n,
  103. dialog.similarity_threshold,
  104. dialog.vector_similarity_weight,
  105. doc_ids=kwargs.get("doc_ids", "").split(","),
  106. top=1024, aggs=False)
  107. knowledges = [ck["content_with_weight"] for ck in kbinfos["chunks"]]
  108. chat_logger.info(
  109. "{}->{}".format(" ".join(questions), "\n->".join(knowledges)))
  110. if not knowledges and prompt_config.get("empty_response"):
  111. if stream:
  112. yield {"answer": prompt_config["empty_response"], "reference": kbinfos}
  113. return {"answer": prompt_config["empty_response"], "reference": kbinfos}
  114. kwargs["knowledge"] = "\n".join(knowledges)
  115. gen_conf = dialog.llm_setting
  116. msg = [{"role": m["role"], "content": m["content"]}
  117. for m in messages if m["role"] != "system"]
  118. used_token_count, msg = message_fit_in(msg, int(max_tokens * 0.97))
  119. if "max_tokens" in gen_conf:
  120. gen_conf["max_tokens"] = min(
  121. gen_conf["max_tokens"],
  122. max_tokens - used_token_count)
  123. def decorate_answer(answer):
  124. nonlocal prompt_config, knowledges, kwargs, kbinfos
  125. if knowledges and (prompt_config.get("quote", True) and kwargs.get("quote", True)):
  126. answer, idx = retrievaler.insert_citations(answer,
  127. [ck["content_ltks"]
  128. for ck in kbinfos["chunks"]],
  129. [ck["vector"]
  130. for ck in kbinfos["chunks"]],
  131. embd_mdl,
  132. tkweight=1 - dialog.vector_similarity_weight,
  133. vtweight=dialog.vector_similarity_weight)
  134. idx = set([kbinfos["chunks"][int(i)]["doc_id"] for i in idx])
  135. recall_docs = [
  136. d for d in kbinfos["doc_aggs"] if d["doc_id"] in idx]
  137. if not recall_docs: recall_docs = kbinfos["doc_aggs"]
  138. kbinfos["doc_aggs"] = recall_docs
  139. refs = deepcopy(kbinfos)
  140. for c in refs["chunks"]:
  141. if c.get("vector"):
  142. del c["vector"]
  143. if answer.lower().find("invalid key") >= 0 or answer.lower().find("invalid api")>=0:
  144. answer += " Please set LLM API-Key in 'User Setting -> Model Providers -> API-Key'"
  145. return {"answer": answer, "reference": refs}
  146. if stream:
  147. answer = ""
  148. for ans in chat_mdl.chat_streamly(prompt_config["system"].format(**kwargs), msg, gen_conf):
  149. answer = ans
  150. yield {"answer": answer, "reference": {}}
  151. yield decorate_answer(answer)
  152. else:
  153. answer = chat_mdl.chat(
  154. prompt_config["system"].format(
  155. **kwargs), msg, gen_conf)
  156. chat_logger.info("User: {}|Assistant: {}".format(
  157. msg[-1]["content"], answer))
  158. return decorate_answer(answer)
  159. def use_sql(question, field_map, tenant_id, chat_mdl, quota=True):
  160. sys_prompt = "你是一个DBA。你需要这对以下表的字段结构,根据用户的问题列表,写出最后一个问题对应的SQL。"
  161. user_promt = """
  162. 表名:{};
  163. 数据库表字段说明如下:
  164. {}
  165. 问题如下:
  166. {}
  167. 请写出SQL, 且只要SQL,不要有其他说明及文字。
  168. """.format(
  169. index_name(tenant_id),
  170. "\n".join([f"{k}: {v}" for k, v in field_map.items()]),
  171. question
  172. )
  173. tried_times = 0
  174. def get_table():
  175. nonlocal sys_prompt, user_promt, question, tried_times
  176. sql = chat_mdl.chat(sys_prompt, [{"role": "user", "content": user_promt}], {
  177. "temperature": 0.06})
  178. print(user_promt, sql)
  179. chat_logger.info(f"“{question}”==>{user_promt} get SQL: {sql}")
  180. sql = re.sub(r"[\r\n]+", " ", sql.lower())
  181. sql = re.sub(r".*select ", "select ", sql.lower())
  182. sql = re.sub(r" +", " ", sql)
  183. sql = re.sub(r"([;;]|```).*", "", sql)
  184. if sql[:len("select ")] != "select ":
  185. return None, None
  186. if not re.search(r"((sum|avg|max|min)\(|group by )", sql.lower()):
  187. if sql[:len("select *")] != "select *":
  188. sql = "select doc_id,docnm_kwd," + sql[6:]
  189. else:
  190. flds = []
  191. for k in field_map.keys():
  192. if k in forbidden_select_fields4resume:
  193. continue
  194. if len(flds) > 11:
  195. break
  196. flds.append(k)
  197. sql = "select doc_id,docnm_kwd," + ",".join(flds) + sql[8:]
  198. print(f"“{question}” get SQL(refined): {sql}")
  199. chat_logger.info(f"“{question}” get SQL(refined): {sql}")
  200. tried_times += 1
  201. return retrievaler.sql_retrieval(sql, format="json"), sql
  202. tbl, sql = get_table()
  203. if tbl is None:
  204. return None
  205. if tbl.get("error") and tried_times <= 2:
  206. user_promt = """
  207. 表名:{};
  208. 数据库表字段说明如下:
  209. {}
  210. 问题如下:
  211. {}
  212. 你上一次给出的错误SQL如下:
  213. {}
  214. 后台报错如下:
  215. {}
  216. 请纠正SQL中的错误再写一遍,且只要SQL,不要有其他说明及文字。
  217. """.format(
  218. index_name(tenant_id),
  219. "\n".join([f"{k}: {v}" for k, v in field_map.items()]),
  220. question, sql, tbl["error"]
  221. )
  222. tbl, sql = get_table()
  223. chat_logger.info("TRY it again: {}".format(sql))
  224. chat_logger.info("GET table: {}".format(tbl))
  225. print(tbl)
  226. if tbl.get("error") or len(tbl["rows"]) == 0:
  227. return None
  228. docid_idx = set([ii for ii, c in enumerate(
  229. tbl["columns"]) if c["name"] == "doc_id"])
  230. docnm_idx = set([ii for ii, c in enumerate(
  231. tbl["columns"]) if c["name"] == "docnm_kwd"])
  232. clmn_idx = [ii for ii in range(
  233. len(tbl["columns"])) if ii not in (docid_idx | docnm_idx)]
  234. # compose markdown table
  235. clmns = "|" + "|".join([re.sub(r"(/.*|([^()]+))", "", field_map.get(tbl["columns"][i]["name"],
  236. tbl["columns"][i]["name"])) for i in clmn_idx]) + ("|Source|" if docid_idx and docid_idx else "|")
  237. line = "|" + "|".join(["------" for _ in range(len(clmn_idx))]) + \
  238. ("|------|" if docid_idx and docid_idx else "")
  239. rows = ["|" +
  240. "|".join([rmSpace(str(r[i])) for i in clmn_idx]).replace("None", " ") +
  241. "|" for r in tbl["rows"]]
  242. if quota:
  243. rows = "\n".join([r + f" ##{ii}$$ |" for ii, r in enumerate(rows)])
  244. else: rows = "\n".join([r + f" ##{ii}$$ |" for ii, r in enumerate(rows)])
  245. rows = re.sub(r"T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+Z)?\|", "|", rows)
  246. if not docid_idx or not docnm_idx:
  247. chat_logger.warning("SQL missing field: " + sql)
  248. return {
  249. "answer": "\n".join([clmns, line, rows]),
  250. "reference": {"chunks": [], "doc_aggs": []}
  251. }
  252. docid_idx = list(docid_idx)[0]
  253. docnm_idx = list(docnm_idx)[0]
  254. doc_aggs = {}
  255. for r in tbl["rows"]:
  256. if r[docid_idx] not in doc_aggs:
  257. doc_aggs[r[docid_idx]] = {"doc_name": r[docnm_idx], "count": 0}
  258. doc_aggs[r[docid_idx]]["count"] += 1
  259. return {
  260. "answer": "\n".join([clmns, line, rows]),
  261. "reference": {"chunks": [{"doc_id": r[docid_idx], "docnm_kwd": r[docnm_idx]} for r in tbl["rows"]],
  262. "doc_aggs": [{"doc_id": did, "doc_name": d["doc_name"], "count": d["count"]} for did, d in doc_aggs.items()]}
  263. }