Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

dialog_service.py 11KB

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