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 3.1KB

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. import pandas as pd
  18. from api.db import LLMType
  19. from api.db.services.llm_service import LLMBundle
  20. from graph.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, "Category examples")
  32. def get_prompt(self):
  33. cate_lines = []
  34. for c, desc in self.category_description.items():
  35. for l in desc["examples"].split("\n"):
  36. if not l: continue
  37. cate_lines.append("Question: {}\tCategory: {}".format(l, c))
  38. descriptions = []
  39. for c, desc in self.category_description.items():
  40. if desc.get("description"):
  41. descriptions.append(
  42. "--------------------\nCategory: {}\nDescription: {}\n".format(c, desc["description"]))
  43. self.prompt = """
  44. You're a text classifier. You need to categorize the user’s questions into {} categories,
  45. namely: {}
  46. Here's description of each category:
  47. {}
  48. You could learn from the following examples:
  49. {}
  50. You could learn from the above examples.
  51. Just mention the category names, no need for any additional words.
  52. """.format(
  53. len(self.category_description.keys()),
  54. "/".join(list(self.category_description.keys())),
  55. "\n".join(descriptions),
  56. "- ".join(cate_lines)
  57. )
  58. return self.prompt
  59. class Categorize(Generate, ABC):
  60. component_name = "Categorize"
  61. def _run(self, history, **kwargs):
  62. input = self.get_input()
  63. print(input, "DDDDDDDDDDDDDDDDDDDDDDDDDDDDD")
  64. input = "Question: " + ("; ".join(input["content"]) if "content" in input else "") + "Category: "
  65. chat_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.CHAT, self._param.llm_id)
  66. ans = chat_mdl.chat(self._param.get_prompt(), [{"role": "user", "content": input}],
  67. self._param.gen_conf())
  68. print(ans, ":::::::::::::::::::::::::::::::::")
  69. for c in self._param.category_description.keys():
  70. if ans.lower().find(c.lower()) >= 0:
  71. return Categorize.be_output(self._param.category_description[c]["to"])
  72. return Categorize.be_output(self._param.category_description.items()[-1][1]["to"])