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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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.rerank_id = ""
  40. self.empty_response = ""
  41. self.tavily_api_key = ""
  42. self.use_kg = False
  43. def check(self):
  44. self.check_decimal_float(self.similarity_threshold, "[Retrieval] Similarity threshold")
  45. self.check_decimal_float(self.keywords_similarity_weight, "[Retrieval] Keyword similarity weight")
  46. self.check_positive_number(self.top_n, "[Retrieval] Top N")
  47. class Retrieval(ComponentBase, ABC):
  48. component_name = "Retrieval"
  49. def _run(self, history, **kwargs):
  50. query = self.get_input()
  51. query = str(query["content"][0]) if "content" in query else ""
  52. kbs = KnowledgebaseService.get_by_ids(self._param.kb_ids)
  53. if not kbs:
  54. return Retrieval.be_output("")
  55. embd_nms = list(set([kb.embd_id for kb in kbs]))
  56. assert len(embd_nms) == 1, "Knowledge bases use different embedding models."
  57. embd_mdl = None
  58. if embd_nms:
  59. embd_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.EMBEDDING, embd_nms[0])
  60. self._canvas.set_embedding_model(embd_nms[0])
  61. rerank_mdl = None
  62. if self._param.rerank_id:
  63. rerank_mdl = LLMBundle(kbs[0].tenant_id, LLMType.RERANK, self._param.rerank_id)
  64. if kbs:
  65. kbinfos = settings.retrievaler.retrieval(query, embd_mdl, kbs[0].tenant_id, self._param.kb_ids,
  66. 1, self._param.top_n,
  67. self._param.similarity_threshold, 1 - self._param.keywords_similarity_weight,
  68. aggs=False, rerank_mdl=rerank_mdl,
  69. rank_feature=label_question(query, kbs))
  70. else:
  71. kbinfos = {"chunks": [], "doc_aggs": []}
  72. if self._param.use_kg and kbs:
  73. ck = settings.kg_retrievaler.retrieval(query,
  74. [kbs[0].tenant_id],
  75. self._param.kb_ids,
  76. embd_mdl,
  77. LLMBundle(kbs[0].tenant_id, LLMType.CHAT))
  78. if ck["content_with_weight"]:
  79. kbinfos["chunks"].insert(0, ck)
  80. if self._param.tavily_api_key:
  81. tav = Tavily(self._param.tavily_api_key)
  82. tav_res = tav.retrieve_chunks(query)
  83. kbinfos["chunks"].extend(tav_res["chunks"])
  84. kbinfos["doc_aggs"].extend(tav_res["doc_aggs"])
  85. if not kbinfos["chunks"]:
  86. df = Retrieval.be_output("")
  87. if self._param.empty_response and self._param.empty_response.strip():
  88. df["empty_response"] = self._param.empty_response
  89. return df
  90. df = pd.DataFrame({"content": kb_prompt(kbinfos, 200000), "chunks": json.dumps(kbinfos["chunks"])})
  91. logging.debug("{} {}".format(query, df))
  92. return df.dropna()