Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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.language = ""
  29. def check(self):
  30. super().check()
  31. def get_prompt(self, conv, language, query):
  32. prompt = """
  33. Role: A helpful assistant
  34. Task: Generate a full user question that would follow the conversation.
  35. Requirements & Restrictions:
  36. - Text generated MUST be in the same language of the original user's question.
  37. - If the user's latest question is completely, don't do anything, just return the original question.
  38. - DON'T generate anything except a refined question."""
  39. if language:
  40. prompt += f"""
  41. - Text generated MUST be in {language}"""
  42. prompt += f"""
  43. ######################
  44. -Examples-
  45. ######################
  46. # Example 1
  47. ## Conversation
  48. USER: What is the name of Donald Trump's father?
  49. ASSISTANT: Fred Trump.
  50. USER: And his mother?
  51. ###############
  52. Output: What's the name of Donald Trump's mother?
  53. ------------
  54. # Example 2
  55. ## Conversation
  56. USER: What is the name of Donald Trump's father?
  57. ASSISTANT: Fred Trump.
  58. USER: And his mother?
  59. ASSISTANT: Mary Trump.
  60. USER: What's her full name?
  61. ###############
  62. Output: What's the full name of Donald Trump's mother Mary Trump?
  63. ######################
  64. # Real Data
  65. ## Conversation
  66. {conv}
  67. ###############
  68. """
  69. return prompt
  70. class RewriteQuestion(Generate, ABC):
  71. component_name = "RewriteQuestion"
  72. def _run(self, history, **kwargs):
  73. hist = self._canvas.get_history(self._param.message_history_window_size)
  74. query = self.get_input()
  75. query = str(query["content"][0]) if "content" in query else ""
  76. conv = []
  77. for m in hist:
  78. if m["role"] not in ["user", "assistant"]:
  79. continue
  80. conv.append("{}: {}".format(m["role"].upper(), m["content"]))
  81. conv = "\n".join(conv)
  82. chat_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.CHAT, self._param.llm_id)
  83. ans = chat_mdl.chat(self._param.get_prompt(conv, self.gen_lang(self._param.language), query),
  84. [{"role": "user", "content": "Output: "}], self._param.gen_conf())
  85. self._canvas.history.pop()
  86. self._canvas.history.append(("user", ans))
  87. return RewriteQuestion.be_output(ans)
  88. @staticmethod
  89. def gen_lang(language):
  90. # convert code lang to language word for the prompt
  91. language_dict = {'af': 'Afrikaans', 'ak': 'Akan', 'sq': 'Albanian', 'ws': 'Samoan', 'am': 'Amharic',
  92. 'ar': 'Arabic', 'hy': 'Armenian', 'az': 'Azerbaijani', 'eu': 'Basque', 'be': 'Belarusian',
  93. 'bem': 'Bemba', 'bn': 'Bengali', 'bh': 'Bihari',
  94. 'xx-bork': 'Bork', 'bs': 'Bosnian', 'br': 'Breton', 'bg': 'Bulgarian', 'bt': 'Bhutani',
  95. 'km': 'Cambodian', 'ca': 'Catalan', 'chr': 'Cherokee', 'ny': 'Chichewa', 'zh-cn': 'Chinese',
  96. 'zh-tw': 'Chinese', 'co': 'Corsican',
  97. 'hr': 'Croatian', 'cs': 'Czech', 'da': 'Danish', 'nl': 'Dutch', 'xx-elmer': 'Elmer',
  98. 'en': 'English', 'eo': 'Esperanto', 'et': 'Estonian', 'ee': 'Ewe', 'fo': 'Faroese',
  99. 'tl': 'Filipino', 'fi': 'Finnish', 'fr': 'French',
  100. 'fy': 'Frisian', 'gaa': 'Ga', 'gl': 'Galician', 'ka': 'Georgian', 'de': 'German',
  101. 'el': 'Greek', 'kl': 'Greenlandic', 'gn': 'Guarani', 'gu': 'Gujarati', 'xx-hacker': 'Hacker',
  102. 'ht': 'Haitian Creole', 'ha': 'Hausa', 'haw': 'Hawaiian',
  103. 'iw': 'Hebrew', 'hi': 'Hindi', 'hu': 'Hungarian', 'is': 'Icelandic', 'ig': 'Igbo',
  104. 'id': 'Indonesian', 'ia': 'Interlingua', 'ga': 'Irish', 'it': 'Italian', 'ja': 'Japanese',
  105. 'jw': 'Javanese', 'kn': 'Kannada', 'kk': 'Kazakh', 'rw': 'Kinyarwanda',
  106. 'rn': 'Kirundi', 'xx-klingon': 'Klingon', 'kg': 'Kongo', 'ko': 'Korean', 'kri': 'Krio',
  107. 'ku': 'Kurdish', 'ckb': 'Kurdish (Sorani)', 'ky': 'Kyrgyz', 'lo': 'Laothian', 'la': 'Latin',
  108. 'lv': 'Latvian', 'ln': 'Lingala', 'lt': 'Lithuanian',
  109. 'loz': 'Lozi', 'lg': 'Luganda', 'ach': 'Luo', 'mk': 'Macedonian', 'mg': 'Malagasy',
  110. 'ms': 'Malay', 'ml': 'Malayalam', 'mt': 'Maltese', 'mv': 'Maldivian', 'mi': 'Maori',
  111. 'mr': 'Marathi', 'mfe': 'Mauritian Creole', 'mo': 'Moldavian', 'mn': 'Mongolian',
  112. 'sr-me': 'Montenegrin', 'my': 'Burmese', 'ne': 'Nepali', 'pcm': 'Nigerian Pidgin',
  113. 'nso': 'Northern Sotho', 'no': 'Norwegian', 'nn': 'Norwegian Nynorsk', 'oc': 'Occitan',
  114. 'or': 'Oriya', 'om': 'Oromo', 'ps': 'Pashto', 'fa': 'Persian',
  115. 'xx-pirate': 'Pirate', 'pl': 'Polish', 'pt': 'Portuguese', 'pt-br': 'Portuguese (Brazilian)',
  116. 'pt-pt': 'Portuguese (Portugal)', 'pa': 'Punjabi', 'qu': 'Quechua', 'ro': 'Romanian',
  117. 'rm': 'Romansh', 'nyn': 'Runyankole', 'ru': 'Russian', 'gd': 'Scots Gaelic',
  118. 'sr': 'Serbian', 'sh': 'Serbo-Croatian', 'st': 'Sesotho', 'tn': 'Setswana',
  119. 'crs': 'Seychellois Creole', 'sn': 'Shona', 'sd': 'Sindhi', 'si': 'Sinhalese', 'sk': 'Slovak',
  120. 'sl': 'Slovenian', 'so': 'Somali', 'es': 'Spanish', 'es-419': 'Spanish (Latin America)',
  121. 'su': 'Sundanese',
  122. 'sw': 'Swahili', 'sv': 'Swedish', 'tg': 'Tajik', 'ta': 'Tamil', 'tt': 'Tatar', 'te': 'Telugu',
  123. 'th': 'Thai', 'ti': 'Tigrinya', 'to': 'Tongan', 'lua': 'Tshiluba', 'tum': 'Tumbuka',
  124. 'tr': 'Turkish', 'tk': 'Turkmen', 'tw': 'Twi',
  125. 'ug': 'Uyghur', 'uk': 'Ukrainian', 'ur': 'Urdu', 'uz': 'Uzbek', 'vu': 'Vanuatu',
  126. 'vi': 'Vietnamese', 'cy': 'Welsh', 'wo': 'Wolof', 'xh': 'Xhosa', 'yi': 'Yiddish',
  127. 'yo': 'Yoruba', 'zu': 'Zulu'}
  128. if language in language_dict:
  129. return language_dict[language]
  130. else:
  131. return ""