Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

dialog_service.py 32KB

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