Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

dialog_service.py 26KB

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