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 20KB

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