Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

categorize.py 3.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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: {}\n".format(c, desc["description"]))
  49. self.prompt = """
  50. You're a text classifier. You need to categorize the user’s questions into {} categories,
  51. 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. Just mention the category names, no need for any additional words.
  58. ---- Real Data ----
  59. {}
  60. """.format(
  61. len(self.category_description.keys()),
  62. "/".join(list(self.category_description.keys())),
  63. "\n".join(descriptions),
  64. "- ".join(cate_lines),
  65. chat_hist
  66. )
  67. return self.prompt
  68. class Categorize(Generate, ABC):
  69. component_name = "Categorize"
  70. def _run(self, history, **kwargs):
  71. input = self.get_input()
  72. input = " - ".join(input["content"]) if "content" in input else ""
  73. chat_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.CHAT, self._param.llm_id)
  74. ans = chat_mdl.chat(self._param.get_prompt(input), [{"role": "user", "content": "\nCategory: "}],
  75. self._param.gen_conf())
  76. logging.debug(f"input: {input}, answer: {str(ans)}")
  77. for c in self._param.category_description.keys():
  78. if ans.lower().find(c.lower()) >= 0:
  79. return Categorize.be_output(self._param.category_description[c]["to"])
  80. return Categorize.be_output(list(self._param.category_description.items())[-1][1]["to"])
  81. def debug(self, **kwargs):
  82. df = self._run([], **kwargs)
  83. cpn_id = df.iloc[0, 0]
  84. return Categorize.be_output(self._canvas.get_component_name(cpn_id))