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

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