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

deep_research.py 10KB

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