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.

categorize.py 4.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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 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:
  34. raise ValueError("[Categorize] Category name can not be empty!")
  35. if not v.get("to"):
  36. raise ValueError(f"[Categorize] 'To' of category {k} can not be empty!")
  37. def get_prompt(self, chat_hist):
  38. cate_lines = []
  39. for c, desc in self.category_description.items():
  40. for line in desc.get("examples", "").split("\n"):
  41. if not line:
  42. continue
  43. cate_lines.append("USER: {}\nCategory: {}".format(line, c))
  44. descriptions = []
  45. for c, desc in self.category_description.items():
  46. if desc.get("description"):
  47. descriptions.append(
  48. "\nCategory: {}\nDescription: {}".format(c, desc["description"]))
  49. self.prompt = """
  50. Role: You're a text classifier.
  51. Task: You need to categorize the user’s questions into {} categories, namely: {}
  52. Here's description of each category:
  53. {}
  54. You could learn from the following examples:
  55. {}
  56. You could learn from the above examples.
  57. Requirements:
  58. - Just mention the category names, no need for any additional words.
  59. ---- Real Data ----
  60. USER: {}\n
  61. """.format(
  62. len(self.category_description.keys()),
  63. "/".join(list(self.category_description.keys())),
  64. "\n".join(descriptions),
  65. "\n\n- ".join(cate_lines),
  66. chat_hist
  67. )
  68. return self.prompt
  69. class Categorize(Generate, ABC):
  70. component_name = "Categorize"
  71. def _run(self, history, **kwargs):
  72. input = self.get_input()
  73. input = " - ".join(input["content"]) if "content" in input else ""
  74. chat_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.CHAT, self._param.llm_id)
  75. self._canvas.set_component_infor(self._id, {"prompt":self._param.get_prompt(input),"messages": [{"role": "user", "content": "\nCategory: "}],"conf": self._param.gen_conf()})
  76. ans = chat_mdl.chat(self._param.get_prompt(input), [{"role": "user", "content": "\nCategory: "}],
  77. self._param.gen_conf())
  78. logging.debug(f"input: {input}, answer: {str(ans)}")
  79. # Count the number of times each category appears in the answer.
  80. category_counts = {}
  81. for c in self._param.category_description.keys():
  82. count = ans.lower().count(c.lower())
  83. category_counts[c] = count
  84. # If a category is found, return the category with the highest count.
  85. if any(category_counts.values()):
  86. max_category = max(category_counts.items(), key=lambda x: x[1])
  87. return Categorize.be_output(self._param.category_description[max_category[0]]["to"])
  88. return Categorize.be_output(list(self._param.category_description.items())[-1][1]["to"])
  89. def debug(self, **kwargs):
  90. df = self._run([], **kwargs)
  91. cpn_id = df.iloc[0, 0]
  92. return Categorize.be_output(self._canvas.get_component_name(cpn_id))