選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

switch.py 5.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  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. from agent.component.base import ComponentBase, ComponentParamBase
  18. class SwitchParam(ComponentParamBase):
  19. """
  20. Define the Switch component parameters.
  21. """
  22. def __init__(self):
  23. super().__init__()
  24. """
  25. {
  26. "logical_operator" : "and | or"
  27. "items" : [
  28. {"cpn_id": "categorize:0", "operator": "contains", "value": ""},
  29. {"cpn_id": "categorize:0", "operator": "contains", "value": ""},...],
  30. "to": ""
  31. }
  32. """
  33. self.conditions = []
  34. self.end_cpn_id = "answer:0"
  35. self.operators = ['contains', 'not contains', 'start with', 'end with', 'empty', 'not empty', '=', '≠', '>',
  36. '<', '≥', '≤']
  37. def check(self):
  38. self.check_empty(self.conditions, "[Switch] conditions")
  39. for cond in self.conditions:
  40. if not cond["to"]: raise ValueError(f"[Switch] 'To' can not be empty!")
  41. if cond["logical_operator"] not in ["and", "or"] and len(cond["items"]) > 1:
  42. raise ValueError(f"[Switch] Please set logical_operator correctly!")
  43. class Switch(ComponentBase, ABC):
  44. component_name = "Switch"
  45. def _run(self, history, **kwargs):
  46. for cond in self._param.conditions:
  47. if len(cond["items"]) == 1:
  48. out = self._canvas.get_component(cond["items"][0]["cpn_id"])["obj"].output()[1]
  49. cpn_input = "" if "content" not in out.columns else " ".join(out["content"])
  50. if self.process_operator(cpn_input, cond["items"][0]["operator"], cond["items"][0]["value"]):
  51. return Switch.be_output(cond["to"])
  52. continue
  53. if cond["logical_operator"] == "and":
  54. res = True
  55. for item in cond["items"]:
  56. out = self._canvas.get_component(item["cpn_id"])["obj"].output()[1]
  57. cpn_input = "" if "content" not in out.columns else " ".join(out["content"])
  58. if not self.process_operator(cpn_input, item["operator"], item["value"]):
  59. res = False
  60. break
  61. if res:
  62. return Switch.be_output(cond["to"])
  63. continue
  64. res = False
  65. for item in cond["items"]:
  66. out = self._canvas.get_component(item["cpn_id"])["obj"].output()[1]
  67. cpn_input = "" if "content" not in out.columns else " ".join(out["content"])
  68. if self.process_operator(cpn_input, item["operator"], item["value"]):
  69. res = True
  70. break
  71. if res:
  72. return Switch.be_output(cond["to"])
  73. return Switch.be_output(self._param.end_cpn_id)
  74. def process_operator(self, input: str, operator: str, value: str) -> bool:
  75. if not isinstance(input, str) or not isinstance(value, str):
  76. raise ValueError('Invalid input or value type: string')
  77. if operator == "contains":
  78. return True if value.lower() in input.lower() else False
  79. elif operator == "not contains":
  80. return True if value.lower() not in input.lower() else False
  81. elif operator == "start with":
  82. return True if input.lower().startswith(value.lower()) else False
  83. elif operator == "end with":
  84. return True if input.lower().endswith(value.lower()) else False
  85. elif operator == "empty":
  86. return True if not input else False
  87. elif operator == "not empty":
  88. return True if input else False
  89. elif operator == "=":
  90. return True if input == value else False
  91. elif operator == "≠":
  92. return True if input != value else False
  93. elif operator == ">":
  94. try:
  95. return True if float(input) > float(value) else False
  96. except Exception as e:
  97. return True if input > value else False
  98. elif operator == "<":
  99. try:
  100. return True if float(input) < float(value) else False
  101. except Exception as e:
  102. return True if input < value else False
  103. elif operator == "≥":
  104. try:
  105. return True if float(input) >= float(value) else False
  106. except Exception as e:
  107. return True if input >= value else False
  108. elif operator == "≤":
  109. try:
  110. return True if float(input) <= float(value) else False
  111. except Exception as e:
  112. return True if input <= value else False
  113. raise ValueError('Not supported operator' + operator)