Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

deep_research.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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 re
  18. from functools import partial
  19. from agentic_reasoning.prompts import BEGIN_SEARCH_QUERY, BEGIN_SEARCH_RESULT, END_SEARCH_RESULT, MAX_SEARCH_LIMIT, \
  20. END_SEARCH_QUERY, REASON_PROMPT, RELEVANT_EXTRACTION_PROMPT
  21. from api.db.services.llm_service import LLMBundle
  22. from rag.nlp import extract_between
  23. from rag.prompts import kb_prompt
  24. from rag.utils.tavily_conn import Tavily
  25. class DeepResearcher:
  26. def __init__(self,
  27. chat_mdl: LLMBundle,
  28. prompt_config: dict,
  29. kb_retrieve: partial = None,
  30. kg_retrieve: partial = None
  31. ):
  32. self.chat_mdl = chat_mdl
  33. self.prompt_config = prompt_config
  34. self._kb_retrieve = kb_retrieve
  35. self._kg_retrieve = kg_retrieve
  36. def _remove_tags(text: str, start_tag: str, end_tag: str) -> str:
  37. """General Tag Removal Method"""
  38. pattern = re.escape(start_tag) + r"(.*?)" + re.escape(end_tag)
  39. return re.sub(pattern, "", text)
  40. @staticmethod
  41. def _remove_query_tags(text: str) -> str:
  42. """Remove Query Tags"""
  43. return DeepResearcher._remove_tags(text, BEGIN_SEARCH_QUERY, END_SEARCH_QUERY)
  44. @staticmethod
  45. def _remove_result_tags(text: str) -> str:
  46. """Remove Result Tags"""
  47. return DeepResearcher._remove_tags(text, BEGIN_SEARCH_RESULT, END_SEARCH_RESULT)
  48. def _generate_reasoning(self, msg_history):
  49. """Generate reasoning steps"""
  50. query_think = ""
  51. if msg_history[-1]["role"] != "user":
  52. msg_history.append({"role": "user", "content": "Continues reasoning with the new information.\n"})
  53. else:
  54. msg_history[-1]["content"] += "\n\nContinues reasoning with the new information.\n"
  55. for ans in self.chat_mdl.chat_streamly(REASON_PROMPT, msg_history, {"temperature": 0.7}):
  56. ans = re.sub(r"^.*</think>", "", ans, flags=re.DOTALL)
  57. if not ans:
  58. continue
  59. query_think = ans
  60. yield query_think
  61. return query_think
  62. def _extract_search_queries(self, query_think, question, step_index):
  63. """Extract search queries from thinking"""
  64. queries = extract_between(query_think, BEGIN_SEARCH_QUERY, END_SEARCH_QUERY)
  65. if not queries and step_index == 0:
  66. # If this is the first step and no queries are found, use the original question as the query
  67. queries = [question]
  68. return queries
  69. def _truncate_previous_reasoning(self, all_reasoning_steps):
  70. """Truncate previous reasoning steps to maintain a reasonable length"""
  71. truncated_prev_reasoning = ""
  72. for i, step in enumerate(all_reasoning_steps):
  73. truncated_prev_reasoning += f"Step {i + 1}: {step}\n\n"
  74. prev_steps = truncated_prev_reasoning.split('\n\n')
  75. if len(prev_steps) <= 5:
  76. truncated_prev_reasoning = '\n\n'.join(prev_steps)
  77. else:
  78. truncated_prev_reasoning = ''
  79. for i, step in enumerate(prev_steps):
  80. if i == 0 or i >= len(prev_steps) - 4 or BEGIN_SEARCH_QUERY in step or BEGIN_SEARCH_RESULT in step:
  81. truncated_prev_reasoning += step + '\n\n'
  82. else:
  83. if truncated_prev_reasoning[-len('\n\n...\n\n'):] != '\n\n...\n\n':
  84. truncated_prev_reasoning += '...\n\n'
  85. return truncated_prev_reasoning.strip('\n')
  86. def _retrieve_information(self, search_query):
  87. """Retrieve information from different sources"""
  88. # 1. Knowledge base retrieval
  89. kbinfos = []
  90. try:
  91. kbinfos = self._kb_retrieve(question=search_query) if self._kb_retrieve else {"chunks": [], "doc_aggs": []}
  92. except Exception as e:
  93. logging.error(f"Knowledge base retrieval error: {e}")
  94. # 2. Web retrieval (if Tavily API is configured)
  95. try:
  96. if self.prompt_config.get("tavily_api_key"):
  97. tav = Tavily(self.prompt_config["tavily_api_key"])
  98. tav_res = tav.retrieve_chunks(search_query)
  99. kbinfos["chunks"].extend(tav_res["chunks"])
  100. kbinfos["doc_aggs"].extend(tav_res["doc_aggs"])
  101. except Exception as e:
  102. logging.error(f"Web retrieval error: {e}")
  103. # 3. Knowledge graph retrieval (if configured)
  104. try:
  105. if self.prompt_config.get("use_kg") and self._kg_retrieve:
  106. ck = self._kg_retrieve(question=search_query)
  107. if ck["content_with_weight"]:
  108. kbinfos["chunks"].insert(0, ck)
  109. except Exception as e:
  110. logging.error(f"Knowledge graph retrieval error: {e}")
  111. return kbinfos
  112. def _update_chunk_info(self, chunk_info, kbinfos):
  113. """Update chunk information for citations"""
  114. if not chunk_info["chunks"]:
  115. # If this is the first retrieval, use the retrieval results directly
  116. for k in chunk_info.keys():
  117. chunk_info[k] = kbinfos[k]
  118. else:
  119. # Merge newly retrieved information, avoiding duplicates
  120. cids = [c["chunk_id"] for c in chunk_info["chunks"]]
  121. for c in kbinfos["chunks"]:
  122. if c["chunk_id"] not in cids:
  123. chunk_info["chunks"].append(c)
  124. dids = [d["doc_id"] for d in chunk_info["doc_aggs"]]
  125. for d in kbinfos["doc_aggs"]:
  126. if d["doc_id"] not in dids:
  127. chunk_info["doc_aggs"].append(d)
  128. def _extract_relevant_info(self, truncated_prev_reasoning, search_query, kbinfos):
  129. """Extract and summarize relevant information"""
  130. summary_think = ""
  131. for ans in self.chat_mdl.chat_streamly(
  132. RELEVANT_EXTRACTION_PROMPT.format(
  133. prev_reasoning=truncated_prev_reasoning,
  134. search_query=search_query,
  135. document="\n".join(kb_prompt(kbinfos, 4096))
  136. ),
  137. [{"role": "user",
  138. "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.'}],
  139. {"temperature": 0.7}):
  140. ans = re.sub(r"^.*</think>", "", ans, flags=re.DOTALL)
  141. if not ans:
  142. continue
  143. summary_think = ans
  144. yield summary_think
  145. return summary_think
  146. def thinking(self, chunk_info: dict, question: str):
  147. executed_search_queries = []
  148. msg_history = [{"role": "user", "content": f'Question:\"{question}\"\n'}]
  149. all_reasoning_steps = []
  150. think = "<think>"
  151. for step_index in range(MAX_SEARCH_LIMIT + 1):
  152. # Check if the maximum search limit has been reached
  153. if step_index == MAX_SEARCH_LIMIT - 1:
  154. summary_think = f"\n{BEGIN_SEARCH_RESULT}\nThe maximum search limit is exceeded. You are not allowed to search.\n{END_SEARCH_RESULT}\n"
  155. yield {"answer": think + summary_think + "</think>", "reference": {}, "audio_binary": None}
  156. all_reasoning_steps.append(summary_think)
  157. msg_history.append({"role": "assistant", "content": summary_think})
  158. break
  159. # Step 1: Generate reasoning
  160. query_think = ""
  161. for ans in self._generate_reasoning(msg_history):
  162. query_think = ans
  163. yield {"answer": think + self._remove_query_tags(query_think) + "</think>", "reference": {}, "audio_binary": None}
  164. think += self._remove_query_tags(query_think)
  165. all_reasoning_steps.append(query_think)
  166. # Step 2: Extract search queries
  167. queries = self._extract_search_queries(query_think, question, step_index)
  168. if not queries and step_index > 0:
  169. # If not the first step and no queries, end the search process
  170. break
  171. # Process each search query
  172. for search_query in queries:
  173. logging.info(f"[THINK]Query: {step_index}. {search_query}")
  174. msg_history.append({"role": "assistant", "content": search_query})
  175. think += f"\n\n> {step_index + 1}. {search_query}\n\n"
  176. yield {"answer": think + "</think>", "reference": {}, "audio_binary": None}
  177. # Check if the query has already been executed
  178. if search_query in executed_search_queries:
  179. summary_think = f"\n{BEGIN_SEARCH_RESULT}\nYou have searched this query. Please refer to previous results.\n{END_SEARCH_RESULT}\n"
  180. yield {"answer": think + summary_think + "</think>", "reference": {}, "audio_binary": None}
  181. all_reasoning_steps.append(summary_think)
  182. msg_history.append({"role": "user", "content": summary_think})
  183. think += summary_think
  184. continue
  185. executed_search_queries.append(search_query)
  186. # Step 3: Truncate previous reasoning steps
  187. truncated_prev_reasoning = self._truncate_previous_reasoning(all_reasoning_steps)
  188. # Step 4: Retrieve information
  189. kbinfos = self._retrieve_information(search_query)
  190. # Step 5: Update chunk information
  191. self._update_chunk_info(chunk_info, kbinfos)
  192. # Step 6: Extract relevant information
  193. think += "\n\n"
  194. summary_think = ""
  195. for ans in self._extract_relevant_info(truncated_prev_reasoning, search_query, kbinfos):
  196. summary_think = ans
  197. yield {"answer": think + self._remove_result_tags(summary_think) + "</think>", "reference": {}, "audio_binary": None}
  198. all_reasoning_steps.append(summary_think)
  199. msg_history.append(
  200. {"role": "user", "content": f"\n\n{BEGIN_SEARCH_RESULT}{summary_think}{END_SEARCH_RESULT}\n\n"})
  201. think += self._remove_result_tags(summary_think)
  202. logging.info(f"[THINK]Summary: {step_index}. {summary_think}")
  203. yield think + "</think>"