Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

categorize.py 3.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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):
  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("Question: {}\tCategory: {}".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. """.format(
  59. len(self.category_description.keys()),
  60. "/".join(list(self.category_description.keys())),
  61. "\n".join(descriptions),
  62. "- ".join(cate_lines)
  63. )
  64. return self.prompt
  65. class Categorize(Generate, ABC):
  66. component_name = "Categorize"
  67. def _run(self, history, **kwargs):
  68. input = self.get_input()
  69. input = "Question: " + (list(input["content"])[-1] if "content" in input else "") + "\tCategory: "
  70. chat_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.CHAT, self._param.llm_id)
  71. ans = chat_mdl.chat(self._param.get_prompt(), [{"role": "user", "content": input}],
  72. self._param.gen_conf())
  73. logging.debug(f"input: {input}, answer: {str(ans)}")
  74. for c in self._param.category_description.keys():
  75. if ans.lower().find(c.lower()) >= 0:
  76. return Categorize.be_output(self._param.category_description[c]["to"])
  77. return Categorize.be_output(list(self._param.category_description.items())[-1][1]["to"])
  78. def debug(self, **kwargs):
  79. df = self._run([], **kwargs)
  80. cpn_id = df.iloc[0, 0]
  81. return Categorize.be_output(self._canvas.get_compnent_name(cpn_id))