選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

dialog_service.py 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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 logging
  17. import binascii
  18. import os
  19. import json
  20. import re
  21. from copy import deepcopy
  22. from timeit import default_timer as timer
  23. import datetime
  24. from datetime import timedelta
  25. from api.db import LLMType, ParserType,StatusEnum
  26. from api.db.db_models import Dialog, DB
  27. from api.db.services.common_service import CommonService
  28. from api.db.services.knowledgebase_service import KnowledgebaseService
  29. from api.db.services.llm_service import LLMService, TenantLLMService, LLMBundle
  30. from api import settings
  31. from rag.app.resume import forbidden_select_fields4resume
  32. from rag.nlp.search import index_name
  33. from rag.utils import rmSpace, num_tokens_from_string, encoder
  34. from api.utils.file_utils import get_project_base_directory
  35. class DialogService(CommonService):
  36. model = Dialog
  37. @classmethod
  38. @DB.connection_context()
  39. def get_list(cls, tenant_id,
  40. page_number, items_per_page, orderby, desc, id , name):
  41. chats = cls.model.select()
  42. if id:
  43. chats = chats.where(cls.model.id == id)
  44. if name:
  45. chats = chats.where(cls.model.name == name)
  46. chats = chats.where(
  47. (cls.model.tenant_id == tenant_id)
  48. & (cls.model.status == StatusEnum.VALID.value)
  49. )
  50. if desc:
  51. chats = chats.order_by(cls.model.getter_by(orderby).desc())
  52. else:
  53. chats = chats.order_by(cls.model.getter_by(orderby).asc())
  54. chats = chats.paginate(page_number, items_per_page)
  55. return list(chats.dicts())
  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. if len(msg) > 1:
  72. msg_.append(msg[-1])
  73. msg = msg_
  74. c = count()
  75. if c < max_length:
  76. return c, msg
  77. ll = num_tokens_from_string(msg_[0]["content"])
  78. ll2 = num_tokens_from_string(msg_[-1]["content"])
  79. if ll / (ll + ll2) > 0.8:
  80. m = msg_[0]["content"]
  81. m = encoder.decode(encoder.encode(m)[:max_length - ll2])
  82. msg[0]["content"] = m
  83. return max_length, msg
  84. m = msg_[1]["content"]
  85. m = encoder.decode(encoder.encode(m)[:max_length - ll2])
  86. msg[1]["content"] = m
  87. return max_length, msg
  88. def llm_id2llm_type(llm_id):
  89. llm_id, _ = TenantLLMService.split_model_name_and_factory(llm_id)
  90. fnm = os.path.join(get_project_base_directory(), "conf")
  91. llm_factories = json.load(open(os.path.join(fnm, "llm_factories.json"), "r"))
  92. for llm_factory in llm_factories["factory_llm_infos"]:
  93. for llm in llm_factory["llm"]:
  94. if llm_id == llm["llm_name"]:
  95. return llm["model_type"].strip(",")[-1]
  96. def chat(dialog, messages, stream=True, **kwargs):
  97. assert messages[-1]["role"] == "user", "The last content of this conversation is not from user."
  98. st = timer()
  99. llm_id, fid = TenantLLMService.split_model_name_and_factory(dialog.llm_id)
  100. llm = LLMService.query(llm_name=llm_id) if not fid else LLMService.query(llm_name=llm_id, fid=fid)
  101. if not llm:
  102. llm = TenantLLMService.query(tenant_id=dialog.tenant_id, llm_name=llm_id) if not fid else \
  103. TenantLLMService.query(tenant_id=dialog.tenant_id, llm_name=llm_id, llm_factory=fid)
  104. if not llm:
  105. raise LookupError("LLM(%s) not found" % dialog.llm_id)
  106. max_tokens = 8192
  107. else:
  108. max_tokens = llm[0].max_tokens
  109. kbs = KnowledgebaseService.get_by_ids(dialog.kb_ids)
  110. embd_nms = list(set([kb.embd_id for kb in kbs]))
  111. if len(embd_nms) != 1:
  112. yield {"answer": "**ERROR**: Knowledge bases use different embedding models.", "reference": []}
  113. return {"answer": "**ERROR**: Knowledge bases use different embedding models.", "reference": []}
  114. is_kg = all([kb.parser_id == ParserType.KG for kb in kbs])
  115. retr = settings.retrievaler if not is_kg else settings.kg_retrievaler
  116. questions = [m["content"] for m in messages if m["role"] == "user"][-3:]
  117. attachments = kwargs["doc_ids"].split(",") if "doc_ids" in kwargs else None
  118. if "doc_ids" in messages[-1]:
  119. attachments = messages[-1]["doc_ids"]
  120. for m in messages[:-1]:
  121. if "doc_ids" in m:
  122. attachments.extend(m["doc_ids"])
  123. embd_mdl = LLMBundle(dialog.tenant_id, LLMType.EMBEDDING, embd_nms[0])
  124. if not embd_mdl:
  125. raise LookupError("Embedding model(%s) not found" % 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. logging.debug("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. refineQ_tm = timer()
  155. keyword_tm = timer()
  156. rerank_mdl = None
  157. if dialog.rerank_id:
  158. rerank_mdl = LLMBundle(dialog.tenant_id, LLMType.RERANK, dialog.rerank_id)
  159. for _ in range(len(questions) // 2):
  160. questions.append(questions[-1])
  161. if "knowledge" not in [p["key"] for p in prompt_config["parameters"]]:
  162. kbinfos = {"total": 0, "chunks": [], "doc_aggs": []}
  163. else:
  164. if prompt_config.get("keyword", False):
  165. questions[-1] += keyword_extraction(chat_mdl, questions[-1])
  166. keyword_tm = timer()
  167. tenant_ids = list(set([kb.tenant_id for kb in kbs]))
  168. kbinfos = retr.retrieval(" ".join(questions), embd_mdl, tenant_ids, dialog.kb_ids, 1, dialog.top_n,
  169. dialog.similarity_threshold,
  170. dialog.vector_similarity_weight,
  171. doc_ids=attachments,
  172. top=dialog.top_k, aggs=False, rerank_mdl=rerank_mdl)
  173. knowledges = [ck["content_with_weight"] for ck in kbinfos["chunks"]]
  174. logging.debug(
  175. "{}->{}".format(" ".join(questions), "\n->".join(knowledges)))
  176. retrieval_tm = timer()
  177. if not knowledges and prompt_config.get("empty_response"):
  178. empty_res = prompt_config["empty_response"]
  179. yield {"answer": empty_res, "reference": kbinfos, "audio_binary": tts(tts_mdl, empty_res)}
  180. return {"answer": prompt_config["empty_response"], "reference": kbinfos}
  181. kwargs["knowledge"] = "\n\n------\n\n".join(knowledges)
  182. gen_conf = dialog.llm_setting
  183. msg = [{"role": "system", "content": prompt_config["system"].format(**kwargs)}]
  184. msg.extend([{"role": m["role"], "content": re.sub(r"##\d+\$\$", "", m["content"])}
  185. for m in messages if m["role"] != "system"])
  186. used_token_count, msg = message_fit_in(msg, int(max_tokens * 0.97))
  187. assert len(msg) >= 2, f"message_fit_in has bug: {msg}"
  188. prompt = msg[0]["content"]
  189. prompt += "\n\n### Query:\n%s" % " ".join(questions)
  190. if "max_tokens" in gen_conf:
  191. gen_conf["max_tokens"] = min(
  192. gen_conf["max_tokens"],
  193. max_tokens - used_token_count)
  194. def decorate_answer(answer):
  195. nonlocal prompt_config, knowledges, kwargs, kbinfos, prompt, retrieval_tm
  196. refs = []
  197. if knowledges and (prompt_config.get("quote", True) and kwargs.get("quote", True)):
  198. answer, idx = retr.insert_citations(answer,
  199. [ck["content_ltks"]
  200. for ck in kbinfos["chunks"]],
  201. [ck["vector"]
  202. for ck in kbinfos["chunks"]],
  203. embd_mdl,
  204. tkweight=1 - dialog.vector_similarity_weight,
  205. vtweight=dialog.vector_similarity_weight)
  206. idx = set([kbinfos["chunks"][int(i)]["doc_id"] for i in idx])
  207. recall_docs = [
  208. d for d in kbinfos["doc_aggs"] if d["doc_id"] in idx]
  209. if not recall_docs:
  210. recall_docs = kbinfos["doc_aggs"]
  211. kbinfos["doc_aggs"] = recall_docs
  212. refs = deepcopy(kbinfos)
  213. for c in refs["chunks"]:
  214. if c.get("vector"):
  215. del c["vector"]
  216. if answer.lower().find("invalid key") >= 0 or answer.lower().find("invalid api") >= 0:
  217. answer += " Please set LLM API-Key in 'User Setting -> Model providers -> API-Key'"
  218. done_tm = timer()
  219. prompt += "\n\n### Elapsed\n - Refine Question: %.1f ms\n - Keywords: %.1f ms\n - Retrieval: %.1f ms\n - LLM: %.1f ms" % (
  220. (refineQ_tm - st) * 1000, (keyword_tm - refineQ_tm) * 1000, (retrieval_tm - keyword_tm) * 1000,
  221. (done_tm - retrieval_tm) * 1000)
  222. return {"answer": answer, "reference": refs, "prompt": prompt}
  223. if stream:
  224. last_ans = ""
  225. answer = ""
  226. for ans in chat_mdl.chat_streamly(prompt, msg[1:], gen_conf):
  227. answer = ans
  228. delta_ans = ans[len(last_ans):]
  229. if num_tokens_from_string(delta_ans) < 16:
  230. continue
  231. last_ans = answer
  232. yield {"answer": answer, "reference": {}, "audio_binary": tts(tts_mdl, delta_ans)}
  233. delta_ans = answer[len(last_ans):]
  234. if delta_ans:
  235. yield {"answer": answer, "reference": {}, "audio_binary": tts(tts_mdl, delta_ans)}
  236. yield decorate_answer(answer)
  237. else:
  238. answer = chat_mdl.chat(prompt, msg[1:], gen_conf)
  239. logging.debug("User: {}|Assistant: {}".format(
  240. msg[-1]["content"], answer))
  241. res = decorate_answer(answer)
  242. res["audio_binary"] = tts(tts_mdl, answer)
  243. yield res
  244. def use_sql(question, field_map, tenant_id, chat_mdl, quota=True):
  245. sys_prompt = "你是一个DBA。你需要这对以下表的字段结构,根据用户的问题列表,写出最后一个问题对应的SQL。"
  246. user_promt = """
  247. 表名:{};
  248. 数据库表字段说明如下:
  249. {}
  250. 问题如下:
  251. {}
  252. 请写出SQL, 且只要SQL,不要有其他说明及文字。
  253. """.format(
  254. index_name(tenant_id),
  255. "\n".join([f"{k}: {v}" for k, v in field_map.items()]),
  256. question
  257. )
  258. tried_times = 0
  259. def get_table():
  260. nonlocal sys_prompt, user_promt, question, tried_times
  261. sql = chat_mdl.chat(sys_prompt, [{"role": "user", "content": user_promt}], {
  262. "temperature": 0.06})
  263. logging.debug(f"{question} ==> {user_promt} get SQL: {sql}")
  264. sql = re.sub(r"[\r\n]+", " ", sql.lower())
  265. sql = re.sub(r".*select ", "select ", sql.lower())
  266. sql = re.sub(r" +", " ", sql)
  267. sql = re.sub(r"([;;]|```).*", "", sql)
  268. if sql[:len("select ")] != "select ":
  269. return None, None
  270. if not re.search(r"((sum|avg|max|min)\(|group by )", sql.lower()):
  271. if sql[:len("select *")] != "select *":
  272. sql = "select doc_id,docnm_kwd," + sql[6:]
  273. else:
  274. flds = []
  275. for k in field_map.keys():
  276. if k in forbidden_select_fields4resume:
  277. continue
  278. if len(flds) > 11:
  279. break
  280. flds.append(k)
  281. sql = "select doc_id,docnm_kwd," + ",".join(flds) + sql[8:]
  282. logging.debug(f"{question} get SQL(refined): {sql}")
  283. tried_times += 1
  284. return settings.retrievaler.sql_retrieval(sql, format="json"), sql
  285. tbl, sql = get_table()
  286. if tbl is None:
  287. return None
  288. if tbl.get("error") and tried_times <= 2:
  289. user_promt = """
  290. 表名:{};
  291. 数据库表字段说明如下:
  292. {}
  293. 问题如下:
  294. {}
  295. 你上一次给出的错误SQL如下:
  296. {}
  297. 后台报错如下:
  298. {}
  299. 请纠正SQL中的错误再写一遍,且只要SQL,不要有其他说明及文字。
  300. """.format(
  301. index_name(tenant_id),
  302. "\n".join([f"{k}: {v}" for k, v in field_map.items()]),
  303. question, sql, tbl["error"]
  304. )
  305. tbl, sql = get_table()
  306. logging.debug("TRY it again: {}".format(sql))
  307. logging.debug("GET table: {}".format(tbl))
  308. if tbl.get("error") or len(tbl["rows"]) == 0:
  309. return None
  310. docid_idx = set([ii for ii, c in enumerate(
  311. tbl["columns"]) if c["name"] == "doc_id"])
  312. docnm_idx = set([ii for ii, c in enumerate(
  313. tbl["columns"]) if c["name"] == "docnm_kwd"])
  314. clmn_idx = [ii for ii in range(
  315. len(tbl["columns"])) if ii not in (docid_idx | docnm_idx)]
  316. # compose markdown table
  317. clmns = "|" + "|".join([re.sub(r"(/.*|([^()]+))", "", field_map.get(tbl["columns"][i]["name"],
  318. tbl["columns"][i]["name"])) for i in
  319. clmn_idx]) + ("|Source|" if docid_idx and docid_idx else "|")
  320. line = "|" + "|".join(["------" for _ in range(len(clmn_idx))]) + \
  321. ("|------|" if docid_idx and docid_idx else "")
  322. rows = ["|" +
  323. "|".join([rmSpace(str(r[i])) for i in clmn_idx]).replace("None", " ") +
  324. "|" for r in tbl["rows"]]
  325. rows = [r for r in rows if re.sub(r"[ |]+", "", r)]
  326. if quota:
  327. rows = "\n".join([r + f" ##{ii}$$ |" for ii, r in enumerate(rows)])
  328. else:
  329. rows = "\n".join([r + f" ##{ii}$$ |" for ii, r in enumerate(rows)])
  330. rows = re.sub(r"T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+Z)?\|", "|", rows)
  331. if not docid_idx or not docnm_idx:
  332. logging.warning("SQL missing field: " + sql)
  333. return {
  334. "answer": "\n".join([clmns, line, rows]),
  335. "reference": {"chunks": [], "doc_aggs": []},
  336. "prompt": sys_prompt
  337. }
  338. docid_idx = list(docid_idx)[0]
  339. docnm_idx = list(docnm_idx)[0]
  340. doc_aggs = {}
  341. for r in tbl["rows"]:
  342. if r[docid_idx] not in doc_aggs:
  343. doc_aggs[r[docid_idx]] = {"doc_name": r[docnm_idx], "count": 0}
  344. doc_aggs[r[docid_idx]]["count"] += 1
  345. return {
  346. "answer": "\n".join([clmns, line, rows]),
  347. "reference": {"chunks": [{"doc_id": r[docid_idx], "docnm_kwd": r[docnm_idx]} for r in tbl["rows"]],
  348. "doc_aggs": [{"doc_id": did, "doc_name": d["doc_name"], "count": d["count"]} for did, d in
  349. doc_aggs.items()]},
  350. "prompt": sys_prompt
  351. }
  352. def relevant(tenant_id, llm_id, question, contents: list):
  353. if llm_id2llm_type(llm_id) == "image2text":
  354. chat_mdl = LLMBundle(tenant_id, LLMType.IMAGE2TEXT, llm_id)
  355. else:
  356. chat_mdl = LLMBundle(tenant_id, LLMType.CHAT, llm_id)
  357. prompt = """
  358. You are a grader assessing relevance of a retrieved document to a user question.
  359. It does not need to be a stringent test. The goal is to filter out erroneous retrievals.
  360. If the document contains keyword(s) or semantic meaning related to the user question, grade it as relevant.
  361. Give a binary score 'yes' or 'no' score to indicate whether the document is relevant to the question.
  362. No other words needed except 'yes' or 'no'.
  363. """
  364. if not contents:
  365. return False
  366. contents = "Documents: \n" + " - ".join(contents)
  367. contents = f"Question: {question}\n" + contents
  368. if num_tokens_from_string(contents) >= chat_mdl.max_length - 4:
  369. contents = encoder.decode(encoder.encode(contents)[:chat_mdl.max_length - 4])
  370. ans = chat_mdl.chat(prompt, [{"role": "user", "content": contents}], {"temperature": 0.01})
  371. if ans.lower().find("yes") >= 0:
  372. return True
  373. return False
  374. def rewrite(tenant_id, llm_id, question):
  375. if llm_id2llm_type(llm_id) == "image2text":
  376. chat_mdl = LLMBundle(tenant_id, LLMType.IMAGE2TEXT, llm_id)
  377. else:
  378. chat_mdl = LLMBundle(tenant_id, LLMType.CHAT, llm_id)
  379. prompt = """
  380. You are an expert at query expansion to generate a paraphrasing of a question.
  381. I can't retrieval relevant information from the knowledge base by using user's question directly.
  382. You need to expand or paraphrase user's question by multiple ways such as using synonyms words/phrase,
  383. writing the abbreviation in its entirety, adding some extra descriptions or explanations,
  384. changing the way of expression, translating the original question into another language (English/Chinese), etc.
  385. And return 5 versions of question and one is from translation.
  386. Just list the question. No other words are needed.
  387. """
  388. ans = chat_mdl.chat(prompt, [{"role": "user", "content": question}], {"temperature": 0.8})
  389. return ans
  390. def keyword_extraction(chat_mdl, content, topn=3):
  391. prompt = f"""
  392. Role: You're a text analyzer.
  393. Task: extract the most important keywords/phrases of a given piece of text content.
  394. Requirements:
  395. - Summarize the text content, and give top {topn} important keywords/phrases.
  396. - The keywords MUST be in language of the given piece of text content.
  397. - The keywords are delimited by ENGLISH COMMA.
  398. - Keywords ONLY in output.
  399. ### Text Content
  400. {content}
  401. """
  402. msg = [
  403. {"role": "system", "content": prompt},
  404. {"role": "user", "content": "Output: "}
  405. ]
  406. _, msg = message_fit_in(msg, chat_mdl.max_length)
  407. kwd = chat_mdl.chat(prompt, msg[1:], {"temperature": 0.2})
  408. if isinstance(kwd, tuple):
  409. kwd = kwd[0]
  410. if kwd.find("**ERROR**") >=0:
  411. return ""
  412. return kwd
  413. def question_proposal(chat_mdl, content, topn=3):
  414. prompt = f"""
  415. Role: You're a text analyzer.
  416. Task: propose {topn} questions about a given piece of text content.
  417. Requirements:
  418. - Understand and summarize the text content, and propose top {topn} important questions.
  419. - The questions SHOULD NOT have overlapping meanings.
  420. - The questions SHOULD cover the main content of the text as much as possible.
  421. - The questions MUST be in language of the given piece of text content.
  422. - One question per line.
  423. - Question ONLY in output.
  424. ### Text Content
  425. {content}
  426. """
  427. msg = [
  428. {"role": "system", "content": prompt},
  429. {"role": "user", "content": "Output: "}
  430. ]
  431. _, msg = message_fit_in(msg, chat_mdl.max_length)
  432. kwd = chat_mdl.chat(prompt, msg[1:], {"temperature": 0.2})
  433. if isinstance(kwd, tuple):
  434. kwd = kwd[0]
  435. if kwd.find("**ERROR**") >= 0:
  436. return ""
  437. return kwd
  438. def full_question(tenant_id, llm_id, messages):
  439. if llm_id2llm_type(llm_id) == "image2text":
  440. chat_mdl = LLMBundle(tenant_id, LLMType.IMAGE2TEXT, llm_id)
  441. else:
  442. chat_mdl = LLMBundle(tenant_id, LLMType.CHAT, llm_id)
  443. conv = []
  444. for m in messages:
  445. if m["role"] not in ["user", "assistant"]:
  446. continue
  447. conv.append("{}: {}".format(m["role"].upper(), m["content"]))
  448. conv = "\n".join(conv)
  449. today = datetime.date.today().isoformat()
  450. yesterday = (datetime.date.today() - timedelta(days=1)).isoformat()
  451. tomorrow = (datetime.date.today() + timedelta(days=1)).isoformat()
  452. prompt = f"""
  453. Role: A helpful assistant
  454. Task and steps:
  455. 1. Generate a full user question that would follow the conversation.
  456. 2. If the user's question involves relative date, you need to convert it into absolute date based on the current date, which is {today}. For example: 'yesterday' would be converted to {yesterday}.
  457. Requirements & Restrictions:
  458. - Text generated MUST be in the same language of the original user's question.
  459. - If the user's latest question is completely, don't do anything, just return the original question.
  460. - DON'T generate anything except a refined question.
  461. ######################
  462. -Examples-
  463. ######################
  464. # Example 1
  465. ## Conversation
  466. USER: What is the name of Donald Trump's father?
  467. ASSISTANT: Fred Trump.
  468. USER: And his mother?
  469. ###############
  470. Output: What's the name of Donald Trump's mother?
  471. ------------
  472. # Example 2
  473. ## Conversation
  474. USER: What is the name of Donald Trump's father?
  475. ASSISTANT: Fred Trump.
  476. USER: And his mother?
  477. ASSISTANT: Mary Trump.
  478. User: What's her full name?
  479. ###############
  480. Output: What's the full name of Donald Trump's mother Mary Trump?
  481. ------------
  482. # Example 3
  483. ## Conversation
  484. USER: What's the weather today in London?
  485. ASSISTANT: Cloudy.
  486. USER: What's about tomorrow in Rochester?
  487. ###############
  488. Output: What's the weather in Rochester on {tomorrow}?
  489. ######################
  490. # Real Data
  491. ## Conversation
  492. {conv}
  493. ###############
  494. """
  495. ans = chat_mdl.chat(prompt, [{"role": "user", "content": "Output: "}], {"temperature": 0.2})
  496. return ans if ans.find("**ERROR**") < 0 else messages[-1]["content"]
  497. def tts(tts_mdl, text):
  498. if not tts_mdl or not text:
  499. return
  500. bin = b""
  501. for chunk in tts_mdl.tts(text):
  502. bin += chunk
  503. return binascii.hexlify(bin).decode("utf-8")
  504. def ask(question, kb_ids, tenant_id):
  505. kbs = KnowledgebaseService.get_by_ids(kb_ids)
  506. tenant_ids = [kb.tenant_id for kb in kbs]
  507. embd_nms = list(set([kb.embd_id for kb in kbs]))
  508. is_kg = all([kb.parser_id == ParserType.KG for kb in kbs])
  509. retr = settings.retrievaler if not is_kg else settings.kg_retrievaler
  510. embd_mdl = LLMBundle(tenant_id, LLMType.EMBEDDING, embd_nms[0])
  511. chat_mdl = LLMBundle(tenant_id, LLMType.CHAT)
  512. max_tokens = chat_mdl.max_length
  513. kbinfos = retr.retrieval(question, embd_mdl, tenant_ids, kb_ids, 1, 12, 0.1, 0.3, aggs=False)
  514. knowledges = [ck["content_with_weight"] for ck in kbinfos["chunks"]]
  515. used_token_count = 0
  516. for i, c in enumerate(knowledges):
  517. used_token_count += num_tokens_from_string(c)
  518. if max_tokens * 0.97 < used_token_count:
  519. knowledges = knowledges[:i]
  520. break
  521. prompt = """
  522. Role: You're a smart assistant. Your name is Miss R.
  523. Task: Summarize the information from knowledge bases and answer user's question.
  524. Requirements and restriction:
  525. - DO NOT make things up, especially for numbers.
  526. - If the information from knowledge is irrelevant with user's question, JUST SAY: Sorry, no relevant information provided.
  527. - Answer with markdown format text.
  528. - Answer in language of user's question.
  529. - DO NOT make things up, especially for numbers.
  530. ### Information from knowledge bases
  531. %s
  532. The above is information from knowledge bases.
  533. """%"\n".join(knowledges)
  534. msg = [{"role": "user", "content": question}]
  535. def decorate_answer(answer):
  536. nonlocal knowledges, kbinfos, prompt
  537. answer, idx = retr.insert_citations(answer,
  538. [ck["content_ltks"]
  539. for ck in kbinfos["chunks"]],
  540. [ck["vector"]
  541. for ck in kbinfos["chunks"]],
  542. embd_mdl,
  543. tkweight=0.7,
  544. vtweight=0.3)
  545. idx = set([kbinfos["chunks"][int(i)]["doc_id"] for i in idx])
  546. recall_docs = [
  547. d for d in kbinfos["doc_aggs"] if d["doc_id"] in idx]
  548. if not recall_docs:
  549. recall_docs = kbinfos["doc_aggs"]
  550. kbinfos["doc_aggs"] = recall_docs
  551. refs = deepcopy(kbinfos)
  552. for c in refs["chunks"]:
  553. if c.get("vector"):
  554. del c["vector"]
  555. if answer.lower().find("invalid key") >= 0 or answer.lower().find("invalid api") >= 0:
  556. answer += " Please set LLM API-Key in 'User Setting -> Model providers -> API-Key'"
  557. return {"answer": answer, "reference": refs}
  558. answer = ""
  559. for ans in chat_mdl.chat_streamly(prompt, msg, {"temperature": 0.1}):
  560. answer = ans
  561. yield {"answer": answer, "reference": {}}
  562. yield decorate_answer(answer)