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 3.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. class RetrievalParam(ComponentParamBase):
  26. """
  27. Define the Retrieval component parameters.
  28. """
  29. def __init__(self):
  30. super().__init__()
  31. self.similarity_threshold = 0.2
  32. self.keywords_similarity_weight = 0.5
  33. self.top_n = 8
  34. self.top_k = 1024
  35. self.kb_ids = []
  36. self.rerank_id = ""
  37. self.empty_response = ""
  38. def check(self):
  39. self.check_decimal_float(self.similarity_threshold, "[Retrieval] Similarity threshold")
  40. self.check_decimal_float(self.keywords_similarity_weight, "[Retrieval] Keyword similarity weight")
  41. self.check_positive_number(self.top_n, "[Retrieval] Top N")
  42. class Retrieval(ComponentBase, ABC):
  43. component_name = "Retrieval"
  44. def _run(self, history, **kwargs):
  45. query = self.get_input()
  46. query = str(query["content"][0]) if "content" in query else ""
  47. lines = query.split('\n')
  48. user_queries = [line.split("USER:", 1)[1] for line in lines if line.startswith("USER:")]
  49. query = user_queries[-1] if user_queries else ""
  50. kbs = KnowledgebaseService.get_by_ids(self._param.kb_ids)
  51. if not kbs:
  52. return Retrieval.be_output("")
  53. embd_nms = list(set([kb.embd_id for kb in kbs]))
  54. assert len(embd_nms) == 1, "Knowledge bases use different embedding models."
  55. embd_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.EMBEDDING, embd_nms[0])
  56. self._canvas.set_embedding_model(embd_nms[0])
  57. rerank_mdl = None
  58. if self._param.rerank_id:
  59. rerank_mdl = LLMBundle(kbs[0].tenant_id, LLMType.RERANK, self._param.rerank_id)
  60. kbinfos = settings.retrievaler.retrieval(query, embd_mdl, kbs[0].tenant_id, self._param.kb_ids,
  61. 1, self._param.top_n,
  62. self._param.similarity_threshold, 1 - self._param.keywords_similarity_weight,
  63. aggs=False, rerank_mdl=rerank_mdl,
  64. rank_feature=label_question(query, kbs))
  65. if not kbinfos["chunks"]:
  66. df = Retrieval.be_output("")
  67. if self._param.empty_response and self._param.empty_response.strip():
  68. df["empty_response"] = self._param.empty_response
  69. return df
  70. df = pd.DataFrame(kbinfos["chunks"])
  71. df["content"] = df["content_with_weight"]
  72. del df["content_with_weight"]
  73. logging.debug("{} {}".format(query, df))
  74. return df