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.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  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 time
  21. import json_repair
  22. import re
  23. from collections import defaultdict
  24. from copy import deepcopy
  25. from timeit import default_timer as timer
  26. import datetime
  27. from datetime import timedelta
  28. from api.db import LLMType, ParserType, StatusEnum
  29. from api.db.db_models import Dialog, DB
  30. from api.db.services.common_service import CommonService
  31. from api.db.services.document_service import DocumentService
  32. from api.db.services.knowledgebase_service import KnowledgebaseService
  33. from api.db.services.llm_service import TenantLLMService, LLMBundle
  34. from api import settings
  35. from graphrag.utils import get_tags_from_cache, set_tags_to_cache
  36. from rag.app.resume import forbidden_select_fields4resume
  37. from rag.nlp import extract_between
  38. from rag.nlp.search import index_name
  39. from rag.settings import TAG_FLD
  40. from rag.utils import rmSpace, num_tokens_from_string, encoder
  41. from api.utils.file_utils import get_project_base_directory
  42. class DialogService(CommonService):
  43. model = Dialog
  44. @classmethod
  45. @DB.connection_context()
  46. def get_list(cls, tenant_id,
  47. page_number, items_per_page, orderby, desc, id, name):
  48. chats = cls.model.select()
  49. if id:
  50. chats = chats.where(cls.model.id == id)
  51. if name:
  52. chats = chats.where(cls.model.name == name)
  53. chats = chats.where(
  54. (cls.model.tenant_id == tenant_id)
  55. & (cls.model.status == StatusEnum.VALID.value)
  56. )
  57. if desc:
  58. chats = chats.order_by(cls.model.getter_by(orderby).desc())
  59. else:
  60. chats = chats.order_by(cls.model.getter_by(orderby).asc())
  61. chats = chats.paginate(page_number, items_per_page)
  62. return list(chats.dicts())
  63. def message_fit_in(msg, max_length=4000):
  64. def count():
  65. nonlocal msg
  66. tks_cnts = []
  67. for m in msg:
  68. tks_cnts.append(
  69. {"role": m["role"], "count": num_tokens_from_string(m["content"])})
  70. total = 0
  71. for m in tks_cnts:
  72. total += m["count"]
  73. return total
  74. c = count()
  75. if c < max_length:
  76. return c, msg
  77. msg_ = [m for m in msg[:-1] if m["role"] == "system"]
  78. if len(msg) > 1:
  79. msg_.append(msg[-1])
  80. msg = msg_
  81. c = count()
  82. if c < max_length:
  83. return c, msg
  84. ll = num_tokens_from_string(msg_[0]["content"])
  85. ll2 = num_tokens_from_string(msg_[-1]["content"])
  86. if ll / (ll + ll2) > 0.8:
  87. m = msg_[0]["content"]
  88. m = encoder.decode(encoder.encode(m)[:max_length - ll2])
  89. msg[0]["content"] = m
  90. return max_length, msg
  91. m = msg_[1]["content"]
  92. m = encoder.decode(encoder.encode(m)[:max_length - ll2])
  93. msg[1]["content"] = m
  94. return max_length, msg
  95. def llm_id2llm_type(llm_id):
  96. llm_id, _ = TenantLLMService.split_model_name_and_factory(llm_id)
  97. fnm = os.path.join(get_project_base_directory(), "conf")
  98. llm_factories = json.load(open(os.path.join(fnm, "llm_factories.json"), "r"))
  99. for llm_factory in llm_factories["factory_llm_infos"]:
  100. for llm in llm_factory["llm"]:
  101. if llm_id == llm["llm_name"]:
  102. return llm["model_type"].strip(",")[-1]
  103. def kb_prompt(kbinfos, max_tokens):
  104. knowledges = [ck["content_with_weight"] for ck in kbinfos["chunks"]]
  105. used_token_count = 0
  106. chunks_num = 0
  107. for i, c in enumerate(knowledges):
  108. used_token_count += num_tokens_from_string(c)
  109. chunks_num += 1
  110. if max_tokens * 0.97 < used_token_count:
  111. knowledges = knowledges[:i]
  112. break
  113. docs = DocumentService.get_by_ids([ck["doc_id"] for ck in kbinfos["chunks"][:chunks_num]])
  114. docs = {d.id: d.meta_fields for d in docs}
  115. doc2chunks = defaultdict(lambda: {"chunks": [], "meta": []})
  116. for ck in kbinfos["chunks"][:chunks_num]:
  117. doc2chunks[ck["docnm_kwd"]]["chunks"].append(ck["content_with_weight"])
  118. doc2chunks[ck["docnm_kwd"]]["meta"] = docs.get(ck["doc_id"], {})
  119. knowledges = []
  120. for nm, cks_meta in doc2chunks.items():
  121. txt = f"Document: {nm} \n"
  122. for k, v in cks_meta["meta"].items():
  123. txt += f"{k}: {v}\n"
  124. txt += "Relevant fragments as following:\n"
  125. for i, chunk in enumerate(cks_meta["chunks"], 1):
  126. txt += f"{i}. {chunk}\n"
  127. knowledges.append(txt)
  128. return knowledges
  129. def label_question(question, kbs):
  130. tags = None
  131. tag_kb_ids = []
  132. for kb in kbs:
  133. if kb.parser_config.get("tag_kb_ids"):
  134. tag_kb_ids.extend(kb.parser_config["tag_kb_ids"])
  135. if tag_kb_ids:
  136. all_tags = get_tags_from_cache(tag_kb_ids)
  137. if not all_tags:
  138. all_tags = settings.retrievaler.all_tags_in_portion(kb.tenant_id, tag_kb_ids)
  139. set_tags_to_cache(all_tags, tag_kb_ids)
  140. else:
  141. all_tags = json.loads(all_tags)
  142. tag_kbs = KnowledgebaseService.get_by_ids(tag_kb_ids)
  143. tags = settings.retrievaler.tag_query(question,
  144. list(set([kb.tenant_id for kb in tag_kbs])),
  145. tag_kb_ids,
  146. all_tags,
  147. kb.parser_config.get("topn_tags", 3)
  148. )
  149. return tags
  150. def chat(dialog, messages, stream=True, **kwargs):
  151. assert messages[-1]["role"] == "user", "The last content of this conversation is not from user."
  152. chat_start_ts = timer()
  153. if llm_id2llm_type(dialog.llm_id) == "image2text":
  154. llm_model_config = TenantLLMService.get_model_config(dialog.tenant_id, LLMType.IMAGE2TEXT, dialog.llm_id)
  155. else:
  156. llm_model_config = TenantLLMService.get_model_config(dialog.tenant_id, LLMType.CHAT, dialog.llm_id)
  157. max_tokens = llm_model_config.get("max_tokens", 8192)
  158. check_llm_ts = timer()
  159. kbs = KnowledgebaseService.get_by_ids(dialog.kb_ids)
  160. embedding_list = list(set([kb.embd_id for kb in kbs]))
  161. if len(embedding_list) != 1:
  162. yield {"answer": "**ERROR**: Knowledge bases use different embedding models.", "reference": []}
  163. return {"answer": "**ERROR**: Knowledge bases use different embedding models.", "reference": []}
  164. embedding_model_name = embedding_list[0]
  165. retriever = settings.retrievaler
  166. questions = [m["content"] for m in messages if m["role"] == "user"][-3:]
  167. attachments = kwargs["doc_ids"].split(",") if "doc_ids" in kwargs else None
  168. if "doc_ids" in messages[-1]:
  169. attachments = messages[-1]["doc_ids"]
  170. create_retriever_ts = timer()
  171. embd_mdl = LLMBundle(dialog.tenant_id, LLMType.EMBEDDING, embedding_model_name)
  172. if not embd_mdl:
  173. raise LookupError("Embedding model(%s) not found" % embedding_model_name)
  174. bind_embedding_ts = timer()
  175. if llm_id2llm_type(dialog.llm_id) == "image2text":
  176. chat_mdl = LLMBundle(dialog.tenant_id, LLMType.IMAGE2TEXT, dialog.llm_id)
  177. else:
  178. chat_mdl = LLMBundle(dialog.tenant_id, LLMType.CHAT, dialog.llm_id)
  179. bind_llm_ts = timer()
  180. prompt_config = dialog.prompt_config
  181. field_map = KnowledgebaseService.get_field_map(dialog.kb_ids)
  182. tts_mdl = None
  183. if prompt_config.get("tts"):
  184. tts_mdl = LLMBundle(dialog.tenant_id, LLMType.TTS)
  185. # try to use sql if field mapping is good to go
  186. if field_map:
  187. logging.debug("Use SQL to retrieval:{}".format(questions[-1]))
  188. ans = use_sql(questions[-1], field_map, dialog.tenant_id, chat_mdl, prompt_config.get("quote", True))
  189. if ans:
  190. yield ans
  191. return
  192. for p in prompt_config["parameters"]:
  193. if p["key"] == "knowledge":
  194. continue
  195. if p["key"] not in kwargs and not p["optional"]:
  196. raise KeyError("Miss parameter: " + p["key"])
  197. if p["key"] not in kwargs:
  198. prompt_config["system"] = prompt_config["system"].replace(
  199. "{%s}" % p["key"], " ")
  200. if len(questions) > 1 and prompt_config.get("refine_multiturn"):
  201. questions = [full_question(dialog.tenant_id, dialog.llm_id, messages)]
  202. else:
  203. questions = questions[-1:]
  204. refine_question_ts = timer()
  205. rerank_mdl = None
  206. if dialog.rerank_id:
  207. rerank_mdl = LLMBundle(dialog.tenant_id, LLMType.RERANK, dialog.rerank_id)
  208. bind_reranker_ts = timer()
  209. generate_keyword_ts = bind_reranker_ts
  210. thought = ""
  211. kbinfos = {"total": 0, "chunks": [], "doc_aggs": []}
  212. if "knowledge" not in [p["key"] for p in prompt_config["parameters"]]:
  213. knowledges = []
  214. else:
  215. if prompt_config.get("keyword", False):
  216. questions[-1] += keyword_extraction(chat_mdl, questions[-1])
  217. generate_keyword_ts = timer()
  218. tenant_ids = list(set([kb.tenant_id for kb in kbs]))
  219. knowledges = []
  220. if prompt_config.get("reasoning", False):
  221. for think in reasoning(kbinfos, " ".join(questions), chat_mdl, embd_mdl, tenant_ids, dialog.kb_ids, MAX_SEARCH_LIMIT=3):
  222. if isinstance(think, str):
  223. thought = think
  224. knowledges = [t for t in think.split("\n") if t]
  225. else:
  226. yield think
  227. else:
  228. kbinfos = retriever.retrieval(" ".join(questions), embd_mdl, tenant_ids, dialog.kb_ids, 1, dialog.top_n,
  229. dialog.similarity_threshold,
  230. dialog.vector_similarity_weight,
  231. doc_ids=attachments,
  232. top=dialog.top_k, aggs=False, rerank_mdl=rerank_mdl,
  233. rank_feature=label_question(" ".join(questions), kbs)
  234. )
  235. if prompt_config.get("use_kg"):
  236. ck = settings.kg_retrievaler.retrieval(" ".join(questions),
  237. tenant_ids,
  238. dialog.kb_ids,
  239. embd_mdl,
  240. LLMBundle(dialog.tenant_id, LLMType.CHAT))
  241. if ck["content_with_weight"]:
  242. kbinfos["chunks"].insert(0, ck)
  243. knowledges = kb_prompt(kbinfos, max_tokens)
  244. logging.debug(
  245. "{}->{}".format(" ".join(questions), "\n->".join(knowledges)))
  246. retrieval_ts = timer()
  247. if not knowledges and prompt_config.get("empty_response"):
  248. empty_res = prompt_config["empty_response"]
  249. yield {"answer": empty_res, "reference": kbinfos, "audio_binary": tts(tts_mdl, empty_res)}
  250. return {"answer": prompt_config["empty_response"], "reference": kbinfos}
  251. kwargs["knowledge"] = "\n------\n" + "\n\n------\n\n".join(knowledges)
  252. gen_conf = dialog.llm_setting
  253. msg = [{"role": "system", "content": prompt_config["system"].format(**kwargs)}]
  254. msg.extend([{"role": m["role"], "content": re.sub(r"##\d+\$\$", "", m["content"])}
  255. for m in messages if m["role"] != "system"])
  256. used_token_count, msg = message_fit_in(msg, int(max_tokens * 0.97))
  257. assert len(msg) >= 2, f"message_fit_in has bug: {msg}"
  258. prompt = msg[0]["content"]
  259. prompt += "\n\n### Query:\n%s" % " ".join(questions)
  260. if "max_tokens" in gen_conf:
  261. gen_conf["max_tokens"] = min(
  262. gen_conf["max_tokens"],
  263. max_tokens - used_token_count)
  264. def decorate_answer(answer):
  265. nonlocal prompt_config, knowledges, kwargs, kbinfos, prompt, retrieval_ts
  266. refs = []
  267. ans = answer.split("</think>")
  268. think = ""
  269. if len(ans) == 2:
  270. think = ans[0] + "</think>"
  271. answer = ans[1]
  272. if knowledges and (prompt_config.get("quote", True) and kwargs.get("quote", True)):
  273. answer, idx = retriever.insert_citations(answer,
  274. [ck["content_ltks"]
  275. for ck in kbinfos["chunks"]],
  276. [ck["vector"]
  277. for ck in kbinfos["chunks"]],
  278. embd_mdl,
  279. tkweight=1 - dialog.vector_similarity_weight,
  280. vtweight=dialog.vector_similarity_weight)
  281. idx = set([kbinfos["chunks"][int(i)]["doc_id"] for i in idx])
  282. recall_docs = [
  283. d for d in kbinfos["doc_aggs"] if d["doc_id"] in idx]
  284. if not recall_docs:
  285. recall_docs = kbinfos["doc_aggs"]
  286. kbinfos["doc_aggs"] = recall_docs
  287. refs = deepcopy(kbinfos)
  288. for c in refs["chunks"]:
  289. if c.get("vector"):
  290. del c["vector"]
  291. if answer.lower().find("invalid key") >= 0 or answer.lower().find("invalid api") >= 0:
  292. answer += " Please set LLM API-Key in 'User Setting -> Model providers -> API-Key'"
  293. finish_chat_ts = timer()
  294. total_time_cost = (finish_chat_ts - chat_start_ts) * 1000
  295. check_llm_time_cost = (check_llm_ts - chat_start_ts) * 1000
  296. create_retriever_time_cost = (create_retriever_ts - check_llm_ts) * 1000
  297. bind_embedding_time_cost = (bind_embedding_ts - create_retriever_ts) * 1000
  298. bind_llm_time_cost = (bind_llm_ts - bind_embedding_ts) * 1000
  299. refine_question_time_cost = (refine_question_ts - bind_llm_ts) * 1000
  300. bind_reranker_time_cost = (bind_reranker_ts - refine_question_ts) * 1000
  301. generate_keyword_time_cost = (generate_keyword_ts - bind_reranker_ts) * 1000
  302. retrieval_time_cost = (retrieval_ts - generate_keyword_ts) * 1000
  303. generate_result_time_cost = (finish_chat_ts - retrieval_ts) * 1000
  304. 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"
  305. return {"answer": think+answer, "reference": refs, "prompt": re.sub(r"\n", " \n", prompt), "created_at": time.time()}
  306. if stream:
  307. last_ans = ""
  308. answer = ""
  309. for ans in chat_mdl.chat_streamly(prompt, msg[1:], gen_conf):
  310. if thought:
  311. ans = re.sub(r"<think>.*</think>", "", ans, flags=re.DOTALL)
  312. answer = ans
  313. delta_ans = ans[len(last_ans):]
  314. if num_tokens_from_string(delta_ans) < 16:
  315. continue
  316. last_ans = answer
  317. yield {"answer": thought+answer, "reference": {}, "audio_binary": tts(tts_mdl, delta_ans)}
  318. delta_ans = answer[len(last_ans):]
  319. if delta_ans:
  320. yield {"answer": thought+answer, "reference": {}, "audio_binary": tts(tts_mdl, delta_ans)}
  321. yield decorate_answer(thought+answer)
  322. else:
  323. answer = chat_mdl.chat(prompt, msg[1:], gen_conf)
  324. user_content = msg[-1].get("content", "[content not available]")
  325. logging.debug("User: {}|Assistant: {}".format(user_content, answer))
  326. res = decorate_answer(answer)
  327. res["audio_binary"] = tts(tts_mdl, answer)
  328. yield res
  329. def use_sql(question, field_map, tenant_id, chat_mdl, quota=True):
  330. 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."
  331. user_prompt = """
  332. Table name: {};
  333. Table of database fields are as follows:
  334. {}
  335. Question are as follows:
  336. {}
  337. Please write the SQL, only SQL, without any other explanations or text.
  338. """.format(
  339. index_name(tenant_id),
  340. "\n".join([f"{k}: {v}" for k, v in field_map.items()]),
  341. question
  342. )
  343. tried_times = 0
  344. def get_table():
  345. nonlocal sys_prompt, user_prompt, question, tried_times
  346. sql = chat_mdl.chat(sys_prompt, [{"role": "user", "content": user_prompt}], {
  347. "temperature": 0.06})
  348. logging.debug(f"{question} ==> {user_prompt} get SQL: {sql}")
  349. sql = re.sub(r"[\r\n]+", " ", sql.lower())
  350. sql = re.sub(r".*select ", "select ", sql.lower())
  351. sql = re.sub(r" +", " ", sql)
  352. sql = re.sub(r"([;;]|```).*", "", sql)
  353. if sql[:len("select ")] != "select ":
  354. return None, None
  355. if not re.search(r"((sum|avg|max|min)\(|group by )", sql.lower()):
  356. if sql[:len("select *")] != "select *":
  357. sql = "select doc_id,docnm_kwd," + sql[6:]
  358. else:
  359. flds = []
  360. for k in field_map.keys():
  361. if k in forbidden_select_fields4resume:
  362. continue
  363. if len(flds) > 11:
  364. break
  365. flds.append(k)
  366. sql = "select doc_id,docnm_kwd," + ",".join(flds) + sql[8:]
  367. logging.debug(f"{question} get SQL(refined): {sql}")
  368. tried_times += 1
  369. return settings.retrievaler.sql_retrieval(sql, format="json"), sql
  370. tbl, sql = get_table()
  371. if tbl is None:
  372. return None
  373. if tbl.get("error") and tried_times <= 2:
  374. user_prompt = """
  375. Table name: {};
  376. Table of database fields are as follows:
  377. {}
  378. Question are as follows:
  379. {}
  380. Please write the SQL, only SQL, without any other explanations or text.
  381. The SQL error you provided last time is as follows:
  382. {}
  383. Error issued by database as follows:
  384. {}
  385. Please correct the error and write SQL again, only SQL, without any other explanations or text.
  386. """.format(
  387. index_name(tenant_id),
  388. "\n".join([f"{k}: {v}" for k, v in field_map.items()]),
  389. question, sql, tbl["error"]
  390. )
  391. tbl, sql = get_table()
  392. logging.debug("TRY it again: {}".format(sql))
  393. logging.debug("GET table: {}".format(tbl))
  394. if tbl.get("error") or len(tbl["rows"]) == 0:
  395. return None
  396. docid_idx = set([ii for ii, c in enumerate(
  397. tbl["columns"]) if c["name"] == "doc_id"])
  398. doc_name_idx = set([ii for ii, c in enumerate(
  399. tbl["columns"]) if c["name"] == "docnm_kwd"])
  400. column_idx = [ii for ii in range(
  401. len(tbl["columns"])) if ii not in (docid_idx | doc_name_idx)]
  402. # compose Markdown table
  403. columns = "|" + "|".join([re.sub(r"(/.*|([^()]+))", "", field_map.get(tbl["columns"][i]["name"],
  404. tbl["columns"][i]["name"])) for i in
  405. column_idx]) + ("|Source|" if docid_idx and docid_idx else "|")
  406. line = "|" + "|".join(["------" for _ in range(len(column_idx))]) + \
  407. ("|------|" if docid_idx and docid_idx else "")
  408. rows = ["|" +
  409. "|".join([rmSpace(str(r[i])) for i in column_idx]).replace("None", " ") +
  410. "|" for r in tbl["rows"]]
  411. rows = [r for r in rows if re.sub(r"[ |]+", "", r)]
  412. if quota:
  413. rows = "\n".join([r + f" ##{ii}$$ |" for ii, r in enumerate(rows)])
  414. else:
  415. rows = "\n".join([r + f" ##{ii}$$ |" for ii, r in enumerate(rows)])
  416. rows = re.sub(r"T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+Z)?\|", "|", rows)
  417. if not docid_idx or not doc_name_idx:
  418. logging.warning("SQL missing field: " + sql)
  419. return {
  420. "answer": "\n".join([columns, line, rows]),
  421. "reference": {"chunks": [], "doc_aggs": []},
  422. "prompt": sys_prompt
  423. }
  424. docid_idx = list(docid_idx)[0]
  425. doc_name_idx = list(doc_name_idx)[0]
  426. doc_aggs = {}
  427. for r in tbl["rows"]:
  428. if r[docid_idx] not in doc_aggs:
  429. doc_aggs[r[docid_idx]] = {"doc_name": r[doc_name_idx], "count": 0}
  430. doc_aggs[r[docid_idx]]["count"] += 1
  431. return {
  432. "answer": "\n".join([columns, line, rows]),
  433. "reference": {"chunks": [{"doc_id": r[docid_idx], "docnm_kwd": r[doc_name_idx]} for r in tbl["rows"]],
  434. "doc_aggs": [{"doc_id": did, "doc_name": d["doc_name"], "count": d["count"]} for did, d in
  435. doc_aggs.items()]},
  436. "prompt": sys_prompt
  437. }
  438. def relevant(tenant_id, llm_id, question, contents: list):
  439. if llm_id2llm_type(llm_id) == "image2text":
  440. chat_mdl = LLMBundle(tenant_id, LLMType.IMAGE2TEXT, llm_id)
  441. else:
  442. chat_mdl = LLMBundle(tenant_id, LLMType.CHAT, llm_id)
  443. prompt = """
  444. You are a grader assessing relevance of a retrieved document to a user question.
  445. It does not need to be a stringent test. The goal is to filter out erroneous retrievals.
  446. If the document contains keyword(s) or semantic meaning related to the user question, grade it as relevant.
  447. Give a binary score 'yes' or 'no' score to indicate whether the document is relevant to the question.
  448. No other words needed except 'yes' or 'no'.
  449. """
  450. if not contents:
  451. return False
  452. contents = "Documents: \n" + " - ".join(contents)
  453. contents = f"Question: {question}\n" + contents
  454. if num_tokens_from_string(contents) >= chat_mdl.max_length - 4:
  455. contents = encoder.decode(encoder.encode(contents)[:chat_mdl.max_length - 4])
  456. ans = chat_mdl.chat(prompt, [{"role": "user", "content": contents}], {"temperature": 0.01})
  457. if ans.lower().find("yes") >= 0:
  458. return True
  459. return False
  460. def rewrite(tenant_id, llm_id, question):
  461. if llm_id2llm_type(llm_id) == "image2text":
  462. chat_mdl = LLMBundle(tenant_id, LLMType.IMAGE2TEXT, llm_id)
  463. else:
  464. chat_mdl = LLMBundle(tenant_id, LLMType.CHAT, llm_id)
  465. prompt = """
  466. You are an expert at query expansion to generate a paraphrasing of a question.
  467. I can't retrieval relevant information from the knowledge base by using user's question directly.
  468. You need to expand or paraphrase user's question by multiple ways such as using synonyms words/phrase,
  469. writing the abbreviation in its entirety, adding some extra descriptions or explanations,
  470. changing the way of expression, translating the original question into another language (English/Chinese), etc.
  471. And return 5 versions of question and one is from translation.
  472. Just list the question. No other words are needed.
  473. """
  474. ans = chat_mdl.chat(prompt, [{"role": "user", "content": question}], {"temperature": 0.8})
  475. return ans
  476. def keyword_extraction(chat_mdl, content, topn=3):
  477. prompt = f"""
  478. Role: You're a text analyzer.
  479. Task: extract the most important keywords/phrases of a given piece of text content.
  480. Requirements:
  481. - Summarize the text content, and give top {topn} important keywords/phrases.
  482. - The keywords MUST be in language of the given piece of text content.
  483. - The keywords are delimited by ENGLISH COMMA.
  484. - Keywords ONLY in output.
  485. ### Text Content
  486. {content}
  487. """
  488. msg = [
  489. {"role": "system", "content": prompt},
  490. {"role": "user", "content": "Output: "}
  491. ]
  492. _, msg = message_fit_in(msg, chat_mdl.max_length)
  493. kwd = chat_mdl.chat(prompt, msg[1:], {"temperature": 0.2})
  494. if isinstance(kwd, tuple):
  495. kwd = kwd[0]
  496. kwd = re.sub(r"<think>.*</think>", "", kwd, flags=re.DOTALL)
  497. if kwd.find("**ERROR**") >= 0:
  498. return ""
  499. return kwd
  500. def question_proposal(chat_mdl, content, topn=3):
  501. prompt = f"""
  502. Role: You're a text analyzer.
  503. Task: propose {topn} questions about a given piece of text content.
  504. Requirements:
  505. - Understand and summarize the text content, and propose top {topn} important questions.
  506. - The questions SHOULD NOT have overlapping meanings.
  507. - The questions SHOULD cover the main content of the text as much as possible.
  508. - The questions MUST be in language of the given piece of text content.
  509. - One question per line.
  510. - Question ONLY in output.
  511. ### Text Content
  512. {content}
  513. """
  514. msg = [
  515. {"role": "system", "content": prompt},
  516. {"role": "user", "content": "Output: "}
  517. ]
  518. _, msg = message_fit_in(msg, chat_mdl.max_length)
  519. kwd = chat_mdl.chat(prompt, msg[1:], {"temperature": 0.2})
  520. if isinstance(kwd, tuple):
  521. kwd = kwd[0]
  522. kwd = re.sub(r"<think>.*</think>", "", kwd, flags=re.DOTALL)
  523. if kwd.find("**ERROR**") >= 0:
  524. return ""
  525. return kwd
  526. def full_question(tenant_id, llm_id, messages):
  527. if llm_id2llm_type(llm_id) == "image2text":
  528. chat_mdl = LLMBundle(tenant_id, LLMType.IMAGE2TEXT, llm_id)
  529. else:
  530. chat_mdl = LLMBundle(tenant_id, LLMType.CHAT, llm_id)
  531. conv = []
  532. for m in messages:
  533. if m["role"] not in ["user", "assistant"]:
  534. continue
  535. conv.append("{}: {}".format(m["role"].upper(), m["content"]))
  536. conv = "\n".join(conv)
  537. today = datetime.date.today().isoformat()
  538. yesterday = (datetime.date.today() - timedelta(days=1)).isoformat()
  539. tomorrow = (datetime.date.today() + timedelta(days=1)).isoformat()
  540. prompt = f"""
  541. Role: A helpful assistant
  542. Task and steps:
  543. 1. Generate a full user question that would follow the conversation.
  544. 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}.
  545. Requirements & Restrictions:
  546. - Text generated MUST be in the same language of the original user's question.
  547. - If the user's latest question is completely, don't do anything, just return the original question.
  548. - DON'T generate anything except a refined question.
  549. ######################
  550. -Examples-
  551. ######################
  552. # Example 1
  553. ## Conversation
  554. USER: What is the name of Donald Trump's father?
  555. ASSISTANT: Fred Trump.
  556. USER: And his mother?
  557. ###############
  558. Output: What's the name of Donald Trump's mother?
  559. ------------
  560. # Example 2
  561. ## Conversation
  562. USER: What is the name of Donald Trump's father?
  563. ASSISTANT: Fred Trump.
  564. USER: And his mother?
  565. ASSISTANT: Mary Trump.
  566. User: What's her full name?
  567. ###############
  568. Output: What's the full name of Donald Trump's mother Mary Trump?
  569. ------------
  570. # Example 3
  571. ## Conversation
  572. USER: What's the weather today in London?
  573. ASSISTANT: Cloudy.
  574. USER: What's about tomorrow in Rochester?
  575. ###############
  576. Output: What's the weather in Rochester on {tomorrow}?
  577. ######################
  578. # Real Data
  579. ## Conversation
  580. {conv}
  581. ###############
  582. """
  583. ans = chat_mdl.chat(prompt, [{"role": "user", "content": "Output: "}], {"temperature": 0.2})
  584. ans = re.sub(r"<think>.*</think>", "", ans, flags=re.DOTALL)
  585. return ans if ans.find("**ERROR**") < 0 else messages[-1]["content"]
  586. def tts(tts_mdl, text):
  587. if not tts_mdl or not text:
  588. return
  589. bin = b""
  590. for chunk in tts_mdl.tts(text):
  591. bin += chunk
  592. return binascii.hexlify(bin).decode("utf-8")
  593. def ask(question, kb_ids, tenant_id):
  594. kbs = KnowledgebaseService.get_by_ids(kb_ids)
  595. embedding_list = list(set([kb.embd_id for kb in kbs]))
  596. is_knowledge_graph = all([kb.parser_id == ParserType.KG for kb in kbs])
  597. retriever = settings.retrievaler if not is_knowledge_graph else settings.kg_retrievaler
  598. embd_mdl = LLMBundle(tenant_id, LLMType.EMBEDDING, embedding_list[0])
  599. chat_mdl = LLMBundle(tenant_id, LLMType.CHAT)
  600. max_tokens = chat_mdl.max_length
  601. tenant_ids = list(set([kb.tenant_id for kb in kbs]))
  602. kbinfos = retriever.retrieval(question, embd_mdl, tenant_ids, kb_ids,
  603. 1, 12, 0.1, 0.3, aggs=False,
  604. rank_feature=label_question(question, kbs)
  605. )
  606. knowledges = kb_prompt(kbinfos, max_tokens)
  607. prompt = """
  608. Role: You're a smart assistant. Your name is Miss R.
  609. Task: Summarize the information from knowledge bases and answer user's question.
  610. Requirements and restriction:
  611. - DO NOT make things up, especially for numbers.
  612. - If the information from knowledge is irrelevant with user's question, JUST SAY: Sorry, no relevant information provided.
  613. - Answer with markdown format text.
  614. - Answer in language of user's question.
  615. - DO NOT make things up, especially for numbers.
  616. ### Information from knowledge bases
  617. %s
  618. The above is information from knowledge bases.
  619. """ % "\n".join(knowledges)
  620. msg = [{"role": "user", "content": question}]
  621. def decorate_answer(answer):
  622. nonlocal knowledges, kbinfos, prompt
  623. answer, idx = retriever.insert_citations(answer,
  624. [ck["content_ltks"]
  625. for ck in kbinfos["chunks"]],
  626. [ck["vector"]
  627. for ck in kbinfos["chunks"]],
  628. embd_mdl,
  629. tkweight=0.7,
  630. vtweight=0.3)
  631. idx = set([kbinfos["chunks"][int(i)]["doc_id"] for i in idx])
  632. recall_docs = [
  633. d for d in kbinfos["doc_aggs"] if d["doc_id"] in idx]
  634. if not recall_docs:
  635. recall_docs = kbinfos["doc_aggs"]
  636. kbinfos["doc_aggs"] = recall_docs
  637. refs = deepcopy(kbinfos)
  638. for c in refs["chunks"]:
  639. if c.get("vector"):
  640. del c["vector"]
  641. if answer.lower().find("invalid key") >= 0 or answer.lower().find("invalid api") >= 0:
  642. answer += " Please set LLM API-Key in 'User Setting -> Model Providers -> API-Key'"
  643. return {"answer": answer, "reference": refs}
  644. answer = ""
  645. for ans in chat_mdl.chat_streamly(prompt, msg, {"temperature": 0.1}):
  646. answer = ans
  647. yield {"answer": answer, "reference": {}}
  648. yield decorate_answer(answer)
  649. def content_tagging(chat_mdl, content, all_tags, examples, topn=3):
  650. prompt = f"""
  651. Role: You're a text analyzer.
  652. Task: Tag (put on some labels) to a given piece of text content based on the examples and the entire tag set.
  653. Steps::
  654. - Comprehend the tag/label set.
  655. - Comprehend examples which all consist of both text content and assigned tags with relevance score in format of JSON.
  656. - Summarize the text content, and tag it with top {topn} most relevant tags from the set of tag/label and the corresponding relevance score.
  657. Requirements
  658. - The tags MUST be from the tag set.
  659. - The output MUST be in JSON format only, the key is tag and the value is its relevance score.
  660. - The relevance score must be range from 1 to 10.
  661. - Keywords ONLY in output.
  662. # TAG SET
  663. {", ".join(all_tags)}
  664. """
  665. for i, ex in enumerate(examples):
  666. prompt += """
  667. # Examples {}
  668. ### Text Content
  669. {}
  670. Output:
  671. {}
  672. """.format(i, ex["content"], json.dumps(ex[TAG_FLD], indent=2, ensure_ascii=False))
  673. prompt += f"""
  674. # Real Data
  675. ### Text Content
  676. {content}
  677. """
  678. msg = [
  679. {"role": "system", "content": prompt},
  680. {"role": "user", "content": "Output: "}
  681. ]
  682. _, msg = message_fit_in(msg, chat_mdl.max_length)
  683. kwd = chat_mdl.chat(prompt, msg[1:], {"temperature": 0.5})
  684. if isinstance(kwd, tuple):
  685. kwd = kwd[0]
  686. kwd = re.sub(r"<think>.*</think>", "", kwd, flags=re.DOTALL)
  687. if kwd.find("**ERROR**") >= 0:
  688. raise Exception(kwd)
  689. try:
  690. return json_repair.loads(kwd)
  691. except json_repair.JSONDecodeError:
  692. try:
  693. result = kwd.replace(prompt[:-1], '').replace('user', '').replace('model', '').strip()
  694. result = '{' + result.split('{')[1].split('}')[0] + '}'
  695. return json_repair.loads(result)
  696. except Exception as e:
  697. logging.exception(f"JSON parsing error: {result} -> {e}")
  698. raise e
  699. def reasoning(chunk_info: dict, question: str, chat_mdl: LLMBundle, embd_mdl: LLMBundle,
  700. tenant_ids: list[str], kb_ids: list[str], MAX_SEARCH_LIMIT: int = 3,
  701. top_n: int = 5, similarity_threshold: float = 0.4, vector_similarity_weight: float = 0.3):
  702. BEGIN_SEARCH_QUERY = "<|begin_search_query|>"
  703. END_SEARCH_QUERY = "<|end_search_query|>"
  704. BEGIN_SEARCH_RESULT = "<|begin_search_result|>"
  705. END_SEARCH_RESULT = "<|end_search_result|>"
  706. def rm_query_tags(line):
  707. pattern = re.escape(BEGIN_SEARCH_QUERY) + r"(.*?)" + re.escape(END_SEARCH_QUERY)
  708. return re.sub(pattern, "", line)
  709. def rm_result_tags(line):
  710. pattern = re.escape(BEGIN_SEARCH_RESULT) + r"(.*?)" + re.escape(END_SEARCH_RESULT)
  711. return re.sub(pattern, "", line)
  712. reason_prompt = (
  713. "You are a reasoning assistant with the ability to perform dataset searches to help "
  714. "you answer the user's question accurately. You have special tools:\n\n"
  715. f"- To perform a search: write {BEGIN_SEARCH_QUERY} your query here {END_SEARCH_QUERY}.\n"
  716. f"Then, the system will search and analyze relevant content, then provide you with helpful information in the format {BEGIN_SEARCH_RESULT} ...search results... {END_SEARCH_RESULT}.\n\n"
  717. f"You can repeat the search process multiple times if necessary. The maximum number of search attempts is limited to {MAX_SEARCH_LIMIT}.\n\n"
  718. "Once you have all the information you need, continue your reasoning.\n\n"
  719. "-- Example --\n"
  720. "Question: \"Find the minimum number of vertices in a Steiner tree that includes all specified vertices in a given tree.\"\n"
  721. "Assistant thinking steps:\n"
  722. "- I need to understand what a Steiner tree is and how to compute the minimum number of vertices required to include all specified vertices in a given tree.\n\n"
  723. "Assistant:\n"
  724. f"{BEGIN_SEARCH_QUERY}Minimum Steiner Tree problem in trees{END_SEARCH_QUERY}\n\n"
  725. "(System returns processed information from relevant web pages)\n\n"
  726. "Assistant continues reasoning with the new information...\n\n"
  727. "**Remember**:\n"
  728. f"- You have a dataset to search, so you just provide a proper search query.\n"
  729. f"- Use {BEGIN_SEARCH_QUERY} to request a dataset search and end with {END_SEARCH_QUERY}.\n"
  730. "- The language of query MUST be as the same as 'Question' or 'search result'.\n"
  731. "- When done searching, continue your reasoning.\n\n"
  732. 'Please answer the following question. You should think step by step to solve it.\n\n'
  733. )
  734. relevant_extraction_prompt = """**Task Instruction:**
  735. You are tasked with reading and analyzing web pages based on the following inputs: **Previous Reasoning Steps**, **Current Search Query**, and **Searched Web Pages**. Your objective is to extract relevant and helpful information for **Current Search Query** from the **Searched Web Pages** and seamlessly integrate this information into the **Previous Reasoning Steps** to continue reasoning for the original question.
  736. **Guidelines:**
  737. 1. **Analyze the Searched Web Pages:**
  738. - Carefully review the content of each searched web page.
  739. - Identify factual information that is relevant to the **Current Search Query** and can aid in the reasoning process for the original question.
  740. 2. **Extract Relevant Information:**
  741. - Select the information from the Searched Web Pages that directly contributes to advancing the **Previous Reasoning Steps**.
  742. - Ensure that the extracted information is accurate and relevant.
  743. 3. **Output Format:**
  744. - **If the web pages provide helpful information for current search query:** Present the information beginning with `**Final Information**` as shown below.
  745. - The language of query **MUST BE** as the same as 'Search Query' or 'Web Pages'.\n"
  746. **Final Information**
  747. [Helpful information]
  748. - **If the web pages do not provide any helpful information for current search query:** Output the following text.
  749. **Final Information**
  750. No helpful information found.
  751. **Inputs:**
  752. - **Previous Reasoning Steps:**
  753. {prev_reasoning}
  754. - **Current Search Query:**
  755. {search_query}
  756. - **Searched Web Pages:**
  757. {document}
  758. """
  759. executed_search_queries = []
  760. msg_hisotry = [{"role": "user", "content": f'Question:\n{question}\n\n'}]
  761. all_reasoning_steps = []
  762. think = "<think>"
  763. for ii in range(MAX_SEARCH_LIMIT + 1):
  764. if ii == MAX_SEARCH_LIMIT - 1:
  765. summary_think = f"\n{BEGIN_SEARCH_RESULT}\nThe maximum search limit is exceeded. You are not allowed to search.\n{END_SEARCH_RESULT}\n"
  766. yield {"answer": think + summary_think + "</think>", "reference": {}, "audio_binary": None}
  767. all_reasoning_steps.append(summary_think)
  768. msg_hisotry.append({"role": "assistant", "content": summary_think})
  769. break
  770. query_think = ""
  771. if msg_hisotry[-1]["role"] != "user":
  772. msg_hisotry.append({"role": "user", "content": "Continues reasoning with the new information...\n"})
  773. for ans in chat_mdl.chat_streamly(reason_prompt, msg_hisotry, {"temperature": 0.7}):
  774. ans = re.sub(r"<think>.*</think>", "", ans, flags=re.DOTALL)
  775. if not ans:
  776. continue
  777. query_think = ans
  778. yield {"answer": think + rm_query_tags(query_think) + "</think>", "reference": {}, "audio_binary": None}
  779. think += rm_query_tags(query_think)
  780. all_reasoning_steps.append(query_think)
  781. msg_hisotry.append({"role": "assistant", "content": query_think})
  782. search_query = extract_between(query_think, BEGIN_SEARCH_QUERY, END_SEARCH_QUERY)
  783. if not search_query:
  784. if ii > 0:
  785. break
  786. search_query = question
  787. txt = f"\n{BEGIN_SEARCH_QUERY}{question}{END_SEARCH_QUERY}\n\n"
  788. think += txt
  789. msg_hisotry[-1]["content"] += txt
  790. logging.info(f"[THINK]Query: {ii}. {search_query}")
  791. think += f"\n\n> {ii+1}. {search_query}\n\n"
  792. yield {"answer": think + "</think>", "reference": {}, "audio_binary": None}
  793. summary_think = ""
  794. # The search query has been searched in previous steps.
  795. if search_query in executed_search_queries:
  796. summary_think = f"\n{BEGIN_SEARCH_RESULT}\nYou have searched this query. Please refer to previous results.\n{END_SEARCH_RESULT}\n"
  797. yield {"answer": think + summary_think + "</think>", "reference": {}, "audio_binary": None}
  798. all_reasoning_steps.append(summary_think)
  799. msg_hisotry.append({"role": "assistant", "content": summary_think})
  800. think += summary_think
  801. continue
  802. truncated_prev_reasoning = ""
  803. for i, step in enumerate(all_reasoning_steps):
  804. truncated_prev_reasoning += f"Step {i + 1}: {step}\n\n"
  805. prev_steps = truncated_prev_reasoning.split('\n\n')
  806. if len(prev_steps) <= 5:
  807. truncated_prev_reasoning = '\n\n'.join(prev_steps)
  808. else:
  809. truncated_prev_reasoning = ''
  810. for i, step in enumerate(prev_steps):
  811. if i == 0 or i >= len(prev_steps) - 4 or BEGIN_SEARCH_QUERY in step or BEGIN_SEARCH_RESULT in step:
  812. truncated_prev_reasoning += step + '\n\n'
  813. else:
  814. if truncated_prev_reasoning[-len('\n\n...\n\n'):] != '\n\n...\n\n':
  815. truncated_prev_reasoning += '...\n\n'
  816. truncated_prev_reasoning = truncated_prev_reasoning.strip('\n')
  817. kbinfos = settings.retrievaler.retrieval(search_query, embd_mdl, tenant_ids, kb_ids, 1, top_n,
  818. similarity_threshold,
  819. vector_similarity_weight
  820. )
  821. # Merge chunk info for citations
  822. if not chunk_info["chunks"]:
  823. for k in chunk_info.keys():
  824. chunk_info[k] = kbinfos[k]
  825. else:
  826. cids = [c["chunk_id"] for c in chunk_info["chunks"]]
  827. for c in kbinfos["chunks"]:
  828. if c["chunk_id"] in cids:
  829. continue
  830. chunk_info["chunks"].append(c)
  831. dids = [d["doc_id"] for d in chunk_info["doc_aggs"]]
  832. for d in kbinfos["doc_aggs"]:
  833. if d["doc_id"] in dids:
  834. continue
  835. chunk_info["doc_aggs"].append(d)
  836. think += "\n\n"
  837. for ans in chat_mdl.chat_streamly(
  838. relevant_extraction_prompt.format(
  839. prev_reasoning=truncated_prev_reasoning,
  840. search_query=search_query,
  841. document="\n".join(kb_prompt(kbinfos, 512))
  842. ),
  843. [{"role": "user",
  844. "content": f'Now you should analyze each web page and find helpful information based on the current search query "{search_query}" and previous reasoning steps.'}],
  845. {"temperature": 0.7}):
  846. ans = re.sub(r"<think>.*</think>", "", ans, flags=re.DOTALL)
  847. if not ans:
  848. continue
  849. summary_think = ans
  850. yield {"answer": think + rm_result_tags(summary_think) + "</think>", "reference": {}, "audio_binary": None}
  851. all_reasoning_steps.append(summary_think)
  852. msg_hisotry.append(
  853. {"role": "assistant", "content": f"\n\n{BEGIN_SEARCH_RESULT}{summary_think}{END_SEARCH_RESULT}\n\n"})
  854. think += rm_result_tags(summary_think)
  855. logging.info(f"[THINK]Summary: {ii}. {summary_think}")
  856. yield think + "</think>"