You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dialog_service.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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, top=1024, aggs=False)
  105. knowledges = [ck["content_with_weight"] for ck in kbinfos["chunks"]]
  106. chat_logger.info(
  107. "{}->{}".format(" ".join(questions), "\n->".join(knowledges)))
  108. if not knowledges and prompt_config.get("empty_response"):
  109. if stream:
  110. yield {"answer": prompt_config["empty_response"], "reference": kbinfos}
  111. return {"answer": prompt_config["empty_response"], "reference": kbinfos}
  112. kwargs["knowledge"] = "\n".join(knowledges)
  113. gen_conf = dialog.llm_setting
  114. msg = [{"role": m["role"], "content": m["content"]}
  115. for m in messages if m["role"] != "system"]
  116. used_token_count, msg = message_fit_in(msg, int(max_tokens * 0.97))
  117. if "max_tokens" in gen_conf:
  118. gen_conf["max_tokens"] = min(
  119. gen_conf["max_tokens"],
  120. max_tokens - used_token_count)
  121. def decorate_answer(answer):
  122. nonlocal prompt_config, knowledges, kwargs, kbinfos
  123. if knowledges and (prompt_config.get("quote", True) and kwargs.get("quote", True)):
  124. answer, idx = retrievaler.insert_citations(answer,
  125. [ck["content_ltks"]
  126. for ck in kbinfos["chunks"]],
  127. [ck["vector"]
  128. for ck in kbinfos["chunks"]],
  129. embd_mdl,
  130. tkweight=1 - dialog.vector_similarity_weight,
  131. vtweight=dialog.vector_similarity_weight)
  132. idx = set([kbinfos["chunks"][int(i)]["doc_id"] for i in idx])
  133. recall_docs = [
  134. d for d in kbinfos["doc_aggs"] if d["doc_id"] in idx]
  135. if not recall_docs: recall_docs = kbinfos["doc_aggs"]
  136. kbinfos["doc_aggs"] = recall_docs
  137. refs = deepcopy(kbinfos)
  138. for c in refs["chunks"]:
  139. if c.get("vector"):
  140. del c["vector"]
  141. if answer.lower().find("invalid key") >= 0 or answer.lower().find("invalid api")>=0:
  142. answer += " Please set LLM API-Key in 'User Setting -> Model Providers -> API-Key'"
  143. return {"answer": answer, "reference": refs}
  144. if stream:
  145. answer = ""
  146. for ans in chat_mdl.chat_streamly(prompt_config["system"].format(**kwargs), msg, gen_conf):
  147. answer = ans
  148. yield {"answer": answer, "reference": {}}
  149. yield decorate_answer(answer)
  150. else:
  151. answer = chat_mdl.chat(
  152. prompt_config["system"].format(
  153. **kwargs), msg, gen_conf)
  154. chat_logger.info("User: {}|Assistant: {}".format(
  155. msg[-1]["content"], answer))
  156. return decorate_answer(answer)
  157. def use_sql(question, field_map, tenant_id, chat_mdl, quota=True):
  158. sys_prompt = "你是一个DBA。你需要这对以下表的字段结构,根据用户的问题列表,写出最后一个问题对应的SQL。"
  159. user_promt = """
  160. 表名:{};
  161. 数据库表字段说明如下:
  162. {}
  163. 问题如下:
  164. {}
  165. 请写出SQL, 且只要SQL,不要有其他说明及文字。
  166. """.format(
  167. index_name(tenant_id),
  168. "\n".join([f"{k}: {v}" for k, v in field_map.items()]),
  169. question
  170. )
  171. tried_times = 0
  172. def get_table():
  173. nonlocal sys_prompt, user_promt, question, tried_times
  174. sql = chat_mdl.chat(sys_prompt, [{"role": "user", "content": user_promt}], {
  175. "temperature": 0.06})
  176. print(user_promt, sql)
  177. chat_logger.info(f"“{question}”==>{user_promt} get SQL: {sql}")
  178. sql = re.sub(r"[\r\n]+", " ", sql.lower())
  179. sql = re.sub(r".*select ", "select ", sql.lower())
  180. sql = re.sub(r" +", " ", sql)
  181. sql = re.sub(r"([;;]|```).*", "", sql)
  182. if sql[:len("select ")] != "select ":
  183. return None, None
  184. if not re.search(r"((sum|avg|max|min)\(|group by )", sql.lower()):
  185. if sql[:len("select *")] != "select *":
  186. sql = "select doc_id,docnm_kwd," + sql[6:]
  187. else:
  188. flds = []
  189. for k in field_map.keys():
  190. if k in forbidden_select_fields4resume:
  191. continue
  192. if len(flds) > 11:
  193. break
  194. flds.append(k)
  195. sql = "select doc_id,docnm_kwd," + ",".join(flds) + sql[8:]
  196. print(f"“{question}” get SQL(refined): {sql}")
  197. chat_logger.info(f"“{question}” get SQL(refined): {sql}")
  198. tried_times += 1
  199. return retrievaler.sql_retrieval(sql, format="json"), sql
  200. tbl, sql = get_table()
  201. if tbl is None:
  202. return None
  203. if tbl.get("error") and tried_times <= 2:
  204. user_promt = """
  205. 表名:{};
  206. 数据库表字段说明如下:
  207. {}
  208. 问题如下:
  209. {}
  210. 你上一次给出的错误SQL如下:
  211. {}
  212. 后台报错如下:
  213. {}
  214. 请纠正SQL中的错误再写一遍,且只要SQL,不要有其他说明及文字。
  215. """.format(
  216. index_name(tenant_id),
  217. "\n".join([f"{k}: {v}" for k, v in field_map.items()]),
  218. question, sql, tbl["error"]
  219. )
  220. tbl, sql = get_table()
  221. chat_logger.info("TRY it again: {}".format(sql))
  222. chat_logger.info("GET table: {}".format(tbl))
  223. print(tbl)
  224. if tbl.get("error") or len(tbl["rows"]) == 0:
  225. return None
  226. docid_idx = set([ii for ii, c in enumerate(
  227. tbl["columns"]) if c["name"] == "doc_id"])
  228. docnm_idx = set([ii for ii, c in enumerate(
  229. tbl["columns"]) if c["name"] == "docnm_kwd"])
  230. clmn_idx = [ii for ii in range(
  231. len(tbl["columns"])) if ii not in (docid_idx | docnm_idx)]
  232. # compose markdown table
  233. clmns = "|" + "|".join([re.sub(r"(/.*|([^()]+))", "", field_map.get(tbl["columns"][i]["name"],
  234. tbl["columns"][i]["name"])) for i in clmn_idx]) + ("|Source|" if docid_idx and docid_idx else "|")
  235. line = "|" + "|".join(["------" for _ in range(len(clmn_idx))]) + \
  236. ("|------|" if docid_idx and docid_idx else "")
  237. rows = ["|" +
  238. "|".join([rmSpace(str(r[i])) for i in clmn_idx]).replace("None", " ") +
  239. "|" for r in tbl["rows"]]
  240. if quota:
  241. rows = "\n".join([r + f" ##{ii}$$ |" for ii, r in enumerate(rows)])
  242. else: rows = "\n".join([r + f" ##{ii}$$ |" for ii, r in enumerate(rows)])
  243. rows = re.sub(r"T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+Z)?\|", "|", rows)
  244. if not docid_idx or not docnm_idx:
  245. chat_logger.warning("SQL missing field: " + sql)
  246. return {
  247. "answer": "\n".join([clmns, line, rows]),
  248. "reference": {"chunks": [], "doc_aggs": []}
  249. }
  250. docid_idx = list(docid_idx)[0]
  251. docnm_idx = list(docnm_idx)[0]
  252. doc_aggs = {}
  253. for r in tbl["rows"]:
  254. if r[docid_idx] not in doc_aggs:
  255. doc_aggs[r[docid_idx]] = {"doc_name": r[docnm_idx], "count": 0}
  256. doc_aggs[r[docid_idx]]["count"] += 1
  257. return {
  258. "answer": "\n".join([clmns, line, rows]),
  259. "reference": {"chunks": [{"doc_id": r[docid_idx], "docnm_kwd": r[docnm_idx]} for r in tbl["rows"]],
  260. "doc_aggs": [{"doc_id": did, "doc_name": d["doc_name"], "count": d["count"]} for did, d in doc_aggs.items()]}
  261. }