Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. from abc import ABC
  17. import pandas as pd
  18. from api.db import LLMType
  19. from api.db.services.knowledgebase_service import KnowledgebaseService
  20. from api.db.services.llm_service import LLMBundle
  21. from api.settings import retrievaler
  22. from agent.component.base import ComponentBase, ComponentParamBase
  23. class RetrievalParam(ComponentParamBase):
  24. """
  25. Define the Retrieval component parameters.
  26. """
  27. def __init__(self):
  28. super().__init__()
  29. self.similarity_threshold = 0.2
  30. self.keywords_similarity_weight = 0.5
  31. self.top_n = 8
  32. self.top_k = 1024
  33. self.kb_ids = []
  34. self.rerank_id = ""
  35. self.empty_response = ""
  36. def check(self):
  37. self.check_decimal_float(self.similarity_threshold, "[Retrieval] Similarity threshold")
  38. self.check_decimal_float(self.keywords_similarity_weight, "[Retrieval] Keywords similarity weight")
  39. self.check_positive_number(self.top_n, "[Retrieval] Top N")
  40. self.check_empty(self.kb_ids, "[Retrieval] Knowledge bases")
  41. class Retrieval(ComponentBase, ABC):
  42. component_name = "Retrieval"
  43. def _run(self, history, **kwargs):
  44. query = []
  45. for role, cnt in history[::-1][:self._param.message_history_window_size]:
  46. if role != "user":continue
  47. query.append(cnt)
  48. query = "\n".join(query)
  49. kbs = KnowledgebaseService.get_by_ids(self._param.kb_ids)
  50. if not kbs:
  51. raise ValueError("Can't find knowledgebases by {}".format(self._param.kb_ids))
  52. embd_nms = list(set([kb.embd_id for kb in kbs]))
  53. assert len(embd_nms) == 1, "Knowledge bases use different embedding models."
  54. embd_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.EMBEDDING, embd_nms[0])
  55. self._canvas.set_embedding_model(embd_nms[0])
  56. rerank_mdl = None
  57. if self._param.rerank_id:
  58. rerank_mdl = LLMBundle(kbs[0].tenant_id, LLMType.RERANK, self._param.rerank_id)
  59. kbinfos = retrievaler.retrieval(query, embd_mdl, kbs[0].tenant_id, self._param.kb_ids,
  60. 1, self._param.top_n,
  61. self._param.similarity_threshold, 1 - self._param.keywords_similarity_weight,
  62. aggs=False, rerank_mdl=rerank_mdl)
  63. if not kbinfos["chunks"]:
  64. df = Retrieval.be_output(self._param.empty_response)
  65. df["empty_response"] = True
  66. return df
  67. df = pd.DataFrame(kbinfos["chunks"])
  68. df["content"] = df["content_with_weight"]
  69. del df["content_with_weight"]
  70. print(">>>>>>>>>>>>>>>>>>>>>>>>>>\n", query, df)
  71. return df