選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

retrieval.py 4.7KB

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