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.

cite.py 2.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 CiteParam(ComponentParamBase):
  24. """
  25. Define the Retrieval component parameters.
  26. """
  27. def __init__(self):
  28. super().__init__()
  29. self.cite_sources = []
  30. def check(self):
  31. self.check_empty(self.cite_source, "Please specify where you want to cite from.")
  32. class Cite(ComponentBase, ABC):
  33. component_name = "Cite"
  34. def _run(self, history, **kwargs):
  35. input = "\n- ".join(self.get_input()["content"])
  36. sources = [self._canvas.get_component(cpn_id).output()[1] for cpn_id in self._param.cite_source]
  37. query = []
  38. for role, cnt in history[::-1][:self._param.message_history_window_size]:
  39. if role != "user":continue
  40. query.append(cnt)
  41. query = "\n".join(query)
  42. kbs = KnowledgebaseService.get_by_ids(self._param.kb_ids)
  43. if not kbs:
  44. raise ValueError("Can't find knowledgebases by {}".format(self._param.kb_ids))
  45. embd_nms = list(set([kb.embd_id for kb in kbs]))
  46. assert len(embd_nms) == 1, "Knowledge bases use different embedding models."
  47. embd_mdl = LLMBundle(kbs[0].tenant_id, LLMType.EMBEDDING, embd_nms[0])
  48. rerank_mdl = None
  49. if self._param.rerank_id:
  50. rerank_mdl = LLMBundle(kbs[0].tenant_id, LLMType.RERANK, self._param.rerank_id)
  51. kbinfos = retrievaler.retrieval(query, embd_mdl, kbs[0].tenant_id, self._param.kb_ids,
  52. 1, self._param.top_n,
  53. self._param.similarity_threshold, 1 - self._param.keywords_similarity_weight,
  54. aggs=False, rerank_mdl=rerank_mdl)
  55. if not kbinfos["chunks"]: return pd.DataFrame()
  56. df = pd.DataFrame(kbinfos["chunks"])
  57. df["content"] = df["content_with_weight"]
  58. del df["content_with_weight"]
  59. return df