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

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