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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. from api.db import LLMType
  18. from api.db.services.llm_service import LLMBundle
  19. from agent.component import GenerateParam, Generate
  20. from rag.utils import num_tokens_from_string, encoder
  21. class RelevantParam(GenerateParam):
  22. """
  23. Define the Relevant component parameters.
  24. """
  25. def __init__(self):
  26. super().__init__()
  27. self.prompt = ""
  28. self.yes = ""
  29. self.no = ""
  30. def check(self):
  31. super().check()
  32. self.check_empty(self.yes, "[Relevant] 'Yes'")
  33. self.check_empty(self.no, "[Relevant] 'No'")
  34. def get_prompt(self):
  35. self.prompt = """
  36. You are a grader assessing relevance of a retrieved document to a user question.
  37. It does not need to be a stringent test. The goal is to filter out erroneous retrievals.
  38. If the document contains keyword(s) or semantic meaning related to the user question, grade it as relevant.
  39. Give a binary score 'yes' or 'no' score to indicate whether the document is relevant to the question.
  40. No other words needed except 'yes' or 'no'.
  41. """
  42. return self.prompt
  43. class Relevant(Generate, ABC):
  44. component_name = "Relevant"
  45. def _run(self, history, **kwargs):
  46. q = ""
  47. for r, c in self._canvas.history[::-1]:
  48. if r == "user":
  49. q = c
  50. break
  51. ans = self.get_input()
  52. ans = " - ".join(ans["content"]) if "content" in ans else ""
  53. if not ans:
  54. return Relevant.be_output(self._param.no)
  55. ans = "Documents: \n" + ans
  56. ans = f"Question: {q}\n" + ans
  57. chat_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.CHAT, self._param.llm_id)
  58. if num_tokens_from_string(ans) >= chat_mdl.max_length - 4:
  59. ans = encoder.decode(encoder.encode(ans)[:chat_mdl.max_length - 4])
  60. ans = chat_mdl.chat(self._param.get_prompt(), [{"role": "user", "content": ans}],
  61. self._param.gen_conf())
  62. print(ans, ":::::::::::::::::::::::::::::::::")
  63. if ans.lower().find("yes") >= 0:
  64. return Relevant.be_output(self._param.yes)
  65. if ans.lower().find("no") >= 0:
  66. return Relevant.be_output(self._param.no)
  67. assert False, f"Relevant component got: {ans}"