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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  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 json_repair
  21. import re
  22. from collections import defaultdict
  23. from copy import deepcopy
  24. from timeit import default_timer as timer
  25. import datetime
  26. from datetime import timedelta
  27. from api.db import LLMType, ParserType, StatusEnum
  28. from api.db.db_models import Dialog, DB
  29. from api.db.services.common_service import CommonService
  30. from api.db.services.document_service import DocumentService
  31. from api.db.services.knowledgebase_service import KnowledgebaseService
  32. from api.db.services.llm_service import TenantLLMService, LLMBundle
  33. from api import settings
  34. from graphrag.utils import get_tags_from_cache, set_tags_to_cache
  35. from rag.app.resume import forbidden_select_fields4resume
  36. from rag.nlp.search import index_name
  37. from rag.settings import TAG_FLD
  38. from rag.utils import rmSpace, num_tokens_from_string, encoder
  39. from api.utils.file_utils import get_project_base_directory
  40. class DialogService(CommonService):
  41. model = Dialog
  42. @classmethod
  43. @DB.connection_context()
  44. def get_list(cls, tenant_id,
  45. page_number, items_per_page, orderby, desc, id, name):
  46. chats = cls.model.select()
  47. if id:
  48. chats = chats.where(cls.model.id == id)
  49. if name:
  50. chats = chats.where(cls.model.name == name)
  51. chats = chats.where(
  52. (cls.model.tenant_id == tenant_id)
  53. & (cls.model.status == StatusEnum.VALID.value)
  54. )
  55. if desc:
  56. chats = chats.order_by(cls.model.getter_by(orderby).desc())
  57. else:
  58. chats = chats.order_by(cls.model.getter_by(orderby).asc())
  59. chats = chats.paginate(page_number, items_per_page)
  60. return list(chats.dicts())
  61. def message_fit_in(msg, max_length=4000):
  62. def count():
  63. nonlocal msg
  64. tks_cnts = []
  65. for m in msg:
  66. tks_cnts.append(
  67. {"role": m["role"], "count": num_tokens_from_string(m["content"])})
  68. total = 0
  69. for m in tks_cnts:
  70. total += m["count"]
  71. return total
  72. c = count()
  73. if c < max_length:
  74. return c, msg
  75. msg_ = [m for m in msg[:-1] if m["role"] == "system"]
  76. if len(msg) > 1:
  77. msg_.append(msg[-1])
  78. msg = msg_
  79. c = count()
  80. if c < max_length:
  81. return c, msg
  82. ll = num_tokens_from_string(msg_[0]["content"])
  83. ll2 = num_tokens_from_string(msg_[-1]["content"])
  84. if ll / (ll + ll2) > 0.8:
  85. m = msg_[0]["content"]
  86. m = encoder.decode(encoder.encode(m)[:max_length - ll2])
  87. msg[0]["content"] = m
  88. return max_length, msg
  89. m = msg_[1]["content"]
  90. m = encoder.decode(encoder.encode(m)[:max_length - ll2])
  91. msg[1]["content"] = m
  92. return max_length, msg
  93. def llm_id2llm_type(llm_id):
  94. llm_id, _ = TenantLLMService.split_model_name_and_factory(llm_id)
  95. fnm = os.path.join(get_project_base_directory(), "conf")
  96. llm_factories = json.load(open(os.path.join(fnm, "llm_factories.json"), "r"))
  97. for llm_factory in llm_factories["factory_llm_infos"]:
  98. for llm in llm_factory["llm"]:
  99. if llm_id == llm["llm_name"]:
  100. return llm["model_type"].strip(",")[-1]
  101. def kb_prompt(kbinfos, max_tokens):
  102. knowledges = [ck["content_with_weight"] for ck in kbinfos["chunks"]]
  103. used_token_count = 0
  104. chunks_num = 0
  105. for i, c in enumerate(knowledges):
  106. used_token_count += num_tokens_from_string(c)
  107. chunks_num += 1
  108. if max_tokens * 0.97 < used_token_count:
  109. knowledges = knowledges[:i]
  110. break
  111. docs = DocumentService.get_by_ids([ck["doc_id"] for ck in kbinfos["chunks"][:chunks_num]])
  112. docs = {d.id: d.meta_fields for d in docs}
  113. doc2chunks = defaultdict(lambda: {"chunks": [], "meta": []})
  114. for ck in kbinfos["chunks"][:chunks_num]:
  115. doc2chunks[ck["docnm_kwd"]]["chunks"].append(ck["content_with_weight"])
  116. doc2chunks[ck["docnm_kwd"]]["meta"] = docs.get(ck["doc_id"], {})
  117. knowledges = []
  118. for nm, cks_meta in doc2chunks.items():
  119. txt = f"Document: {nm} \n"
  120. for k,v in cks_meta["meta"].items():
  121. txt += f"{k}: {v}\n"
  122. txt += "Relevant fragments as following:\n"
  123. for i, chunk in enumerate(cks_meta["chunks"], 1):
  124. txt += f"{i}. {chunk}\n"
  125. knowledges.append(txt)
  126. return knowledges
  127. def label_question(question, kbs):
  128. tags = None
  129. tag_kb_ids = []
  130. for kb in kbs:
  131. if kb.parser_config.get("tag_kb_ids"):
  132. tag_kb_ids.extend(kb.parser_config["tag_kb_ids"])
  133. if tag_kb_ids:
  134. all_tags = get_tags_from_cache(tag_kb_ids)
  135. if not all_tags:
  136. all_tags = settings.retrievaler.all_tags_in_portion(kb.tenant_id, tag_kb_ids)
  137. set_tags_to_cache(all_tags, tag_kb_ids)
  138. else:
  139. all_tags = json.loads(all_tags)
  140. tag_kbs = KnowledgebaseService.get_by_ids(tag_kb_ids)
  141. tags = settings.retrievaler.tag_query(question,
  142. list(set([kb.tenant_id for kb in tag_kbs])),
  143. tag_kb_ids,
  144. all_tags,
  145. kb.parser_config.get("topn_tags", 3)
  146. )
  147. return tags
  148. def chat(dialog, messages, stream=True, **kwargs):
  149. assert messages[-1]["role"] == "user", "The last content of this conversation is not from user."
  150. chat_start_ts = timer()
  151. if llm_id2llm_type(dialog.llm_id) == "image2text":
  152. llm_model_config = TenantLLMService.get_model_config(dialog.tenant_id, LLMType.IMAGE2TEXT, dialog.llm_id)
  153. else:
  154. llm_model_config = TenantLLMService.get_model_config(dialog.tenant_id, LLMType.CHAT, dialog.llm_id)
  155. max_tokens = llm_model_config.get("max_tokens", 8192)
  156. check_llm_ts = timer()
  157. kbs = KnowledgebaseService.get_by_ids(dialog.kb_ids)
  158. embedding_list = list(set([kb.embd_id for kb in kbs]))
  159. if len(embedding_list) != 1:
  160. yield {"answer": "**ERROR**: Knowledge bases use different embedding models.", "reference": []}
  161. return {"answer": "**ERROR**: Knowledge bases use different embedding models.", "reference": []}
  162. embedding_model_name = embedding_list[0]
  163. retriever = settings.retrievaler
  164. questions = [m["content"] for m in messages if m["role"] == "user"][-3:]
  165. attachments = kwargs["doc_ids"].split(",") if "doc_ids" in kwargs else None
  166. if "doc_ids" in messages[-1]:
  167. attachments = messages[-1]["doc_ids"]
  168. create_retriever_ts = timer()
  169. embd_mdl = LLMBundle(dialog.tenant_id, LLMType.EMBEDDING, embedding_model_name)
  170. if not embd_mdl:
  171. raise LookupError("Embedding model(%s) not found" % embedding_model_name)
  172. bind_embedding_ts = timer()
  173. if llm_id2llm_type(dialog.llm_id) == "image2text":
  174. chat_mdl = LLMBundle(dialog.tenant_id, LLMType.IMAGE2TEXT, dialog.llm_id)
  175. else:
  176. chat_mdl = LLMBundle(dialog.tenant_id, LLMType.CHAT, dialog.llm_id)
  177. bind_llm_ts = timer()
  178. prompt_config = dialog.prompt_config
  179. field_map = KnowledgebaseService.get_field_map(dialog.kb_ids)
  180. tts_mdl = None
  181. if prompt_config.get("tts"):
  182. tts_mdl = LLMBundle(dialog.tenant_id, LLMType.TTS)
  183. # try to use sql if field mapping is good to go
  184. if field_map:
  185. logging.debug("Use SQL to retrieval:{}".format(questions[-1]))
  186. ans = use_sql(questions[-1], field_map, dialog.tenant_id, chat_mdl, prompt_config.get("quote", True))
  187. if ans:
  188. yield ans
  189. return
  190. for p in prompt_config["parameters"]:
  191. if p["key"] == "knowledge":
  192. continue
  193. if p["key"] not in kwargs and not p["optional"]:
  194. raise KeyError("Miss parameter: " + p["key"])
  195. if p["key"] not in kwargs:
  196. prompt_config["system"] = prompt_config["system"].replace(
  197. "{%s}" % p["key"], " ")
  198. if len(questions) > 1 and prompt_config.get("refine_multiturn"):
  199. questions = [full_question(dialog.tenant_id, dialog.llm_id, messages)]
  200. else:
  201. questions = questions[-1:]
  202. refine_question_ts = timer()
  203. rerank_mdl = None
  204. if dialog.rerank_id:
  205. rerank_mdl = LLMBundle(dialog.tenant_id, LLMType.RERANK, dialog.rerank_id)
  206. bind_reranker_ts = timer()
  207. generate_keyword_ts = bind_reranker_ts
  208. if "knowledge" not in [p["key"] for p in prompt_config["parameters"]]:
  209. kbinfos = {"total": 0, "chunks": [], "doc_aggs": []}
  210. else:
  211. if prompt_config.get("keyword", False):
  212. questions[-1] += keyword_extraction(chat_mdl, questions[-1])
  213. generate_keyword_ts = timer()
  214. tenant_ids = list(set([kb.tenant_id for kb in kbs]))
  215. kbinfos = retriever.retrieval(" ".join(questions), embd_mdl, tenant_ids, dialog.kb_ids, 1, dialog.top_n,
  216. dialog.similarity_threshold,
  217. dialog.vector_similarity_weight,
  218. doc_ids=attachments,
  219. top=dialog.top_k, aggs=False, rerank_mdl=rerank_mdl,
  220. rank_feature=label_question(" ".join(questions), kbs)
  221. )
  222. if prompt_config.get("use_kg"):
  223. ck = settings.kg_retrievaler.retrieval(" ".join(questions),
  224. tenant_ids,
  225. dialog.kb_ids,
  226. embd_mdl,
  227. LLMBundle(dialog.tenant_id, LLMType.CHAT))
  228. if ck["content_with_weight"]:
  229. kbinfos["chunks"].insert(0, ck)
  230. retrieval_ts = timer()
  231. knowledges = kb_prompt(kbinfos, max_tokens)
  232. logging.debug(
  233. "{}->{}".format(" ".join(questions), "\n->".join(knowledges)))
  234. if not knowledges and prompt_config.get("empty_response"):
  235. empty_res = prompt_config["empty_response"]
  236. yield {"answer": empty_res, "reference": kbinfos, "audio_binary": tts(tts_mdl, empty_res)}
  237. return {"answer": prompt_config["empty_response"], "reference": kbinfos}
  238. kwargs["knowledge"] = "\n------\n" + "\n\n------\n\n".join(knowledges)
  239. gen_conf = dialog.llm_setting
  240. msg = [{"role": "system", "content": prompt_config["system"].format(**kwargs)}]
  241. msg.extend([{"role": m["role"], "content": re.sub(r"##\d+\$\$", "", m["content"])}
  242. for m in messages if m["role"] != "system"])
  243. used_token_count, msg = message_fit_in(msg, int(max_tokens * 0.97))
  244. assert len(msg) >= 2, f"message_fit_in has bug: {msg}"
  245. prompt = msg[0]["content"]
  246. prompt += "\n\n### Query:\n%s" % " ".join(questions)
  247. if "max_tokens" in gen_conf:
  248. gen_conf["max_tokens"] = min(
  249. gen_conf["max_tokens"],
  250. max_tokens - used_token_count)
  251. def decorate_answer(answer):
  252. nonlocal prompt_config, knowledges, kwargs, kbinfos, prompt, retrieval_ts
  253. finish_chat_ts = timer()
  254. refs = []
  255. if knowledges and (prompt_config.get("quote", True) and kwargs.get("quote", True)):
  256. answer, idx = retriever.insert_citations(answer,
  257. [ck["content_ltks"]
  258. for ck in kbinfos["chunks"]],
  259. [ck["vector"]
  260. for ck in kbinfos["chunks"]],
  261. embd_mdl,
  262. tkweight=1 - dialog.vector_similarity_weight,
  263. vtweight=dialog.vector_similarity_weight)
  264. idx = set([kbinfos["chunks"][int(i)]["doc_id"] for i in idx])
  265. recall_docs = [
  266. d for d in kbinfos["doc_aggs"] if d["doc_id"] in idx]
  267. if not recall_docs:
  268. recall_docs = kbinfos["doc_aggs"]
  269. kbinfos["doc_aggs"] = recall_docs
  270. refs = deepcopy(kbinfos)
  271. for c in refs["chunks"]:
  272. if c.get("vector"):
  273. del c["vector"]
  274. if answer.lower().find("invalid key") >= 0 or answer.lower().find("invalid api") >= 0:
  275. answer += " Please set LLM API-Key in 'User Setting -> Model providers -> API-Key'"
  276. finish_chat_ts = timer()
  277. total_time_cost = (finish_chat_ts - chat_start_ts) * 1000
  278. check_llm_time_cost = (check_llm_ts - chat_start_ts) * 1000
  279. create_retriever_time_cost = (create_retriever_ts - check_llm_ts) * 1000
  280. bind_embedding_time_cost = (bind_embedding_ts - create_retriever_ts) * 1000
  281. bind_llm_time_cost = (bind_llm_ts - bind_embedding_ts) * 1000
  282. refine_question_time_cost = (refine_question_ts - bind_llm_ts) * 1000
  283. bind_reranker_time_cost = (bind_reranker_ts - refine_question_ts) * 1000
  284. generate_keyword_time_cost = (generate_keyword_ts - bind_reranker_ts) * 1000
  285. retrieval_time_cost = (retrieval_ts - generate_keyword_ts) * 1000
  286. generate_result_time_cost = (finish_chat_ts - retrieval_ts) * 1000
  287. prompt = f"{prompt}\n\n - Total: {total_time_cost:.1f}ms\n - Check LLM: {check_llm_time_cost:.1f}ms\n - Create retriever: {create_retriever_time_cost:.1f}ms\n - Bind embedding: {bind_embedding_time_cost:.1f}ms\n - Bind LLM: {bind_llm_time_cost:.1f}ms\n - Tune question: {refine_question_time_cost:.1f}ms\n - Bind reranker: {bind_reranker_time_cost:.1f}ms\n - Generate keyword: {generate_keyword_time_cost:.1f}ms\n - Retrieval: {retrieval_time_cost:.1f}ms\n - Generate answer: {generate_result_time_cost:.1f}ms"
  288. return {"answer": answer, "reference": refs, "prompt": re.sub(r"\n", " \n", prompt)}
  289. if stream:
  290. last_ans = ""
  291. answer = ""
  292. for ans in chat_mdl.chat_streamly(prompt, msg[1:], gen_conf):
  293. answer = ans
  294. delta_ans = ans[len(last_ans):]
  295. if num_tokens_from_string(delta_ans) < 16:
  296. continue
  297. last_ans = answer
  298. yield {"answer": answer, "reference": {}, "audio_binary": tts(tts_mdl, delta_ans)}
  299. delta_ans = answer[len(last_ans):]
  300. if delta_ans:
  301. yield {"answer": answer, "reference": {}, "audio_binary": tts(tts_mdl, delta_ans)}
  302. yield decorate_answer(answer)
  303. else:
  304. answer = chat_mdl.chat(prompt, msg[1:], gen_conf)
  305. user_content = msg[-1].get("content", "[content not available]")
  306. logging.debug("User: {}|Assistant: {}".format(user_content, answer))
  307. res = decorate_answer(answer)
  308. res["audio_binary"] = tts(tts_mdl, answer)
  309. yield res
  310. def use_sql(question, field_map, tenant_id, chat_mdl, quota=True):
  311. sys_prompt = "You are a Database Administrator. You need to check the fields of the following tables based on the user's list of questions and write the SQL corresponding to the last question."
  312. user_prompt = """
  313. Table name: {};
  314. Table of database fields are as follows:
  315. {}
  316. Question are as follows:
  317. {}
  318. Please write the SQL, only SQL, without any other explanations or text.
  319. """.format(
  320. index_name(tenant_id),
  321. "\n".join([f"{k}: {v}" for k, v in field_map.items()]),
  322. question
  323. )
  324. tried_times = 0
  325. def get_table():
  326. nonlocal sys_prompt, user_prompt, question, tried_times
  327. sql = chat_mdl.chat(sys_prompt, [{"role": "user", "content": user_prompt}], {
  328. "temperature": 0.06})
  329. logging.debug(f"{question} ==> {user_prompt} get SQL: {sql}")
  330. sql = re.sub(r"[\r\n]+", " ", sql.lower())
  331. sql = re.sub(r".*select ", "select ", sql.lower())
  332. sql = re.sub(r" +", " ", sql)
  333. sql = re.sub(r"([;;]|```).*", "", sql)
  334. if sql[:len("select ")] != "select ":
  335. return None, None
  336. if not re.search(r"((sum|avg|max|min)\(|group by )", sql.lower()):
  337. if sql[:len("select *")] != "select *":
  338. sql = "select doc_id,docnm_kwd," + sql[6:]
  339. else:
  340. flds = []
  341. for k in field_map.keys():
  342. if k in forbidden_select_fields4resume:
  343. continue
  344. if len(flds) > 11:
  345. break
  346. flds.append(k)
  347. sql = "select doc_id,docnm_kwd," + ",".join(flds) + sql[8:]
  348. logging.debug(f"{question} get SQL(refined): {sql}")
  349. tried_times += 1
  350. return settings.retrievaler.sql_retrieval(sql, format="json"), sql
  351. tbl, sql = get_table()
  352. if tbl is None:
  353. return None
  354. if tbl.get("error") and tried_times <= 2:
  355. user_prompt = """
  356. Table name: {};
  357. Table of database fields are as follows:
  358. {}
  359. Question are as follows:
  360. {}
  361. Please write the SQL, only SQL, without any other explanations or text.
  362. The SQL error you provided last time is as follows:
  363. {}
  364. Error issued by database as follows:
  365. {}
  366. Please correct the error and write SQL again, only SQL, without any other explanations or text.
  367. """.format(
  368. index_name(tenant_id),
  369. "\n".join([f"{k}: {v}" for k, v in field_map.items()]),
  370. question, sql, tbl["error"]
  371. )
  372. tbl, sql = get_table()
  373. logging.debug("TRY it again: {}".format(sql))
  374. logging.debug("GET table: {}".format(tbl))
  375. if tbl.get("error") or len(tbl["rows"]) == 0:
  376. return None
  377. docid_idx = set([ii for ii, c in enumerate(
  378. tbl["columns"]) if c["name"] == "doc_id"])
  379. doc_name_idx = set([ii for ii, c in enumerate(
  380. tbl["columns"]) if c["name"] == "docnm_kwd"])
  381. column_idx = [ii for ii in range(
  382. len(tbl["columns"])) if ii not in (docid_idx | doc_name_idx)]
  383. # compose Markdown table
  384. columns = "|" + "|".join([re.sub(r"(/.*|([^()]+))", "", field_map.get(tbl["columns"][i]["name"],
  385. tbl["columns"][i]["name"])) for i in
  386. column_idx]) + ("|Source|" if docid_idx and docid_idx else "|")
  387. line = "|" + "|".join(["------" for _ in range(len(column_idx))]) + \
  388. ("|------|" if docid_idx and docid_idx else "")
  389. rows = ["|" +
  390. "|".join([rmSpace(str(r[i])) for i in column_idx]).replace("None", " ") +
  391. "|" for r in tbl["rows"]]
  392. rows = [r for r in rows if re.sub(r"[ |]+", "", r)]
  393. if quota:
  394. rows = "\n".join([r + f" ##{ii}$$ |" for ii, r in enumerate(rows)])
  395. else:
  396. rows = "\n".join([r + f" ##{ii}$$ |" for ii, r in enumerate(rows)])
  397. rows = re.sub(r"T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+Z)?\|", "|", rows)
  398. if not docid_idx or not doc_name_idx:
  399. logging.warning("SQL missing field: " + sql)
  400. return {
  401. "answer": "\n".join([columns, line, rows]),
  402. "reference": {"chunks": [], "doc_aggs": []},
  403. "prompt": sys_prompt
  404. }
  405. docid_idx = list(docid_idx)[0]
  406. doc_name_idx = list(doc_name_idx)[0]
  407. doc_aggs = {}
  408. for r in tbl["rows"]:
  409. if r[docid_idx] not in doc_aggs:
  410. doc_aggs[r[docid_idx]] = {"doc_name": r[doc_name_idx], "count": 0}
  411. doc_aggs[r[docid_idx]]["count"] += 1
  412. return {
  413. "answer": "\n".join([columns, line, rows]),
  414. "reference": {"chunks": [{"doc_id": r[docid_idx], "docnm_kwd": r[doc_name_idx]} for r in tbl["rows"]],
  415. "doc_aggs": [{"doc_id": did, "doc_name": d["doc_name"], "count": d["count"]} for did, d in
  416. doc_aggs.items()]},
  417. "prompt": sys_prompt
  418. }
  419. def relevant(tenant_id, llm_id, question, contents: list):
  420. if llm_id2llm_type(llm_id) == "image2text":
  421. chat_mdl = LLMBundle(tenant_id, LLMType.IMAGE2TEXT, llm_id)
  422. else:
  423. chat_mdl = LLMBundle(tenant_id, LLMType.CHAT, llm_id)
  424. prompt = """
  425. You are a grader assessing relevance of a retrieved document to a user question.
  426. It does not need to be a stringent test. The goal is to filter out erroneous retrievals.
  427. If the document contains keyword(s) or semantic meaning related to the user question, grade it as relevant.
  428. Give a binary score 'yes' or 'no' score to indicate whether the document is relevant to the question.
  429. No other words needed except 'yes' or 'no'.
  430. """
  431. if not contents:
  432. return False
  433. contents = "Documents: \n" + " - ".join(contents)
  434. contents = f"Question: {question}\n" + contents
  435. if num_tokens_from_string(contents) >= chat_mdl.max_length - 4:
  436. contents = encoder.decode(encoder.encode(contents)[:chat_mdl.max_length - 4])
  437. ans = chat_mdl.chat(prompt, [{"role": "user", "content": contents}], {"temperature": 0.01})
  438. if ans.lower().find("yes") >= 0:
  439. return True
  440. return False
  441. def rewrite(tenant_id, llm_id, question):
  442. if llm_id2llm_type(llm_id) == "image2text":
  443. chat_mdl = LLMBundle(tenant_id, LLMType.IMAGE2TEXT, llm_id)
  444. else:
  445. chat_mdl = LLMBundle(tenant_id, LLMType.CHAT, llm_id)
  446. prompt = """
  447. You are an expert at query expansion to generate a paraphrasing of a question.
  448. I can't retrieval relevant information from the knowledge base by using user's question directly.
  449. You need to expand or paraphrase user's question by multiple ways such as using synonyms words/phrase,
  450. writing the abbreviation in its entirety, adding some extra descriptions or explanations,
  451. changing the way of expression, translating the original question into another language (English/Chinese), etc.
  452. And return 5 versions of question and one is from translation.
  453. Just list the question. No other words are needed.
  454. """
  455. ans = chat_mdl.chat(prompt, [{"role": "user", "content": question}], {"temperature": 0.8})
  456. return ans
  457. def keyword_extraction(chat_mdl, content, topn=3):
  458. prompt = f"""
  459. Role: You're a text analyzer.
  460. Task: extract the most important keywords/phrases of a given piece of text content.
  461. Requirements:
  462. - Summarize the text content, and give top {topn} important keywords/phrases.
  463. - The keywords MUST be in language of the given piece of text content.
  464. - The keywords are delimited by ENGLISH COMMA.
  465. - Keywords ONLY in output.
  466. ### Text Content
  467. {content}
  468. """
  469. msg = [
  470. {"role": "system", "content": prompt},
  471. {"role": "user", "content": "Output: "}
  472. ]
  473. _, msg = message_fit_in(msg, chat_mdl.max_length)
  474. kwd = chat_mdl.chat(prompt, msg[1:], {"temperature": 0.2})
  475. if isinstance(kwd, tuple):
  476. kwd = kwd[0]
  477. kwd = re.sub(r"<think>.*</think>", "", kwd, flags=re.DOTALL)
  478. if kwd.find("**ERROR**") >= 0:
  479. return ""
  480. return kwd
  481. def question_proposal(chat_mdl, content, topn=3):
  482. prompt = f"""
  483. Role: You're a text analyzer.
  484. Task: propose {topn} questions about a given piece of text content.
  485. Requirements:
  486. - Understand and summarize the text content, and propose top {topn} important questions.
  487. - The questions SHOULD NOT have overlapping meanings.
  488. - The questions SHOULD cover the main content of the text as much as possible.
  489. - The questions MUST be in language of the given piece of text content.
  490. - One question per line.
  491. - Question ONLY in output.
  492. ### Text Content
  493. {content}
  494. """
  495. msg = [
  496. {"role": "system", "content": prompt},
  497. {"role": "user", "content": "Output: "}
  498. ]
  499. _, msg = message_fit_in(msg, chat_mdl.max_length)
  500. kwd = chat_mdl.chat(prompt, msg[1:], {"temperature": 0.2})
  501. if isinstance(kwd, tuple):
  502. kwd = kwd[0]
  503. kwd = re.sub(r"<think>.*</think>", "", kwd, flags=re.DOTALL)
  504. if kwd.find("**ERROR**") >= 0:
  505. return ""
  506. return kwd
  507. def full_question(tenant_id, llm_id, messages):
  508. if llm_id2llm_type(llm_id) == "image2text":
  509. chat_mdl = LLMBundle(tenant_id, LLMType.IMAGE2TEXT, llm_id)
  510. else:
  511. chat_mdl = LLMBundle(tenant_id, LLMType.CHAT, llm_id)
  512. conv = []
  513. for m in messages:
  514. if m["role"] not in ["user", "assistant"]:
  515. continue
  516. conv.append("{}: {}".format(m["role"].upper(), m["content"]))
  517. conv = "\n".join(conv)
  518. today = datetime.date.today().isoformat()
  519. yesterday = (datetime.date.today() - timedelta(days=1)).isoformat()
  520. tomorrow = (datetime.date.today() + timedelta(days=1)).isoformat()
  521. prompt = f"""
  522. Role: A helpful assistant
  523. Task and steps:
  524. 1. Generate a full user question that would follow the conversation.
  525. 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}.
  526. Requirements & Restrictions:
  527. - Text generated MUST be in the same language of the original user's question.
  528. - If the user's latest question is completely, don't do anything, just return the original question.
  529. - DON'T generate anything except a refined question.
  530. ######################
  531. -Examples-
  532. ######################
  533. # Example 1
  534. ## Conversation
  535. USER: What is the name of Donald Trump's father?
  536. ASSISTANT: Fred Trump.
  537. USER: And his mother?
  538. ###############
  539. Output: What's the name of Donald Trump's mother?
  540. ------------
  541. # Example 2
  542. ## Conversation
  543. USER: What is the name of Donald Trump's father?
  544. ASSISTANT: Fred Trump.
  545. USER: And his mother?
  546. ASSISTANT: Mary Trump.
  547. User: What's her full name?
  548. ###############
  549. Output: What's the full name of Donald Trump's mother Mary Trump?
  550. ------------
  551. # Example 3
  552. ## Conversation
  553. USER: What's the weather today in London?
  554. ASSISTANT: Cloudy.
  555. USER: What's about tomorrow in Rochester?
  556. ###############
  557. Output: What's the weather in Rochester on {tomorrow}?
  558. ######################
  559. # Real Data
  560. ## Conversation
  561. {conv}
  562. ###############
  563. """
  564. ans = chat_mdl.chat(prompt, [{"role": "user", "content": "Output: "}], {"temperature": 0.2})
  565. ans = re.sub(r"<think>.*</think>", "", ans, flags=re.DOTALL)
  566. return ans if ans.find("**ERROR**") < 0 else messages[-1]["content"]
  567. def tts(tts_mdl, text):
  568. if not tts_mdl or not text:
  569. return
  570. bin = b""
  571. for chunk in tts_mdl.tts(text):
  572. bin += chunk
  573. return binascii.hexlify(bin).decode("utf-8")
  574. def ask(question, kb_ids, tenant_id):
  575. kbs = KnowledgebaseService.get_by_ids(kb_ids)
  576. embedding_list = list(set([kb.embd_id for kb in kbs]))
  577. is_knowledge_graph = all([kb.parser_id == ParserType.KG for kb in kbs])
  578. retriever = settings.retrievaler if not is_knowledge_graph else settings.kg_retrievaler
  579. embd_mdl = LLMBundle(tenant_id, LLMType.EMBEDDING, embedding_list[0])
  580. chat_mdl = LLMBundle(tenant_id, LLMType.CHAT)
  581. max_tokens = chat_mdl.max_length
  582. tenant_ids = list(set([kb.tenant_id for kb in kbs]))
  583. kbinfos = retriever.retrieval(question, embd_mdl, tenant_ids, kb_ids,
  584. 1, 12, 0.1, 0.3, aggs=False,
  585. rank_feature=label_question(question, kbs)
  586. )
  587. knowledges = kb_prompt(kbinfos, max_tokens)
  588. prompt = """
  589. Role: You're a smart assistant. Your name is Miss R.
  590. Task: Summarize the information from knowledge bases and answer user's question.
  591. Requirements and restriction:
  592. - DO NOT make things up, especially for numbers.
  593. - If the information from knowledge is irrelevant with user's question, JUST SAY: Sorry, no relevant information provided.
  594. - Answer with markdown format text.
  595. - Answer in language of user's question.
  596. - DO NOT make things up, especially for numbers.
  597. ### Information from knowledge bases
  598. %s
  599. The above is information from knowledge bases.
  600. """ % "\n".join(knowledges)
  601. msg = [{"role": "user", "content": question}]
  602. def decorate_answer(answer):
  603. nonlocal knowledges, kbinfos, prompt
  604. answer, idx = retriever.insert_citations(answer,
  605. [ck["content_ltks"]
  606. for ck in kbinfos["chunks"]],
  607. [ck["vector"]
  608. for ck in kbinfos["chunks"]],
  609. embd_mdl,
  610. tkweight=0.7,
  611. vtweight=0.3)
  612. idx = set([kbinfos["chunks"][int(i)]["doc_id"] for i in idx])
  613. recall_docs = [
  614. d for d in kbinfos["doc_aggs"] if d["doc_id"] in idx]
  615. if not recall_docs:
  616. recall_docs = kbinfos["doc_aggs"]
  617. kbinfos["doc_aggs"] = recall_docs
  618. refs = deepcopy(kbinfos)
  619. for c in refs["chunks"]:
  620. if c.get("vector"):
  621. del c["vector"]
  622. if answer.lower().find("invalid key") >= 0 or answer.lower().find("invalid api") >= 0:
  623. answer += " Please set LLM API-Key in 'User Setting -> Model Providers -> API-Key'"
  624. return {"answer": answer, "reference": refs}
  625. answer = ""
  626. for ans in chat_mdl.chat_streamly(prompt, msg, {"temperature": 0.1}):
  627. answer = ans
  628. yield {"answer": answer, "reference": {}}
  629. yield decorate_answer(answer)
  630. def content_tagging(chat_mdl, content, all_tags, examples, topn=3):
  631. prompt = f"""
  632. Role: You're a text analyzer.
  633. Task: Tag (put on some labels) to a given piece of text content based on the examples and the entire tag set.
  634. Steps::
  635. - Comprehend the tag/label set.
  636. - Comprehend examples which all consist of both text content and assigned tags with relevance score in format of JSON.
  637. - Summarize the text content, and tag it with top {topn} most relevant tags from the set of tag/label and the corresponding relevance score.
  638. Requirements
  639. - The tags MUST be from the tag set.
  640. - The output MUST be in JSON format only, the key is tag and the value is its relevance score.
  641. - The relevance score must be range from 1 to 10.
  642. - Keywords ONLY in output.
  643. # TAG SET
  644. {", ".join(all_tags)}
  645. """
  646. for i, ex in enumerate(examples):
  647. prompt += """
  648. # Examples {}
  649. ### Text Content
  650. {}
  651. Output:
  652. {}
  653. """.format(i, ex["content"], json.dumps(ex[TAG_FLD], indent=2, ensure_ascii=False))
  654. prompt += f"""
  655. # Real Data
  656. ### Text Content
  657. {content}
  658. """
  659. msg = [
  660. {"role": "system", "content": prompt},
  661. {"role": "user", "content": "Output: "}
  662. ]
  663. _, msg = message_fit_in(msg, chat_mdl.max_length)
  664. kwd = chat_mdl.chat(prompt, msg[1:], {"temperature": 0.5})
  665. if isinstance(kwd, tuple):
  666. kwd = kwd[0]
  667. kwd = re.sub(r"<think>.*</think>", "", kwd, flags=re.DOTALL)
  668. if kwd.find("**ERROR**") >= 0:
  669. raise Exception(kwd)
  670. try:
  671. return json_repair.loads(kwd)
  672. except json_repair.JSONDecodeError:
  673. try:
  674. result = kwd.replace(prompt[:-1], '').replace('user', '').replace('model', '').strip()
  675. result = '{' + result.split('{')[1].split('}')[0] + '}'
  676. return json_repair.loads(result)
  677. except Exception as e:
  678. logging.exception(f"JSON parsing error: {result} -> {e}")
  679. raise e