Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

retrieval.py 4.2KB

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