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

retrieval.py 4.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  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 json
  17. import logging
  18. from abc import ABC
  19. import pandas as pd
  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 agent.component.base import ComponentBase, ComponentParamBase
  25. from rag.app.tag import label_question
  26. from rag.prompts import kb_prompt
  27. from rag.utils.tavily_conn import Tavily
  28. class RetrievalParam(ComponentParamBase):
  29. """
  30. Define the Retrieval component parameters.
  31. """
  32. def __init__(self):
  33. super().__init__()
  34. self.similarity_threshold = 0.2
  35. self.keywords_similarity_weight = 0.5
  36. self.top_n = 8
  37. self.top_k = 1024
  38. self.kb_ids = []
  39. self.kb_vars = []
  40. self.rerank_id = ""
  41. self.empty_response = ""
  42. self.tavily_api_key = ""
  43. self.use_kg = False
  44. def check(self):
  45. self.check_decimal_float(self.similarity_threshold, "[Retrieval] Similarity threshold")
  46. self.check_decimal_float(self.keywords_similarity_weight, "[Retrieval] Keyword similarity weight")
  47. self.check_positive_number(self.top_n, "[Retrieval] Top N")
  48. class Retrieval(ComponentBase, ABC):
  49. component_name = "Retrieval"
  50. def _run(self, history, **kwargs):
  51. query = self.get_input()
  52. query = str(query["content"][0]) if "content" in query else ""
  53. kb_ids: list[str] = self._param.kb_ids or []
  54. kb_vars = self._fetch_outputs_from(self._param.kb_vars)
  55. if len(kb_vars) > 0:
  56. for kb_var in kb_vars:
  57. if len(kb_var) == 1:
  58. kb_var_value = str(kb_var["content"][0])
  59. for v in kb_var_value.split(","):
  60. kb_ids.append(v)
  61. else:
  62. for v in kb_var.to_dict("records"):
  63. kb_ids.append(v["content"])
  64. filtered_kb_ids: list[str] = [kb_id for kb_id in kb_ids if kb_id]
  65. kbs = KnowledgebaseService.get_by_ids(filtered_kb_ids)
  66. if not kbs:
  67. return Retrieval.be_output("")
  68. embd_nms = list(set([kb.embd_id for kb in kbs]))
  69. assert len(embd_nms) == 1, "Knowledge bases use different embedding models."
  70. embd_mdl = None
  71. if embd_nms:
  72. embd_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.EMBEDDING, embd_nms[0])
  73. self._canvas.set_embedding_model(embd_nms[0])
  74. rerank_mdl = None
  75. if self._param.rerank_id:
  76. rerank_mdl = LLMBundle(kbs[0].tenant_id, LLMType.RERANK, self._param.rerank_id)
  77. if kbs:
  78. kbinfos = settings.retrievaler.retrieval(
  79. query,
  80. embd_mdl,
  81. [kb.tenant_id for kb in kbs],
  82. filtered_kb_ids,
  83. 1,
  84. self._param.top_n,
  85. self._param.similarity_threshold,
  86. 1 - self._param.keywords_similarity_weight,
  87. aggs=False,
  88. rerank_mdl=rerank_mdl,
  89. rank_feature=label_question(query, kbs),
  90. )
  91. else:
  92. kbinfos = {"chunks": [], "doc_aggs": []}
  93. if self._param.use_kg and kbs:
  94. 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))
  95. if ck["content_with_weight"]:
  96. kbinfos["chunks"].insert(0, ck)
  97. if self._param.tavily_api_key:
  98. tav = Tavily(self._param.tavily_api_key)
  99. tav_res = tav.retrieve_chunks(query)
  100. kbinfos["chunks"].extend(tav_res["chunks"])
  101. kbinfos["doc_aggs"].extend(tav_res["doc_aggs"])
  102. if not kbinfos["chunks"]:
  103. df = Retrieval.be_output("")
  104. if self._param.empty_response and self._param.empty_response.strip():
  105. df["empty_response"] = self._param.empty_response
  106. return df
  107. df = pd.DataFrame({"content": kb_prompt(kbinfos, 200000), "chunks": json.dumps(kbinfos["chunks"])})
  108. logging.debug("{} {}".format(query, df))
  109. return df.dropna()