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.

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