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.

retrieval.py 6.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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 os
  17. import re
  18. from abc import ABC
  19. from agent.tools.base import ToolParamBase, ToolBase, ToolMeta
  20. from api.db import LLMType
  21. from api.db.services.knowledgebase_service import KnowledgebaseService
  22. from api.db.services.llm_service import LLMBundle
  23. from api import settings
  24. from api.utils.api_utils import timeout
  25. from rag.app.tag import label_question
  26. from rag.prompts import kb_prompt
  27. from rag.prompts.prompts import cross_languages
  28. class RetrievalParam(ToolParamBase):
  29. """
  30. Define the Retrieval component parameters.
  31. """
  32. def __init__(self):
  33. self.meta:ToolMeta = {
  34. "name": "search_my_dateset",
  35. "description": "This tool can be utilized for relevant content searching in the datasets.",
  36. "parameters": {
  37. "query": {
  38. "type": "string",
  39. "description": "The keywords to search the dataset. The keywords should be the most important words/terms(includes synonyms) from the original request.",
  40. "default": "",
  41. "required": True
  42. }
  43. }
  44. }
  45. super().__init__()
  46. self.function_name = "search_my_dateset"
  47. self.description = "This tool can be utilized for relevant content searching in the datasets."
  48. self.similarity_threshold = 0.2
  49. self.keywords_similarity_weight = 0.5
  50. self.top_n = 8
  51. self.top_k = 1024
  52. self.kb_ids = []
  53. self.kb_vars = []
  54. self.rerank_id = ""
  55. self.empty_response = ""
  56. self.use_kg = False
  57. self.cross_languages = []
  58. def check(self):
  59. self.check_decimal_float(self.similarity_threshold, "[Retrieval] Similarity threshold")
  60. self.check_decimal_float(self.keywords_similarity_weight, "[Retrieval] Keyword similarity weight")
  61. self.check_positive_number(self.top_n, "[Retrieval] Top N")
  62. def get_input_form(self) -> dict[str, dict]:
  63. return {
  64. "query": {
  65. "name": "Query",
  66. "type": "line"
  67. }
  68. }
  69. class Retrieval(ToolBase, ABC):
  70. component_name = "Retrieval"
  71. @timeout(os.environ.get("COMPONENT_EXEC_TIMEOUT", 12))
  72. def _invoke(self, **kwargs):
  73. if not kwargs.get("query"):
  74. self.set_output("formalized_content", self._param.empty_response)
  75. kb_ids: list[str] = []
  76. for id in self._param.kb_ids:
  77. if id.find("@") < 0:
  78. kb_ids.append(id)
  79. continue
  80. kb_nm = self._canvas.get_variable_value(id)
  81. # if kb_nm is a list
  82. kb_nm_list = kb_nm if isinstance(kb_nm, list) else [kb_nm]
  83. for nm_or_id in kb_nm_list:
  84. e, kb = KnowledgebaseService.get_by_name(nm_or_id,
  85. self._canvas._tenant_id)
  86. if not e:
  87. e, kb = KnowledgebaseService.get_by_id(nm_or_id)
  88. if not e:
  89. raise Exception(f"Dataset({nm_or_id}) does not exist.")
  90. kb_ids.append(kb.id)
  91. filtered_kb_ids: list[str] = list(set([kb_id for kb_id in kb_ids if kb_id]))
  92. kbs = KnowledgebaseService.get_by_ids(filtered_kb_ids)
  93. if not kbs:
  94. raise Exception("No dataset is selected.")
  95. embd_nms = list(set([kb.embd_id for kb in kbs]))
  96. assert len(embd_nms) == 1, "Knowledge bases use different embedding models."
  97. embd_mdl = None
  98. if embd_nms:
  99. embd_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.EMBEDDING, embd_nms[0])
  100. rerank_mdl = None
  101. if self._param.rerank_id:
  102. rerank_mdl = LLMBundle(kbs[0].tenant_id, LLMType.RERANK, self._param.rerank_id)
  103. vars = self.get_input_elements_from_text(kwargs["query"])
  104. vars = {k:o["value"] for k,o in vars.items()}
  105. query = self.string_format(kwargs["query"], vars)
  106. if self._param.cross_languages:
  107. query = cross_languages(kbs[0].tenant_id, None, query, self._param.cross_languages)
  108. if kbs:
  109. query = re.sub(r"^user[::\s]*", "", query, flags=re.IGNORECASE)
  110. kbinfos = settings.retrievaler.retrieval(
  111. query,
  112. embd_mdl,
  113. [kb.tenant_id for kb in kbs],
  114. filtered_kb_ids,
  115. 1,
  116. self._param.top_n,
  117. self._param.similarity_threshold,
  118. 1 - self._param.keywords_similarity_weight,
  119. aggs=False,
  120. rerank_mdl=rerank_mdl,
  121. rank_feature=label_question(query, kbs),
  122. )
  123. if self._param.use_kg:
  124. ck = settings.kg_retrievaler.retrieval(query,
  125. [kb.tenant_id for kb in kbs],
  126. kb_ids,
  127. embd_mdl,
  128. LLMBundle(self._canvas.get_tenant_id(), LLMType.CHAT))
  129. if ck["content_with_weight"]:
  130. kbinfos["chunks"].insert(0, ck)
  131. else:
  132. kbinfos = {"chunks": [], "doc_aggs": []}
  133. if self._param.use_kg and kbs:
  134. ck = settings.kg_retrievaler.retrieval(query, [kb.tenant_id for kb in kbs], filtered_kb_ids, embd_mdl, LLMBundle(kbs[0].tenant_id, LLMType.CHAT))
  135. if ck["content_with_weight"]:
  136. ck["content"] = ck["content_with_weight"]
  137. del ck["content_with_weight"]
  138. kbinfos["chunks"].insert(0, ck)
  139. for ck in kbinfos["chunks"]:
  140. if "vector" in ck:
  141. del ck["vector"]
  142. if "content_ltks" in ck:
  143. del ck["content_ltks"]
  144. if not kbinfos["chunks"]:
  145. self.set_output("formalized_content", self._param.empty_response)
  146. return
  147. self._canvas.add_refernce(kbinfos["chunks"], kbinfos["doc_aggs"])
  148. form_cnt = "\n".join(kb_prompt(kbinfos, 200000, True))
  149. self.set_output("formalized_content", form_cnt)
  150. return form_cnt
  151. def thoughts(self) -> str:
  152. return """
  153. Keywords: {}
  154. Looking for the most relevant articles.
  155. """.format(self.get_input().get("query", "-_-!"))