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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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 binascii
  17. import os
  18. import json
  19. import re
  20. from copy import deepcopy
  21. from api.db import LLMType, ParserType
  22. from api.db.db_models import Dialog, Conversation
  23. from api.db.services.common_service import CommonService
  24. from api.db.services.knowledgebase_service import KnowledgebaseService
  25. from api.db.services.llm_service import LLMService, TenantLLMService, LLMBundle
  26. from api.settings import chat_logger, retrievaler, kg_retrievaler
  27. from rag.app.resume import forbidden_select_fields4resume
  28. from rag.nlp import keyword_extraction
  29. from rag.nlp.search import index_name
  30. from rag.utils import rmSpace, num_tokens_from_string, encoder
  31. from api.utils.file_utils import get_project_base_directory
  32. class DialogService(CommonService):
  33. model = Dialog
  34. class ConversationService(CommonService):
  35. model = Conversation
  36. def message_fit_in(msg, max_length=4000):
  37. def count():
  38. nonlocal msg
  39. tks_cnts = []
  40. for m in msg:
  41. tks_cnts.append(
  42. {"role": m["role"], "count": num_tokens_from_string(m["content"])})
  43. total = 0
  44. for m in tks_cnts:
  45. total += m["count"]
  46. return total
  47. c = count()
  48. if c < max_length:
  49. return c, msg
  50. msg_ = [m for m in msg[:-1] if m["role"] == "system"]
  51. msg_.append(msg[-1])
  52. msg = msg_
  53. c = count()
  54. if c < max_length:
  55. return c, msg
  56. ll = num_tokens_from_string(msg_[0]["content"])
  57. l = num_tokens_from_string(msg_[-1]["content"])
  58. if ll / (ll + l) > 0.8:
  59. m = msg_[0]["content"]
  60. m = encoder.decode(encoder.encode(m)[:max_length - l])
  61. msg[0]["content"] = m
  62. return max_length, msg
  63. m = msg_[1]["content"]
  64. m = encoder.decode(encoder.encode(m)[:max_length - l])
  65. msg[1]["content"] = m
  66. return max_length, msg
  67. def llm_id2llm_type(llm_id):
  68. fnm = os.path.join(get_project_base_directory(), "conf")
  69. llm_factories = json.load(open(os.path.join(fnm, "llm_factories.json"), "r"))
  70. for llm_factory in llm_factories["factory_llm_infos"]:
  71. for llm in llm_factory["llm"]:
  72. if llm_id == llm["llm_name"]:
  73. return llm["model_type"].strip(",")[-1]
  74. def chat(dialog, messages, stream=True, **kwargs):
  75. assert messages[-1]["role"] == "user", "The last content of this conversation is not from user."
  76. llm = LLMService.query(llm_name=dialog.llm_id)
  77. if not llm:
  78. llm = TenantLLMService.query(tenant_id=dialog.tenant_id, llm_name=dialog.llm_id)
  79. if not llm:
  80. raise LookupError("LLM(%s) not found" % dialog.llm_id)
  81. max_tokens = 8192
  82. else:
  83. max_tokens = llm[0].max_tokens
  84. kbs = KnowledgebaseService.get_by_ids(dialog.kb_ids)
  85. embd_nms = list(set([kb.embd_id for kb in kbs]))
  86. if len(embd_nms) != 1:
  87. yield {"answer": "**ERROR**: Knowledge bases use different embedding models.", "reference": []}
  88. return {"answer": "**ERROR**: Knowledge bases use different embedding models.", "reference": []}
  89. is_kg = all([kb.parser_id == ParserType.KG for kb in kbs])
  90. retr = retrievaler if not is_kg else kg_retrievaler
  91. questions = [m["content"] for m in messages if m["role"] == "user"][-3:]
  92. attachments = kwargs["doc_ids"].split(",") if "doc_ids" in kwargs else None
  93. if "doc_ids" in messages[-1]:
  94. attachments = messages[-1]["doc_ids"]
  95. for m in messages[:-1]:
  96. if "doc_ids" in m:
  97. attachments.extend(m["doc_ids"])
  98. embd_mdl = LLMBundle(dialog.tenant_id, LLMType.EMBEDDING, embd_nms[0])
  99. if llm_id2llm_type(dialog.llm_id) == "image2text":
  100. chat_mdl = LLMBundle(dialog.tenant_id, LLMType.IMAGE2TEXT, dialog.llm_id)
  101. else:
  102. chat_mdl = LLMBundle(dialog.tenant_id, LLMType.CHAT, dialog.llm_id)
  103. prompt_config = dialog.prompt_config
  104. field_map = KnowledgebaseService.get_field_map(dialog.kb_ids)
  105. tts_mdl = None
  106. if prompt_config.get("tts"):
  107. tts_mdl = LLMBundle(dialog.tenant_id, LLMType.TTS)
  108. # try to use sql if field mapping is good to go
  109. if field_map:
  110. chat_logger.info("Use SQL to retrieval:{}".format(questions[-1]))
  111. ans = use_sql(questions[-1], field_map, dialog.tenant_id, chat_mdl, prompt_config.get("quote", True))
  112. if ans:
  113. yield ans
  114. return
  115. for p in prompt_config["parameters"]:
  116. if p["key"] == "knowledge":
  117. continue
  118. if p["key"] not in kwargs and not p["optional"]:
  119. raise KeyError("Miss parameter: " + p["key"])
  120. if p["key"] not in kwargs:
  121. prompt_config["system"] = prompt_config["system"].replace(
  122. "{%s}" % p["key"], " ")
  123. rerank_mdl = None
  124. if dialog.rerank_id:
  125. rerank_mdl = LLMBundle(dialog.tenant_id, LLMType.RERANK, dialog.rerank_id)
  126. for _ in range(len(questions) // 2):
  127. questions.append(questions[-1])
  128. if "knowledge" not in [p["key"] for p in prompt_config["parameters"]]:
  129. kbinfos = {"total": 0, "chunks": [], "doc_aggs": []}
  130. else:
  131. if prompt_config.get("keyword", False):
  132. questions[-1] += keyword_extraction(chat_mdl, questions[-1])
  133. kbinfos = retr.retrieval(" ".join(questions), embd_mdl, dialog.tenant_id, dialog.kb_ids, 1, dialog.top_n,
  134. dialog.similarity_threshold,
  135. dialog.vector_similarity_weight,
  136. doc_ids=attachments,
  137. top=dialog.top_k, aggs=False, rerank_mdl=rerank_mdl)
  138. knowledges = [ck["content_with_weight"] for ck in kbinfos["chunks"]]
  139. #self-rag
  140. if dialog.prompt_config.get("self_rag") and not relevant(dialog.tenant_id, dialog.llm_id, questions[-1], knowledges):
  141. questions[-1] = rewrite(dialog.tenant_id, dialog.llm_id, questions[-1])
  142. kbinfos = retr.retrieval(" ".join(questions), embd_mdl, dialog.tenant_id, dialog.kb_ids, 1, dialog.top_n,
  143. dialog.similarity_threshold,
  144. dialog.vector_similarity_weight,
  145. doc_ids=attachments,
  146. top=dialog.top_k, aggs=False, rerank_mdl=rerank_mdl)
  147. knowledges = [ck["content_with_weight"] for ck in kbinfos["chunks"]]
  148. chat_logger.info(
  149. "{}->{}".format(" ".join(questions), "\n->".join(knowledges)))
  150. if not knowledges and prompt_config.get("empty_response"):
  151. empty_res = prompt_config["empty_response"]
  152. yield {"answer": empty_res, "reference": kbinfos, "audio_binary": tts(tts_mdl, empty_res)}
  153. return {"answer": prompt_config["empty_response"], "reference": kbinfos}
  154. kwargs["knowledge"] = "\n".join(knowledges)
  155. gen_conf = dialog.llm_setting
  156. msg = [{"role": "system", "content": prompt_config["system"].format(**kwargs)}]
  157. msg.extend([{"role": m["role"], "content": re.sub(r"##\d+\$\$", "", m["content"])}
  158. for m in messages if m["role"] != "system"])
  159. used_token_count, msg = message_fit_in(msg, int(max_tokens * 0.97))
  160. assert len(msg) >= 2, f"message_fit_in has bug: {msg}"
  161. prompt = msg[0]["content"]
  162. if "max_tokens" in gen_conf:
  163. gen_conf["max_tokens"] = min(
  164. gen_conf["max_tokens"],
  165. max_tokens - used_token_count)
  166. def decorate_answer(answer):
  167. nonlocal prompt_config, knowledges, kwargs, kbinfos, prompt
  168. refs = []
  169. if knowledges and (prompt_config.get("quote", True) and kwargs.get("quote", True)):
  170. answer, idx = retr.insert_citations(answer,
  171. [ck["content_ltks"]
  172. for ck in kbinfos["chunks"]],
  173. [ck["vector"]
  174. for ck in kbinfos["chunks"]],
  175. embd_mdl,
  176. tkweight=1 - dialog.vector_similarity_weight,
  177. vtweight=dialog.vector_similarity_weight)
  178. idx = set([kbinfos["chunks"][int(i)]["doc_id"] for i in idx])
  179. recall_docs = [
  180. d for d in kbinfos["doc_aggs"] if d["doc_id"] in idx]
  181. if not recall_docs: recall_docs = kbinfos["doc_aggs"]
  182. kbinfos["doc_aggs"] = recall_docs
  183. refs = deepcopy(kbinfos)
  184. for c in refs["chunks"]:
  185. if c.get("vector"):
  186. del c["vector"]
  187. if answer.lower().find("invalid key") >= 0 or answer.lower().find("invalid api") >= 0:
  188. answer += " Please set LLM API-Key in 'User Setting -> Model Providers -> API-Key'"
  189. return {"answer": answer, "reference": refs, "prompt": prompt}
  190. if stream:
  191. last_ans = ""
  192. answer = ""
  193. for ans in chat_mdl.chat_streamly(prompt, msg[1:], gen_conf):
  194. answer = ans
  195. delta_ans = ans[len(last_ans):]
  196. if num_tokens_from_string(delta_ans) < 12:
  197. continue
  198. last_ans = answer
  199. yield {"answer": answer, "reference": {}, "audio_binary": tts(tts_mdl, delta_ans)}
  200. delta_ans = answer[len(last_ans):]
  201. if delta_ans:
  202. yield {"answer": answer, "reference": {}, "audio_binary": tts(tts_mdl, delta_ans)}
  203. yield decorate_answer(answer)
  204. else:
  205. answer = chat_mdl.chat(prompt, msg[1:], gen_conf)
  206. chat_logger.info("User: {}|Assistant: {}".format(
  207. msg[-1]["content"], answer))
  208. res = decorate_answer(answer)
  209. res["audio_binary"] = tts(tts_mdl, answer)
  210. yield res
  211. def use_sql(question, field_map, tenant_id, chat_mdl, quota=True):
  212. sys_prompt = "你是一个DBA。你需要这对以下表的字段结构,根据用户的问题列表,写出最后一个问题对应的SQL。"
  213. user_promt = """
  214. 表名:{};
  215. 数据库表字段说明如下:
  216. {}
  217. 问题如下:
  218. {}
  219. 请写出SQL, 且只要SQL,不要有其他说明及文字。
  220. """.format(
  221. index_name(tenant_id),
  222. "\n".join([f"{k}: {v}" for k, v in field_map.items()]),
  223. question
  224. )
  225. tried_times = 0
  226. def get_table():
  227. nonlocal sys_prompt, user_promt, question, tried_times
  228. sql = chat_mdl.chat(sys_prompt, [{"role": "user", "content": user_promt}], {
  229. "temperature": 0.06})
  230. print(user_promt, sql)
  231. chat_logger.info(f"“{question}”==>{user_promt} get SQL: {sql}")
  232. sql = re.sub(r"[\r\n]+", " ", sql.lower())
  233. sql = re.sub(r".*select ", "select ", sql.lower())
  234. sql = re.sub(r" +", " ", sql)
  235. sql = re.sub(r"([;;]|```).*", "", sql)
  236. if sql[:len("select ")] != "select ":
  237. return None, None
  238. if not re.search(r"((sum|avg|max|min)\(|group by )", sql.lower()):
  239. if sql[:len("select *")] != "select *":
  240. sql = "select doc_id,docnm_kwd," + sql[6:]
  241. else:
  242. flds = []
  243. for k in field_map.keys():
  244. if k in forbidden_select_fields4resume:
  245. continue
  246. if len(flds) > 11:
  247. break
  248. flds.append(k)
  249. sql = "select doc_id,docnm_kwd," + ",".join(flds) + sql[8:]
  250. print(f"“{question}” get SQL(refined): {sql}")
  251. chat_logger.info(f"“{question}” get SQL(refined): {sql}")
  252. tried_times += 1
  253. return retrievaler.sql_retrieval(sql, format="json"), sql
  254. tbl, sql = get_table()
  255. if tbl is None:
  256. return None
  257. if tbl.get("error") and tried_times <= 2:
  258. user_promt = """
  259. 表名:{};
  260. 数据库表字段说明如下:
  261. {}
  262. 问题如下:
  263. {}
  264. 你上一次给出的错误SQL如下:
  265. {}
  266. 后台报错如下:
  267. {}
  268. 请纠正SQL中的错误再写一遍,且只要SQL,不要有其他说明及文字。
  269. """.format(
  270. index_name(tenant_id),
  271. "\n".join([f"{k}: {v}" for k, v in field_map.items()]),
  272. question, sql, tbl["error"]
  273. )
  274. tbl, sql = get_table()
  275. chat_logger.info("TRY it again: {}".format(sql))
  276. chat_logger.info("GET table: {}".format(tbl))
  277. print(tbl)
  278. if tbl.get("error") or len(tbl["rows"]) == 0:
  279. return None
  280. docid_idx = set([ii for ii, c in enumerate(
  281. tbl["columns"]) if c["name"] == "doc_id"])
  282. docnm_idx = set([ii for ii, c in enumerate(
  283. tbl["columns"]) if c["name"] == "docnm_kwd"])
  284. clmn_idx = [ii for ii in range(
  285. len(tbl["columns"])) if ii not in (docid_idx | docnm_idx)]
  286. # compose markdown table
  287. clmns = "|" + "|".join([re.sub(r"(/.*|([^()]+))", "", field_map.get(tbl["columns"][i]["name"],
  288. tbl["columns"][i]["name"])) for i in
  289. clmn_idx]) + ("|Source|" if docid_idx and docid_idx else "|")
  290. line = "|" + "|".join(["------" for _ in range(len(clmn_idx))]) + \
  291. ("|------|" if docid_idx and docid_idx else "")
  292. rows = ["|" +
  293. "|".join([rmSpace(str(r[i])) for i in clmn_idx]).replace("None", " ") +
  294. "|" for r in tbl["rows"]]
  295. if quota:
  296. rows = "\n".join([r + f" ##{ii}$$ |" for ii, r in enumerate(rows)])
  297. else:
  298. rows = "\n".join([r + f" ##{ii}$$ |" for ii, r in enumerate(rows)])
  299. rows = re.sub(r"T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+Z)?\|", "|", rows)
  300. if not docid_idx or not docnm_idx:
  301. chat_logger.warning("SQL missing field: " + sql)
  302. return {
  303. "answer": "\n".join([clmns, line, rows]),
  304. "reference": {"chunks": [], "doc_aggs": []},
  305. "prompt": sys_prompt
  306. }
  307. docid_idx = list(docid_idx)[0]
  308. docnm_idx = list(docnm_idx)[0]
  309. doc_aggs = {}
  310. for r in tbl["rows"]:
  311. if r[docid_idx] not in doc_aggs:
  312. doc_aggs[r[docid_idx]] = {"doc_name": r[docnm_idx], "count": 0}
  313. doc_aggs[r[docid_idx]]["count"] += 1
  314. return {
  315. "answer": "\n".join([clmns, line, rows]),
  316. "reference": {"chunks": [{"doc_id": r[docid_idx], "docnm_kwd": r[docnm_idx]} for r in tbl["rows"]],
  317. "doc_aggs": [{"doc_id": did, "doc_name": d["doc_name"], "count": d["count"]} for did, d in
  318. doc_aggs.items()]},
  319. "prompt": sys_prompt
  320. }
  321. def relevant(tenant_id, llm_id, question, contents: list):
  322. if llm_id2llm_type(llm_id) == "image2text":
  323. chat_mdl = LLMBundle(tenant_id, LLMType.IMAGE2TEXT, llm_id)
  324. else:
  325. chat_mdl = LLMBundle(tenant_id, LLMType.CHAT, llm_id)
  326. prompt = """
  327. You are a grader assessing relevance of a retrieved document to a user question.
  328. It does not need to be a stringent test. The goal is to filter out erroneous retrievals.
  329. If the document contains keyword(s) or semantic meaning related to the user question, grade it as relevant.
  330. Give a binary score 'yes' or 'no' score to indicate whether the document is relevant to the question.
  331. No other words needed except 'yes' or 'no'.
  332. """
  333. if not contents:return False
  334. contents = "Documents: \n" + " - ".join(contents)
  335. contents = f"Question: {question}\n" + contents
  336. if num_tokens_from_string(contents) >= chat_mdl.max_length - 4:
  337. contents = encoder.decode(encoder.encode(contents)[:chat_mdl.max_length - 4])
  338. ans = chat_mdl.chat(prompt, [{"role": "user", "content": contents}], {"temperature": 0.01})
  339. if ans.lower().find("yes") >= 0: return True
  340. return False
  341. def rewrite(tenant_id, llm_id, question):
  342. if llm_id2llm_type(llm_id) == "image2text":
  343. chat_mdl = LLMBundle(tenant_id, LLMType.IMAGE2TEXT, llm_id)
  344. else:
  345. chat_mdl = LLMBundle(tenant_id, LLMType.CHAT, llm_id)
  346. prompt = """
  347. You are an expert at query expansion to generate a paraphrasing of a question.
  348. I can't retrieval relevant information from the knowledge base by using user's question directly.
  349. You need to expand or paraphrase user's question by multiple ways such as using synonyms words/phrase,
  350. writing the abbreviation in its entirety, adding some extra descriptions or explanations,
  351. changing the way of expression, translating the original question into another language (English/Chinese), etc.
  352. And return 5 versions of question and one is from translation.
  353. Just list the question. No other words are needed.
  354. """
  355. ans = chat_mdl.chat(prompt, [{"role": "user", "content": question}], {"temperature": 0.8})
  356. return ans
  357. def tts(tts_mdl, text):
  358. return
  359. if not tts_mdl or not text: return
  360. bin = b""
  361. for chunk in tts_mdl.tts(text):
  362. bin += chunk
  363. return binascii.hexlify(bin).decode("utf-8")