Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

dialog_service.py 31KB

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