您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

dialog_service.py 44KB

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