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.

rewrite.py 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. class RewriteQuestionParam(GenerateParam):
  21. """
  22. Define the QuestionRewrite component parameters.
  23. """
  24. def __init__(self):
  25. super().__init__()
  26. self.temperature = 0.9
  27. self.prompt = ""
  28. self.loop = 1
  29. def check(self):
  30. super().check()
  31. def get_prompt(self):
  32. self.prompt = """
  33. You are an expert at query expansion to generate a paraphrasing of a question.
  34. I can't retrieval relevant information from the knowledge base by using user's question directly.
  35. You need to expand or paraphrase user's question by multiple ways such as using synonyms words/phrase,
  36. writing the abbreviation in its entirety, adding some extra descriptions or explanations,
  37. changing the way of expression, translating the original question into another language (English/Chinese), etc.
  38. And return 5 versions of question and one is from translation.
  39. Just list the question. No other words are needed.
  40. """
  41. return self.prompt
  42. class RewriteQuestion(Generate, ABC):
  43. component_name = "RewriteQuestion"
  44. def _run(self, history, **kwargs):
  45. if not hasattr(self, "_loop"):
  46. setattr(self, "_loop", 0)
  47. if self._loop >= self._param.loop:
  48. self._loop = 0
  49. raise Exception("Maximum loop time exceeds. Can't find relevant information.")
  50. self._loop += 1
  51. q = "Question: "
  52. for r, c in self._canvas.history[::-1]:
  53. if r == "user":
  54. q += c
  55. break
  56. chat_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.CHAT, self._param.llm_id)
  57. ans = chat_mdl.chat(self._param.get_prompt(), [{"role": "user", "content": q}],
  58. self._param.gen_conf())
  59. print(ans, ":::::::::::::::::::::::::::::::::")
  60. return RewriteQuestion.be_output(ans)