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. from graph.settings import DEBUG
  22. class CategorizeParam(GenerateParam):
  23. """
  24. Define the Categorize component parameters.
  25. """
  26. def __init__(self):
  27. super().__init__()
  28. self.category_description = {}
  29. self.prompt = ""
  30. def check(self):
  31. super().check()
  32. self.check_empty(self.category_description, "Category examples")
  33. def get_prompt(self):
  34. cate_lines = []
  35. for c, desc in self.category_description.items():
  36. for l in desc["examples"].split("\n"):
  37. if not l: continue
  38. cate_lines.append("Question: {}\tCategory: {}".format(l, c))
  39. descriptions = []
  40. for c, desc in self.category_description.items():
  41. if desc.get("description"):
  42. descriptions.append(
  43. "--------------------\nCategory: {}\nDescription: {}\n".format(c, desc["description"]))
  44. self.prompt = """
  45. You're a text classifier. You need to categorize the user’s questions into {} categories,
  46. namely: {}
  47. Here's description of each category:
  48. {}
  49. You could learn from the following examples:
  50. {}
  51. You could learn from the above examples.
  52. Just mention the category names, no need for any additional words.
  53. """.format(
  54. len(self.category_description.keys()),
  55. "/".join(list(self.category_description.keys())),
  56. "\n".join(descriptions),
  57. "- ".join(cate_lines)
  58. )
  59. return self.prompt
  60. class Categorize(Generate, ABC):
  61. component_name = "Categorize"
  62. def _run(self, history, **kwargs):
  63. input = self.get_input()
  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. if DEBUG: print(ans, ":::::::::::::::::::::::::::::::::", input)
  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"])