Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

dialog_service.py 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  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 binascii
  17. import logging
  18. import re
  19. import time
  20. from copy import deepcopy
  21. from datetime import datetime
  22. from functools import partial
  23. from timeit import default_timer as timer
  24. from langfuse import Langfuse
  25. from peewee import fn
  26. from agentic_reasoning import DeepResearcher
  27. from api import settings
  28. from api.db import LLMType, ParserType, StatusEnum
  29. from api.db.db_models import DB, Dialog
  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.langfuse_service import TenantLangfuseService
  34. from api.db.services.llm_service import LLMBundle, TenantLLMService
  35. from api.utils import current_timestamp, datetime_format
  36. from rag.app.resume import forbidden_select_fields4resume
  37. from rag.app.tag import label_question
  38. from rag.nlp.search import index_name
  39. from rag.prompts import chunks_format, citation_prompt, cross_languages, full_question, kb_prompt, keyword_extraction, message_fit_in
  40. from rag.prompts.prompts import gen_meta_filter
  41. from rag.utils import num_tokens_from_string, rmSpace
  42. from rag.utils.tavily_conn import Tavily
  43. class DialogService(CommonService):
  44. model = Dialog
  45. @classmethod
  46. def save(cls, **kwargs):
  47. """Save a new record to database.
  48. This method creates a new record in the database with the provided field values,
  49. forcing an insert operation rather than an update.
  50. Args:
  51. **kwargs: Record field values as keyword arguments.
  52. Returns:
  53. Model instance: The created record object.
  54. """
  55. sample_obj = cls.model(**kwargs).save(force_insert=True)
  56. return sample_obj
  57. @classmethod
  58. def update_many_by_id(cls, data_list):
  59. """Update multiple records by their IDs.
  60. This method updates multiple records in the database, identified by their IDs.
  61. It automatically updates the update_time and update_date fields for each record.
  62. Args:
  63. data_list (list): List of dictionaries containing record data to update.
  64. Each dictionary must include an 'id' field.
  65. """
  66. with DB.atomic():
  67. for data in data_list:
  68. data["update_time"] = current_timestamp()
  69. data["update_date"] = datetime_format(datetime.now())
  70. cls.model.update(data).where(cls.model.id == data["id"]).execute()
  71. @classmethod
  72. @DB.connection_context()
  73. def get_list(cls, tenant_id, page_number, items_per_page, orderby, desc, id, name):
  74. chats = cls.model.select()
  75. if id:
  76. chats = chats.where(cls.model.id == id)
  77. if name:
  78. chats = chats.where(cls.model.name == name)
  79. chats = chats.where((cls.model.tenant_id == tenant_id) & (cls.model.status == StatusEnum.VALID.value))
  80. if desc:
  81. chats = chats.order_by(cls.model.getter_by(orderby).desc())
  82. else:
  83. chats = chats.order_by(cls.model.getter_by(orderby).asc())
  84. chats = chats.paginate(page_number, items_per_page)
  85. return list(chats.dicts())
  86. @classmethod
  87. @DB.connection_context()
  88. def get_by_tenant_ids(cls, joined_tenant_ids, user_id, page_number, items_per_page, orderby, desc, keywords, parser_id=None):
  89. from api.db.db_models import User
  90. fields = [
  91. cls.model.id,
  92. cls.model.tenant_id,
  93. cls.model.name,
  94. cls.model.description,
  95. cls.model.language,
  96. cls.model.llm_id,
  97. cls.model.llm_setting,
  98. cls.model.prompt_type,
  99. cls.model.prompt_config,
  100. cls.model.similarity_threshold,
  101. cls.model.vector_similarity_weight,
  102. cls.model.top_n,
  103. cls.model.top_k,
  104. cls.model.do_refer,
  105. cls.model.rerank_id,
  106. cls.model.kb_ids,
  107. cls.model.icon,
  108. cls.model.status,
  109. User.nickname,
  110. User.avatar.alias("tenant_avatar"),
  111. cls.model.update_time,
  112. cls.model.create_time,
  113. ]
  114. if keywords:
  115. dialogs = (
  116. cls.model.select(*fields)
  117. .join(User, on=(cls.model.tenant_id == User.id))
  118. .where(
  119. (cls.model.tenant_id.in_(joined_tenant_ids) | (cls.model.tenant_id == user_id)) & (cls.model.status == StatusEnum.VALID.value),
  120. (fn.LOWER(cls.model.name).contains(keywords.lower())),
  121. )
  122. )
  123. else:
  124. dialogs = (
  125. cls.model.select(*fields)
  126. .join(User, on=(cls.model.tenant_id == User.id))
  127. .where(
  128. (cls.model.tenant_id.in_(joined_tenant_ids) | (cls.model.tenant_id == user_id)) & (cls.model.status == StatusEnum.VALID.value),
  129. )
  130. )
  131. if parser_id:
  132. dialogs = dialogs.where(cls.model.parser_id == parser_id)
  133. if desc:
  134. dialogs = dialogs.order_by(cls.model.getter_by(orderby).desc())
  135. else:
  136. dialogs = dialogs.order_by(cls.model.getter_by(orderby).asc())
  137. count = dialogs.count()
  138. if page_number and items_per_page:
  139. dialogs = dialogs.paginate(page_number, items_per_page)
  140. return list(dialogs.dicts()), count
  141. def chat_solo(dialog, messages, stream=True):
  142. if TenantLLMService.llm_id2llm_type(dialog.llm_id) == "image2text":
  143. chat_mdl = LLMBundle(dialog.tenant_id, LLMType.IMAGE2TEXT, dialog.llm_id)
  144. else:
  145. chat_mdl = LLMBundle(dialog.tenant_id, LLMType.CHAT, dialog.llm_id)
  146. prompt_config = dialog.prompt_config
  147. tts_mdl = None
  148. if prompt_config.get("tts"):
  149. tts_mdl = LLMBundle(dialog.tenant_id, LLMType.TTS)
  150. msg = [{"role": m["role"], "content": re.sub(r"##\d+\$\$", "", m["content"])} for m in messages if m["role"] != "system"]
  151. if stream:
  152. last_ans = ""
  153. delta_ans = ""
  154. for ans in chat_mdl.chat_streamly(prompt_config.get("system", ""), msg, dialog.llm_setting):
  155. answer = ans
  156. delta_ans = ans[len(last_ans) :]
  157. if num_tokens_from_string(delta_ans) < 16:
  158. continue
  159. last_ans = answer
  160. yield {"answer": answer, "reference": {}, "audio_binary": tts(tts_mdl, delta_ans), "prompt": "", "created_at": time.time()}
  161. delta_ans = ""
  162. if delta_ans:
  163. yield {"answer": answer, "reference": {}, "audio_binary": tts(tts_mdl, delta_ans), "prompt": "", "created_at": time.time()}
  164. else:
  165. answer = chat_mdl.chat(prompt_config.get("system", ""), msg, dialog.llm_setting)
  166. user_content = msg[-1].get("content", "[content not available]")
  167. logging.debug("User: {}|Assistant: {}".format(user_content, answer))
  168. yield {"answer": answer, "reference": {}, "audio_binary": tts(tts_mdl, answer), "prompt": "", "created_at": time.time()}
  169. def get_models(dialog):
  170. embd_mdl, chat_mdl, rerank_mdl, tts_mdl = None, None, None, None
  171. kbs = KnowledgebaseService.get_by_ids(dialog.kb_ids)
  172. embedding_list = list(set([kb.embd_id for kb in kbs]))
  173. if len(embedding_list) > 1:
  174. raise Exception("**ERROR**: Knowledge bases use different embedding models.")
  175. if embedding_list:
  176. embd_mdl = LLMBundle(dialog.tenant_id, LLMType.EMBEDDING, embedding_list[0])
  177. if not embd_mdl:
  178. raise LookupError("Embedding model(%s) not found" % embedding_list[0])
  179. if TenantLLMService.llm_id2llm_type(dialog.llm_id) == "image2text":
  180. chat_mdl = LLMBundle(dialog.tenant_id, LLMType.IMAGE2TEXT, dialog.llm_id)
  181. else:
  182. chat_mdl = LLMBundle(dialog.tenant_id, LLMType.CHAT, dialog.llm_id)
  183. if dialog.rerank_id:
  184. rerank_mdl = LLMBundle(dialog.tenant_id, LLMType.RERANK, dialog.rerank_id)
  185. if dialog.prompt_config.get("tts"):
  186. tts_mdl = LLMBundle(dialog.tenant_id, LLMType.TTS)
  187. return kbs, embd_mdl, rerank_mdl, chat_mdl, tts_mdl
  188. BAD_CITATION_PATTERNS = [
  189. re.compile(r"\(\s*ID\s*[: ]*\s*(\d+)\s*\)"), # (ID: 12)
  190. re.compile(r"\[\s*ID\s*[: ]*\s*(\d+)\s*\]"), # [ID: 12]
  191. re.compile(r"【\s*ID\s*[: ]*\s*(\d+)\s*】"), # 【ID: 12】
  192. re.compile(r"ref\s*(\d+)", flags=re.IGNORECASE), # ref12、REF 12
  193. ]
  194. def repair_bad_citation_formats(answer: str, kbinfos: dict, idx: set):
  195. max_index = len(kbinfos["chunks"])
  196. def safe_add(i):
  197. if 0 <= i < max_index:
  198. idx.add(i)
  199. return True
  200. return False
  201. def find_and_replace(pattern, group_index=1, repl=lambda i: f"ID:{i}", flags=0):
  202. nonlocal answer
  203. def replacement(match):
  204. try:
  205. i = int(match.group(group_index))
  206. if safe_add(i):
  207. return f"[{repl(i)}]"
  208. except Exception:
  209. pass
  210. return match.group(0)
  211. answer = re.sub(pattern, replacement, answer, flags=flags)
  212. for pattern in BAD_CITATION_PATTERNS:
  213. find_and_replace(pattern)
  214. return answer, idx
  215. def meta_filter(metas: dict, filters: list[dict]):
  216. doc_ids = []
  217. def filter_out(v2docs, operator, value):
  218. nonlocal doc_ids
  219. for input,docids in v2docs.items():
  220. try:
  221. input = float(input)
  222. value = float(value)
  223. except Exception:
  224. input = str(input)
  225. value = str(value)
  226. for conds in [
  227. (operator == "contains", str(value).lower() in str(input).lower()),
  228. (operator == "not contains", str(value).lower() not in str(input).lower()),
  229. (operator == "start with", str(input).lower().startswith(str(value).lower())),
  230. (operator == "end with", str(input).lower().endswith(str(value).lower())),
  231. (operator == "empty", not input),
  232. (operator == "not empty", input),
  233. (operator == "=", input == value),
  234. (operator == "≠", input != value),
  235. (operator == ">", input > value),
  236. (operator == "<", input < value),
  237. (operator == "≥", input >= value),
  238. (operator == "≤", input <= value),
  239. ]:
  240. try:
  241. if all(conds):
  242. doc_ids.extend(docids)
  243. except Exception:
  244. pass
  245. for k, v2docs in metas.items():
  246. for f in filters:
  247. if k != f["key"]:
  248. continue
  249. filter_out(v2docs, f["op"], f["value"])
  250. return doc_ids
  251. def chat(dialog, messages, stream=True, **kwargs):
  252. assert messages[-1]["role"] == "user", "The last content of this conversation is not from user."
  253. if not dialog.kb_ids and not dialog.prompt_config.get("tavily_api_key"):
  254. for ans in chat_solo(dialog, messages, stream):
  255. yield ans
  256. return
  257. chat_start_ts = timer()
  258. if TenantLLMService.llm_id2llm_type(dialog.llm_id) == "image2text":
  259. llm_model_config = TenantLLMService.get_model_config(dialog.tenant_id, LLMType.IMAGE2TEXT, dialog.llm_id)
  260. else:
  261. llm_model_config = TenantLLMService.get_model_config(dialog.tenant_id, LLMType.CHAT, dialog.llm_id)
  262. max_tokens = llm_model_config.get("max_tokens", 8192)
  263. check_llm_ts = timer()
  264. langfuse_tracer = None
  265. trace_context = {}
  266. langfuse_keys = TenantLangfuseService.filter_by_tenant(tenant_id=dialog.tenant_id)
  267. if langfuse_keys:
  268. langfuse = Langfuse(public_key=langfuse_keys.public_key, secret_key=langfuse_keys.secret_key, host=langfuse_keys.host)
  269. if langfuse.auth_check():
  270. langfuse_tracer = langfuse
  271. trace_id = langfuse_tracer.create_trace_id()
  272. trace_context = {"trace_id": trace_id}
  273. check_langfuse_tracer_ts = timer()
  274. kbs, embd_mdl, rerank_mdl, chat_mdl, tts_mdl = get_models(dialog)
  275. toolcall_session, tools = kwargs.get("toolcall_session"), kwargs.get("tools")
  276. if toolcall_session and tools:
  277. chat_mdl.bind_tools(toolcall_session, tools)
  278. bind_models_ts = timer()
  279. retriever = settings.retrievaler
  280. questions = [m["content"] for m in messages if m["role"] == "user"][-3:]
  281. attachments = kwargs["doc_ids"].split(",") if "doc_ids" in kwargs else []
  282. if "doc_ids" in messages[-1]:
  283. attachments = messages[-1]["doc_ids"]
  284. prompt_config = dialog.prompt_config
  285. field_map = KnowledgebaseService.get_field_map(dialog.kb_ids)
  286. # try to use sql if field mapping is good to go
  287. if field_map:
  288. logging.debug("Use SQL to retrieval:{}".format(questions[-1]))
  289. ans = use_sql(questions[-1], field_map, dialog.tenant_id, chat_mdl, prompt_config.get("quote", True))
  290. if ans:
  291. yield ans
  292. return
  293. for p in prompt_config["parameters"]:
  294. if p["key"] == "knowledge":
  295. continue
  296. if p["key"] not in kwargs and not p["optional"]:
  297. raise KeyError("Miss parameter: " + p["key"])
  298. if p["key"] not in kwargs:
  299. prompt_config["system"] = prompt_config["system"].replace("{%s}" % p["key"], " ")
  300. if len(questions) > 1 and prompt_config.get("refine_multiturn"):
  301. questions = [full_question(dialog.tenant_id, dialog.llm_id, messages)]
  302. else:
  303. questions = questions[-1:]
  304. if prompt_config.get("cross_languages"):
  305. questions = [cross_languages(dialog.tenant_id, dialog.llm_id, questions[0], prompt_config["cross_languages"])]
  306. if dialog.meta_data_filter:
  307. metas = DocumentService.get_meta_by_kbs(dialog.kb_ids)
  308. if dialog.meta_data_filter.get("method") == "auto":
  309. filters = gen_meta_filter(chat_mdl, metas, questions[-1])
  310. attachments.extend(meta_filter(metas, filters))
  311. if not attachments:
  312. attachments = None
  313. elif dialog.meta_data_filter.get("method") == "manual":
  314. attachments.extend(meta_filter(metas, dialog.meta_data_filter["manual"]))
  315. if not attachments:
  316. attachments = None
  317. if prompt_config.get("keyword", False):
  318. questions[-1] += keyword_extraction(chat_mdl, questions[-1])
  319. refine_question_ts = timer()
  320. thought = ""
  321. kbinfos = {"total": 0, "chunks": [], "doc_aggs": []}
  322. knowledges = []
  323. if attachments is not None and "knowledge" in [p["key"] for p in prompt_config["parameters"]]:
  324. tenant_ids = list(set([kb.tenant_id for kb in kbs]))
  325. knowledges = []
  326. if prompt_config.get("reasoning", False):
  327. reasoner = DeepResearcher(
  328. chat_mdl,
  329. prompt_config,
  330. partial(retriever.retrieval, embd_mdl=embd_mdl, tenant_ids=tenant_ids, kb_ids=dialog.kb_ids, page=1, page_size=dialog.top_n, similarity_threshold=0.2, vector_similarity_weight=0.3, doc_ids=attachments),
  331. )
  332. for think in reasoner.thinking(kbinfos, " ".join(questions)):
  333. if isinstance(think, str):
  334. thought = think
  335. knowledges = [t for t in think.split("\n") if t]
  336. elif stream:
  337. yield think
  338. else:
  339. if embd_mdl:
  340. kbinfos = retriever.retrieval(
  341. " ".join(questions),
  342. embd_mdl,
  343. tenant_ids,
  344. dialog.kb_ids,
  345. 1,
  346. dialog.top_n,
  347. dialog.similarity_threshold,
  348. dialog.vector_similarity_weight,
  349. doc_ids=attachments,
  350. top=dialog.top_k,
  351. aggs=False,
  352. rerank_mdl=rerank_mdl,
  353. rank_feature=label_question(" ".join(questions), kbs),
  354. )
  355. if prompt_config.get("tavily_api_key"):
  356. tav = Tavily(prompt_config["tavily_api_key"])
  357. tav_res = tav.retrieve_chunks(" ".join(questions))
  358. kbinfos["chunks"].extend(tav_res["chunks"])
  359. kbinfos["doc_aggs"].extend(tav_res["doc_aggs"])
  360. if prompt_config.get("use_kg"):
  361. ck = settings.kg_retrievaler.retrieval(" ".join(questions), tenant_ids, dialog.kb_ids, embd_mdl, LLMBundle(dialog.tenant_id, LLMType.CHAT))
  362. if ck["content_with_weight"]:
  363. kbinfos["chunks"].insert(0, ck)
  364. knowledges = kb_prompt(kbinfos, max_tokens)
  365. logging.debug("{}->{}".format(" ".join(questions), "\n->".join(knowledges)))
  366. retrieval_ts = timer()
  367. if not knowledges and prompt_config.get("empty_response"):
  368. empty_res = prompt_config["empty_response"]
  369. yield {"answer": empty_res, "reference": kbinfos, "prompt": "\n\n### Query:\n%s" % " ".join(questions), "audio_binary": tts(tts_mdl, empty_res)}
  370. return {"answer": prompt_config["empty_response"], "reference": kbinfos}
  371. kwargs["knowledge"] = "\n------\n" + "\n\n------\n\n".join(knowledges)
  372. gen_conf = dialog.llm_setting
  373. msg = [{"role": "system", "content": prompt_config["system"].format(**kwargs)}]
  374. prompt4citation = ""
  375. if knowledges and (prompt_config.get("quote", True) and kwargs.get("quote", True)):
  376. prompt4citation = citation_prompt()
  377. msg.extend([{"role": m["role"], "content": re.sub(r"##\d+\$\$", "", m["content"])} for m in messages if m["role"] != "system"])
  378. used_token_count, msg = message_fit_in(msg, int(max_tokens * 0.95))
  379. assert len(msg) >= 2, f"message_fit_in has bug: {msg}"
  380. prompt = msg[0]["content"]
  381. if "max_tokens" in gen_conf:
  382. gen_conf["max_tokens"] = min(gen_conf["max_tokens"], max_tokens - used_token_count)
  383. def decorate_answer(answer):
  384. nonlocal embd_mdl, prompt_config, knowledges, kwargs, kbinfos, prompt, retrieval_ts, questions, langfuse_tracer
  385. refs = []
  386. ans = answer.split("</think>")
  387. think = ""
  388. if len(ans) == 2:
  389. think = ans[0] + "</think>"
  390. answer = ans[1]
  391. if knowledges and (prompt_config.get("quote", True) and kwargs.get("quote", True)):
  392. idx = set([])
  393. if embd_mdl and not re.search(r"\[ID:([0-9]+)\]", answer):
  394. answer, idx = retriever.insert_citations(
  395. answer,
  396. [ck["content_ltks"] for ck in kbinfos["chunks"]],
  397. [ck["vector"] for ck in kbinfos["chunks"]],
  398. embd_mdl,
  399. tkweight=1 - dialog.vector_similarity_weight,
  400. vtweight=dialog.vector_similarity_weight,
  401. )
  402. else:
  403. for match in re.finditer(r"\[ID:([0-9]+)\]", answer):
  404. i = int(match.group(1))
  405. if i < len(kbinfos["chunks"]):
  406. idx.add(i)
  407. answer, idx = repair_bad_citation_formats(answer, kbinfos, idx)
  408. idx = set([kbinfos["chunks"][int(i)]["doc_id"] for i in idx])
  409. recall_docs = [d for d in kbinfos["doc_aggs"] if d["doc_id"] in idx]
  410. if not recall_docs:
  411. recall_docs = kbinfos["doc_aggs"]
  412. kbinfos["doc_aggs"] = recall_docs
  413. refs = deepcopy(kbinfos)
  414. for c in refs["chunks"]:
  415. if c.get("vector"):
  416. del c["vector"]
  417. if answer.lower().find("invalid key") >= 0 or answer.lower().find("invalid api") >= 0:
  418. answer += " Please set LLM API-Key in 'User Setting -> Model providers -> API-Key'"
  419. finish_chat_ts = timer()
  420. total_time_cost = (finish_chat_ts - chat_start_ts) * 1000
  421. check_llm_time_cost = (check_llm_ts - chat_start_ts) * 1000
  422. check_langfuse_tracer_cost = (check_langfuse_tracer_ts - check_llm_ts) * 1000
  423. bind_embedding_time_cost = (bind_models_ts - check_langfuse_tracer_ts) * 1000
  424. refine_question_time_cost = (refine_question_ts - bind_models_ts) * 1000
  425. retrieval_time_cost = (retrieval_ts - refine_question_ts) * 1000
  426. generate_result_time_cost = (finish_chat_ts - retrieval_ts) * 1000
  427. tk_num = num_tokens_from_string(think + answer)
  428. prompt += "\n\n### Query:\n%s" % " ".join(questions)
  429. prompt = (
  430. f"{prompt}\n\n"
  431. "## Time elapsed:\n"
  432. f" - Total: {total_time_cost:.1f}ms\n"
  433. f" - Check LLM: {check_llm_time_cost:.1f}ms\n"
  434. f" - Check Langfuse tracer: {check_langfuse_tracer_cost:.1f}ms\n"
  435. f" - Bind models: {bind_embedding_time_cost:.1f}ms\n"
  436. f" - Query refinement(LLM): {refine_question_time_cost:.1f}ms\n"
  437. f" - Retrieval: {retrieval_time_cost:.1f}ms\n"
  438. f" - Generate answer: {generate_result_time_cost:.1f}ms\n\n"
  439. "## Token usage:\n"
  440. f" - Generated tokens(approximately): {tk_num}\n"
  441. f" - Token speed: {int(tk_num / (generate_result_time_cost / 1000.0))}/s"
  442. )
  443. # Add a condition check to call the end method only if langfuse_tracer exists
  444. if langfuse_tracer and "langfuse_generation" in locals():
  445. langfuse_output = "\n" + re.sub(r"^.*?(### Query:.*)", r"\1", prompt, flags=re.DOTALL)
  446. langfuse_output = {"time_elapsed:": re.sub(r"\n", " \n", langfuse_output), "created_at": time.time()}
  447. langfuse_generation.update(output=langfuse_output)
  448. langfuse_generation.end()
  449. return {"answer": think + answer, "reference": refs, "prompt": re.sub(r"\n", " \n", prompt), "created_at": time.time()}
  450. if langfuse_tracer:
  451. langfuse_generation = langfuse_tracer.start_generation(
  452. trace_context=trace_context, name="chat", model=llm_model_config["llm_name"], input={"prompt": prompt, "prompt4citation": prompt4citation, "messages": msg}
  453. )
  454. if stream:
  455. last_ans = ""
  456. answer = ""
  457. for ans in chat_mdl.chat_streamly(prompt + prompt4citation, msg[1:], gen_conf):
  458. if thought:
  459. ans = re.sub(r"^.*</think>", "", ans, flags=re.DOTALL)
  460. answer = ans
  461. delta_ans = ans[len(last_ans) :]
  462. if num_tokens_from_string(delta_ans) < 16:
  463. continue
  464. last_ans = answer
  465. yield {"answer": thought + answer, "reference": {}, "audio_binary": tts(tts_mdl, delta_ans)}
  466. delta_ans = answer[len(last_ans) :]
  467. if delta_ans:
  468. yield {"answer": thought + answer, "reference": {}, "audio_binary": tts(tts_mdl, delta_ans)}
  469. yield decorate_answer(thought + answer)
  470. else:
  471. answer = chat_mdl.chat(prompt + prompt4citation, msg[1:], gen_conf)
  472. user_content = msg[-1].get("content", "[content not available]")
  473. logging.debug("User: {}|Assistant: {}".format(user_content, answer))
  474. res = decorate_answer(answer)
  475. res["audio_binary"] = tts(tts_mdl, answer)
  476. yield res
  477. def use_sql(question, field_map, tenant_id, chat_mdl, quota=True):
  478. 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."
  479. user_prompt = """
  480. Table name: {};
  481. Table of database fields are as follows:
  482. {}
  483. Question are as follows:
  484. {}
  485. Please write the SQL, only SQL, without any other explanations or text.
  486. """.format(index_name(tenant_id), "\n".join([f"{k}: {v}" for k, v in field_map.items()]), question)
  487. tried_times = 0
  488. def get_table():
  489. nonlocal sys_prompt, user_prompt, question, tried_times
  490. sql = chat_mdl.chat(sys_prompt, [{"role": "user", "content": user_prompt}], {"temperature": 0.06})
  491. sql = re.sub(r"^.*</think>", "", sql, flags=re.DOTALL)
  492. logging.debug(f"{question} ==> {user_prompt} get SQL: {sql}")
  493. sql = re.sub(r"[\r\n]+", " ", sql.lower())
  494. sql = re.sub(r".*select ", "select ", sql.lower())
  495. sql = re.sub(r" +", " ", sql)
  496. sql = re.sub(r"([;;]|```).*", "", sql)
  497. if sql[: len("select ")] != "select ":
  498. return None, None
  499. if not re.search(r"((sum|avg|max|min)\(|group by )", sql.lower()):
  500. if sql[: len("select *")] != "select *":
  501. sql = "select doc_id,docnm_kwd," + sql[6:]
  502. else:
  503. flds = []
  504. for k in field_map.keys():
  505. if k in forbidden_select_fields4resume:
  506. continue
  507. if len(flds) > 11:
  508. break
  509. flds.append(k)
  510. sql = "select doc_id,docnm_kwd," + ",".join(flds) + sql[8:]
  511. logging.debug(f"{question} get SQL(refined): {sql}")
  512. tried_times += 1
  513. return settings.retrievaler.sql_retrieval(sql, format="json"), sql
  514. tbl, sql = get_table()
  515. if tbl is None:
  516. return None
  517. if tbl.get("error") and tried_times <= 2:
  518. user_prompt = """
  519. Table name: {};
  520. Table of database fields are as follows:
  521. {}
  522. Question are as follows:
  523. {}
  524. Please write the SQL, only SQL, without any other explanations or text.
  525. The SQL error you provided last time is as follows:
  526. {}
  527. Error issued by database as follows:
  528. {}
  529. Please correct the error and write SQL again, only SQL, without any other explanations or text.
  530. """.format(index_name(tenant_id), "\n".join([f"{k}: {v}" for k, v in field_map.items()]), question, sql, tbl["error"])
  531. tbl, sql = get_table()
  532. logging.debug("TRY it again: {}".format(sql))
  533. logging.debug("GET table: {}".format(tbl))
  534. if tbl.get("error") or len(tbl["rows"]) == 0:
  535. return None
  536. docid_idx = set([ii for ii, c in enumerate(tbl["columns"]) if c["name"] == "doc_id"])
  537. doc_name_idx = set([ii for ii, c in enumerate(tbl["columns"]) if c["name"] == "docnm_kwd"])
  538. column_idx = [ii for ii in range(len(tbl["columns"])) if ii not in (docid_idx | doc_name_idx)]
  539. # compose Markdown table
  540. columns = (
  541. "|" + "|".join([re.sub(r"(/.*|([^()]+))", "", field_map.get(tbl["columns"][i]["name"], tbl["columns"][i]["name"])) for i in column_idx]) + ("|Source|" if docid_idx and docid_idx else "|")
  542. )
  543. line = "|" + "|".join(["------" for _ in range(len(column_idx))]) + ("|------|" if docid_idx and docid_idx else "")
  544. rows = ["|" + "|".join([rmSpace(str(r[i])) for i in column_idx]).replace("None", " ") + "|" for r in tbl["rows"]]
  545. rows = [r for r in rows if re.sub(r"[ |]+", "", r)]
  546. if quota:
  547. rows = "\n".join([r + f" ##{ii}$$ |" for ii, r in enumerate(rows)])
  548. else:
  549. rows = "\n".join([r + f" ##{ii}$$ |" for ii, r in enumerate(rows)])
  550. rows = re.sub(r"T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+Z)?\|", "|", rows)
  551. if not docid_idx or not doc_name_idx:
  552. logging.warning("SQL missing field: " + sql)
  553. return {"answer": "\n".join([columns, line, rows]), "reference": {"chunks": [], "doc_aggs": []}, "prompt": sys_prompt}
  554. docid_idx = list(docid_idx)[0]
  555. doc_name_idx = list(doc_name_idx)[0]
  556. doc_aggs = {}
  557. for r in tbl["rows"]:
  558. if r[docid_idx] not in doc_aggs:
  559. doc_aggs[r[docid_idx]] = {"doc_name": r[doc_name_idx], "count": 0}
  560. doc_aggs[r[docid_idx]]["count"] += 1
  561. return {
  562. "answer": "\n".join([columns, line, rows]),
  563. "reference": {
  564. "chunks": [{"doc_id": r[docid_idx], "docnm_kwd": r[doc_name_idx]} for r in tbl["rows"]],
  565. "doc_aggs": [{"doc_id": did, "doc_name": d["doc_name"], "count": d["count"]} for did, d in doc_aggs.items()],
  566. },
  567. "prompt": sys_prompt,
  568. }
  569. def tts(tts_mdl, text):
  570. if not tts_mdl or not text:
  571. return
  572. bin = b""
  573. for chunk in tts_mdl.tts(text):
  574. bin += chunk
  575. return binascii.hexlify(bin).decode("utf-8")
  576. def ask(question, kb_ids, tenant_id, chat_llm_name=None):
  577. kbs = KnowledgebaseService.get_by_ids(kb_ids)
  578. embedding_list = list(set([kb.embd_id for kb in kbs]))
  579. is_knowledge_graph = all([kb.parser_id == ParserType.KG for kb in kbs])
  580. retriever = settings.retrievaler if not is_knowledge_graph else settings.kg_retrievaler
  581. embd_mdl = LLMBundle(tenant_id, LLMType.EMBEDDING, embedding_list[0])
  582. chat_mdl = LLMBundle(tenant_id, LLMType.CHAT, chat_llm_name)
  583. max_tokens = chat_mdl.max_length
  584. tenant_ids = list(set([kb.tenant_id for kb in kbs]))
  585. kbinfos = retriever.retrieval(question, embd_mdl, tenant_ids, kb_ids, 1, 12, 0.1, 0.3, aggs=False, rank_feature=label_question(question, kbs))
  586. knowledges = kb_prompt(kbinfos, max_tokens)
  587. prompt = """
  588. Role: You're a smart assistant. Your name is Miss R.
  589. Task: Summarize the information from knowledge bases and answer user's question.
  590. Requirements and restriction:
  591. - DO NOT make things up, especially for numbers.
  592. - If the information from knowledge is irrelevant with user's question, JUST SAY: Sorry, no relevant information provided.
  593. - Answer with markdown format text.
  594. - Answer in language of user's question.
  595. - DO NOT make things up, especially for numbers.
  596. ### Information from knowledge bases
  597. %s
  598. The above is information from knowledge bases.
  599. """ % "\n".join(knowledges)
  600. msg = [{"role": "user", "content": question}]
  601. def decorate_answer(answer):
  602. nonlocal knowledges, kbinfos, prompt
  603. answer, idx = retriever.insert_citations(answer, [ck["content_ltks"] for ck in kbinfos["chunks"]], [ck["vector"] for ck in kbinfos["chunks"]], embd_mdl, tkweight=0.7, vtweight=0.3)
  604. idx = set([kbinfos["chunks"][int(i)]["doc_id"] for i in idx])
  605. recall_docs = [d for d in kbinfos["doc_aggs"] if d["doc_id"] in idx]
  606. if not recall_docs:
  607. recall_docs = kbinfos["doc_aggs"]
  608. kbinfos["doc_aggs"] = recall_docs
  609. refs = deepcopy(kbinfos)
  610. for c in refs["chunks"]:
  611. if c.get("vector"):
  612. del c["vector"]
  613. if answer.lower().find("invalid key") >= 0 or answer.lower().find("invalid api") >= 0:
  614. answer += " Please set LLM API-Key in 'User Setting -> Model Providers -> API-Key'"
  615. refs["chunks"] = chunks_format(refs)
  616. return {"answer": answer, "reference": refs}
  617. answer = ""
  618. for ans in chat_mdl.chat_streamly(prompt, msg, {"temperature": 0.1}):
  619. answer = ans
  620. yield {"answer": answer, "reference": {}}
  621. yield decorate_answer(answer)