You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

deep_research.py 8.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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 thinking(self, chunk_info: dict, question: str):
  37. def rm_query_tags(line):
  38. pattern = re.escape(BEGIN_SEARCH_QUERY) + r"(.*?)" + re.escape(END_SEARCH_QUERY)
  39. return re.sub(pattern, "", line)
  40. def rm_result_tags(line):
  41. pattern = re.escape(BEGIN_SEARCH_RESULT) + r"(.*?)" + re.escape(END_SEARCH_RESULT)
  42. return re.sub(pattern, "", line)
  43. executed_search_queries = []
  44. msg_hisotry = [{"role": "user", "content": f'Question:\"{question}\"\n'}]
  45. all_reasoning_steps = []
  46. think = "<think>"
  47. for ii in range(MAX_SEARCH_LIMIT + 1):
  48. if ii == MAX_SEARCH_LIMIT - 1:
  49. summary_think = f"\n{BEGIN_SEARCH_RESULT}\nThe maximum search limit is exceeded. You are not allowed to search.\n{END_SEARCH_RESULT}\n"
  50. yield {"answer": think + summary_think + "</think>", "reference": {}, "audio_binary": None}
  51. all_reasoning_steps.append(summary_think)
  52. msg_hisotry.append({"role": "assistant", "content": summary_think})
  53. break
  54. query_think = ""
  55. if msg_hisotry[-1]["role"] != "user":
  56. msg_hisotry.append({"role": "user", "content": "Continues reasoning with the new information.\n"})
  57. else:
  58. msg_hisotry[-1]["content"] += "\n\nContinues reasoning with the new information.\n"
  59. for ans in self.chat_mdl.chat_streamly(REASON_PROMPT, msg_hisotry, {"temperature": 0.7}):
  60. ans = re.sub(r"<think>.*</think>", "", ans, flags=re.DOTALL)
  61. if not ans:
  62. continue
  63. query_think = ans
  64. yield {"answer": think + rm_query_tags(query_think) + "</think>", "reference": {}, "audio_binary": None}
  65. think += rm_query_tags(query_think)
  66. all_reasoning_steps.append(query_think)
  67. queries = extract_between(query_think, BEGIN_SEARCH_QUERY, END_SEARCH_QUERY)
  68. if not queries:
  69. if ii > 0:
  70. break
  71. queries = [question]
  72. for search_query in queries:
  73. logging.info(f"[THINK]Query: {ii}. {search_query}")
  74. msg_hisotry.append({"role": "assistant", "content": search_query})
  75. think += f"\n\n> {ii +1}. {search_query}\n\n"
  76. yield {"answer": think + "</think>", "reference": {}, "audio_binary": None}
  77. summary_think = ""
  78. # The search query has been searched in previous steps.
  79. if search_query in executed_search_queries:
  80. summary_think = f"\n{BEGIN_SEARCH_RESULT}\nYou have searched this query. Please refer to previous results.\n{END_SEARCH_RESULT}\n"
  81. yield {"answer": think + summary_think + "</think>", "reference": {}, "audio_binary": None}
  82. all_reasoning_steps.append(summary_think)
  83. msg_hisotry.append({"role": "user", "content": summary_think})
  84. think += summary_think
  85. continue
  86. truncated_prev_reasoning = ""
  87. for i, step in enumerate(all_reasoning_steps):
  88. truncated_prev_reasoning += f"Step {i + 1}: {step}\n\n"
  89. prev_steps = truncated_prev_reasoning.split('\n\n')
  90. if len(prev_steps) <= 5:
  91. truncated_prev_reasoning = '\n\n'.join(prev_steps)
  92. else:
  93. truncated_prev_reasoning = ''
  94. for i, step in enumerate(prev_steps):
  95. if i == 0 or i >= len(prev_steps) - 4 or BEGIN_SEARCH_QUERY in step or BEGIN_SEARCH_RESULT in step:
  96. truncated_prev_reasoning += step + '\n\n'
  97. else:
  98. if truncated_prev_reasoning[-len('\n\n...\n\n'):] != '\n\n...\n\n':
  99. truncated_prev_reasoning += '...\n\n'
  100. truncated_prev_reasoning = truncated_prev_reasoning.strip('\n')
  101. # Retrieval procedure:
  102. # 1. KB search
  103. # 2. Web search (optional)
  104. # 3. KG search (optional)
  105. kbinfos = self._kb_retrieve(question=search_query) if self._kb_retrieve else {"chunks": [], "doc_aggs": []}
  106. if self.prompt_config.get("tavily_api_key"):
  107. tav = Tavily(self.prompt_config["tavily_api_key"])
  108. tav_res = tav.retrieve_chunks(search_query)
  109. kbinfos["chunks"].extend(tav_res["chunks"])
  110. kbinfos["doc_aggs"].extend(tav_res["doc_aggs"])
  111. if self.prompt_config.get("use_kg") and self._kg_retrieve:
  112. ck = self._kg_retrieve(question=search_query)
  113. if ck["content_with_weight"]:
  114. kbinfos["chunks"].insert(0, ck)
  115. # Merge chunk info for citations
  116. if not chunk_info["chunks"]:
  117. for k in chunk_info.keys():
  118. chunk_info[k] = kbinfos[k]
  119. else:
  120. cids = [c["chunk_id"] for c in chunk_info["chunks"]]
  121. for c in kbinfos["chunks"]:
  122. if c["chunk_id"] in cids:
  123. continue
  124. chunk_info["chunks"].append(c)
  125. dids = [d["doc_id"] for d in chunk_info["doc_aggs"]]
  126. for d in kbinfos["doc_aggs"]:
  127. if d["doc_id"] in dids:
  128. continue
  129. chunk_info["doc_aggs"].append(d)
  130. think += "\n\n"
  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>.*</think>", "", ans, flags=re.DOTALL)
  141. if not ans:
  142. continue
  143. summary_think = ans
  144. yield {"answer": think + rm_result_tags(summary_think) + "</think>", "reference": {}, "audio_binary": None}
  145. all_reasoning_steps.append(summary_think)
  146. msg_hisotry.append(
  147. {"role": "user", "content": f"\n\n{BEGIN_SEARCH_RESULT}{summary_think}{END_SEARCH_RESULT}\n\n"})
  148. think += rm_result_tags(summary_think)
  149. logging.info(f"[THINK]Summary: {ii}. {summary_think}")
  150. yield think + "</think>"