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.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 re
  17. from abc import ABC
  18. from api.db import LLMType
  19. from api.db.services.llm_service import LLMBundle
  20. from graph.component import GenerateParam, Generate
  21. from graph.settings import DEBUG
  22. class KeywordExtractParam(GenerateParam):
  23. """
  24. Define the KeywordExtract component parameters.
  25. """
  26. def __init__(self):
  27. super().__init__()
  28. self.temperature = 0.5
  29. self.prompt = ""
  30. self.topn = 1
  31. def check(self):
  32. super().check()
  33. def get_prompt(self):
  34. self.prompt = """
  35. - Role: You're a question analyzer.
  36. - Requirements:
  37. - Summarize user's question, and give top %s important keyword/phrase.
  38. - Use comma as a delimiter to separate keywords/phrases.
  39. - Answer format: (in language of user's question)
  40. - keyword:
  41. """%self.topn
  42. return self.prompt
  43. class KeywordExtract(Generate, ABC):
  44. component_name = "RewriteQuestion"
  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. chat_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.CHAT, self._param.llm_id)
  52. ans = chat_mdl.chat(self._param.get_prompt(), [{"role": "user", "content": q}],
  53. self._param.gen_conf())
  54. ans = re.sub(r".*keyword:", "", ans).strip()
  55. if DEBUG: print(ans, ":::::::::::::::::::::::::::::::::")
  56. return KeywordExtract.be_output(ans)