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.

switch.py 5.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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 numbers
  17. import os
  18. from abc import ABC
  19. from typing import Any
  20. from agent.component.base import ComponentBase, ComponentParamBase
  21. from api.utils.api_utils import timeout
  22. class SwitchParam(ComponentParamBase):
  23. """
  24. Define the Switch component parameters.
  25. """
  26. def __init__(self):
  27. super().__init__()
  28. """
  29. {
  30. "logical_operator" : "and | or"
  31. "items" : [
  32. {"cpn_id": "categorize:0", "operator": "contains", "value": ""},
  33. {"cpn_id": "categorize:0", "operator": "contains", "value": ""},...],
  34. "to": ""
  35. }
  36. """
  37. self.conditions = []
  38. self.end_cpn_ids = []
  39. self.operators = ['contains', 'not contains', 'start with', 'end with', 'empty', 'not empty', '=', '≠', '>',
  40. '<', '≥', '≤']
  41. def check(self):
  42. self.check_empty(self.conditions, "[Switch] conditions")
  43. for cond in self.conditions:
  44. if not cond["to"]:
  45. raise ValueError("[Switch] 'To' can not be empty!")
  46. self.check_empty(self.end_cpn_ids, "[Switch] the ELSE/Other destination can not be empty.")
  47. def get_input_form(self) -> dict[str, dict]:
  48. return {
  49. "urls": {
  50. "name": "URLs",
  51. "type": "line"
  52. }
  53. }
  54. class Switch(ComponentBase, ABC):
  55. component_name = "Switch"
  56. @timeout(os.environ.get("COMPONENT_EXEC_TIMEOUT", 3))
  57. def _invoke(self, **kwargs):
  58. for cond in self._param.conditions:
  59. res = []
  60. for item in cond["items"]:
  61. if not item["cpn_id"]:
  62. continue
  63. cpn_v = self._canvas.get_variable_value(item["cpn_id"])
  64. self.set_input_value(item["cpn_id"], cpn_v)
  65. operatee = item.get("value", "")
  66. if isinstance(cpn_v, numbers.Number):
  67. operatee = float(operatee)
  68. res.append(self.process_operator(cpn_v, item["operator"], operatee))
  69. if cond["logical_operator"] != "and" and any(res):
  70. self.set_output("next", [self._canvas.get_component_name(cpn_id) for cpn_id in cond["to"]])
  71. self.set_output("_next", cond["to"])
  72. return
  73. if all(res):
  74. self.set_output("next", [self._canvas.get_component_name(cpn_id) for cpn_id in cond["to"]])
  75. self.set_output("_next", cond["to"])
  76. return
  77. self.set_output("next", [self._canvas.get_component_name(cpn_id) for cpn_id in self._param.end_cpn_ids])
  78. self.set_output("_next", self._param.end_cpn_ids)
  79. def process_operator(self, input: Any, operator: str, value: Any) -> bool:
  80. if operator == "contains":
  81. return True if value.lower() in input.lower() else False
  82. elif operator == "not contains":
  83. return True if value.lower() not in input.lower() else False
  84. elif operator == "start with":
  85. return True if input.lower().startswith(value.lower()) else False
  86. elif operator == "end with":
  87. return True if input.lower().endswith(value.lower()) else False
  88. elif operator == "empty":
  89. return True if not input else False
  90. elif operator == "not empty":
  91. return True if input else False
  92. elif operator == "=":
  93. return True if input == value else False
  94. elif operator == "≠":
  95. return True if input != value else False
  96. elif operator == ">":
  97. try:
  98. return True if float(input) > float(value) else False
  99. except Exception:
  100. return True if input > value else False
  101. elif operator == "<":
  102. try:
  103. return True if float(input) < float(value) else False
  104. except Exception:
  105. return True if input < value else False
  106. elif operator == "≥":
  107. try:
  108. return True if float(input) >= float(value) else False
  109. except Exception:
  110. return True if input >= value else False
  111. elif operator == "≤":
  112. try:
  113. return True if float(input) <= float(value) else False
  114. except Exception:
  115. return True if input <= value else False
  116. raise ValueError('Not supported operator' + operator)
  117. def thoughts(self) -> str:
  118. return "I’m weighing a few options and will pick the next step shortly."