Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

categorize.py 3.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 agent.settings import DEBUG
  21. class CategorizeParam(GenerateParam):
  22. """
  23. Define the Categorize component parameters.
  24. """
  25. def __init__(self):
  26. super().__init__()
  27. self.category_description = {}
  28. self.prompt = ""
  29. def check(self):
  30. super().check()
  31. self.check_empty(self.category_description, "[Categorize] Category examples")
  32. for k, v in self.category_description.items():
  33. if not k: raise ValueError(f"[Categorize] Category name can not be empty!")
  34. if not v.get("to"): raise ValueError(f"[Categorize] 'To' of category {k} can not be empty!")
  35. def get_prompt(self):
  36. cate_lines = []
  37. for c, desc in self.category_description.items():
  38. for l in desc.get("examples", "").split("\n"):
  39. if not l: continue
  40. cate_lines.append("Question: {}\tCategory: {}".format(l, c))
  41. descriptions = []
  42. for c, desc in self.category_description.items():
  43. if desc.get("description"):
  44. descriptions.append(
  45. "--------------------\nCategory: {}\nDescription: {}\n".format(c, desc["description"]))
  46. self.prompt = """
  47. You're a text classifier. You need to categorize the user’s questions into {} categories,
  48. namely: {}
  49. Here's description of each category:
  50. {}
  51. You could learn from the following examples:
  52. {}
  53. You could learn from the above examples.
  54. Just mention the category names, no need for any additional words.
  55. """.format(
  56. len(self.category_description.keys()),
  57. "/".join(list(self.category_description.keys())),
  58. "\n".join(descriptions),
  59. "- ".join(cate_lines)
  60. )
  61. return self.prompt
  62. class Categorize(Generate, ABC):
  63. component_name = "Categorize"
  64. def _run(self, history, **kwargs):
  65. input = self.get_input()
  66. input = "Question: " + ("; ".join(input["content"]) if "content" in input else "") + "Category: "
  67. chat_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.CHAT, self._param.llm_id)
  68. ans = chat_mdl.chat(self._param.get_prompt(), [{"role": "user", "content": input}],
  69. self._param.gen_conf())
  70. if DEBUG: print(ans, ":::::::::::::::::::::::::::::::::", input)
  71. for c in self._param.category_description.keys():
  72. if ans.lower().find(c.lower()) >= 0:
  73. return Categorize.be_output(self._param.category_description[c]["to"])
  74. return Categorize.be_output(self._param.category_description.items()[-1][1]["to"])