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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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. from api.db import LLMType
  19. from api.db.services.llm_service import LLMBundle
  20. from agent.component import GenerateParam, Generate
  21. class RewriteQuestionParam(GenerateParam):
  22. """
  23. Define the QuestionRewrite component parameters.
  24. """
  25. def __init__(self):
  26. super().__init__()
  27. self.temperature = 0.9
  28. self.prompt = ""
  29. self.loop = 1
  30. def check(self):
  31. super().check()
  32. def get_prompt(self, conv):
  33. self.prompt = """
  34. You are an expert at query expansion to generate a paraphrasing of a question.
  35. I can't retrieval relevant information from the knowledge base by using user's question directly.
  36. You need to expand or paraphrase user's question by multiple ways such as using synonyms words/phrase,
  37. writing the abbreviation in its entirety, adding some extra descriptions or explanations,
  38. changing the way of expression, translating the original question into another language (English/Chinese), etc.
  39. And return 5 versions of question and one is from translation.
  40. Just list the question. No other words are needed.
  41. """
  42. return f"""
  43. Role: A helpful assistant
  44. Task: Generate a full user question that would follow the conversation.
  45. Requirements & Restrictions:
  46. - Text generated MUST be in the same language of the original user's question.
  47. - If the user's latest question is completely, don't do anything, just return the original question.
  48. - DON'T generate anything except a refined question.
  49. ######################
  50. -Examples-
  51. ######################
  52. # Example 1
  53. ## Conversation
  54. USER: What is the name of Donald Trump's father?
  55. ASSISTANT: Fred Trump.
  56. USER: And his mother?
  57. ###############
  58. Output: What's the name of Donald Trump's mother?
  59. ------------
  60. # Example 2
  61. ## Conversation
  62. USER: What is the name of Donald Trump's father?
  63. ASSISTANT: Fred Trump.
  64. USER: And his mother?
  65. ASSISTANT: Mary Trump.
  66. User: What's her full name?
  67. ###############
  68. Output: What's the full name of Donald Trump's mother Mary Trump?
  69. ######################
  70. # Real Data
  71. ## Conversation
  72. {conv}
  73. ###############
  74. """
  75. return self.prompt
  76. class RewriteQuestion(Generate, ABC):
  77. component_name = "RewriteQuestion"
  78. def _run(self, history, **kwargs):
  79. if not hasattr(self, "_loop"):
  80. setattr(self, "_loop", 0)
  81. if self._loop >= self._param.loop:
  82. self._loop = 0
  83. raise Exception("Sorry! Nothing relevant found.")
  84. self._loop += 1
  85. hist = self._canvas.get_history(4)
  86. conv = []
  87. for m in hist:
  88. if m["role"] not in ["user", "assistant"]:
  89. continue
  90. conv.append("{}: {}".format(m["role"].upper(), m["content"]))
  91. conv = "\n".join(conv)
  92. chat_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.CHAT, self._param.llm_id)
  93. ans = chat_mdl.chat(self._param.get_prompt(conv), [{"role": "user", "content": "Output: "}],
  94. self._param.gen_conf())
  95. self._canvas.history.pop()
  96. self._canvas.history.append(("user", ans))
  97. logging.debug(ans)
  98. return RewriteQuestion.be_output(ans)