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

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