RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
fix(agent): normalize Switch operators and numeric strings (#19987)
Sbaaoui Idriss7ae237ce23ab
diff --git a/agent/component/switch.py b/agent/component/switch.pyindex 8612078a87..4d017d2ed0 100644--- a/agent/component/switch.py+++ b/agent/component/switch.py@@ -13,6 +13,7 @@# See the License for the specific language governing permissions and# limitations under the License.#+import mathimport numbersimport osfrom abc import ABC@@ -75,7 +76,7 @@ class Switch(ComponentBase, ABC):cpn_v = self._canvas.get_variable_value(item["cpn_id"])self.set_input_value(item["cpn_id"], cpn_v)operatee = item.get("value", "")- if isinstance(cpn_v, numbers.Number):+ if item["operator"] in ("=", "≠", "==", "!=", "<>") and isinstance(cpn_v, numbers.Number):operatee = float(operatee)res.append(self.process_operator(cpn_v, item["operator"], operatee))if cond["logical_operator"] != "and" and any(res):@@ -92,6 +93,7 @@ class Switch(ComponentBase, ABC):self.set_output("_next", self._param.end_cpn_ids)def process_operator(self, input: Any, operator: str, value: Any) -> bool:+ operator = {"==": "=", "!=": "≠", "<>": "≠", ">=": "≥", "<=": "≤"}.get(operator, operator)if operator in ("contains", "not contains", "start with", "end with"):input = "" if input is None else str(input)value = "" if value is None else str(value)@@ -111,26 +113,22 @@ class Switch(ComponentBase, ABC):return True if input == value else Falseelif operator == "≠":return True if input != value else False- elif operator == ">":+ elif operator in (">", "<", "≥", "≤"):try:- return True if float(input) > float(value) else False- except Exception:- return True if input > value else False- elif operator == "<":- try:- return True if float(input) < float(value) else False- except Exception:- return True if input < value else False- elif operator == "≥":- try:- return True if float(input) >= float(value) else False- except Exception:- return True if input >= value else False- elif operator == "≤":- try:- return True if float(input) <= float(value) else False- except Exception:- return True if input <= value else False+ if isinstance(input, bool) or isinstance(value, bool):+ raise ValueError+ left, right = float(input), float(value)+ except (TypeError, ValueError, OverflowError) as exc:+ raise ValueError(f'operator "{operator}" requires numeric operands (left={type(input).__name__}, right={type(value).__name__})') from exc+ if not math.isfinite(left) or not math.isfinite(right):+ raise ValueError(f'operator "{operator}" requires numeric operands (left={type(input).__name__}, right={type(value).__name__})')+ if operator == ">":+ return left > right+ if operator == "<":+ return left < right+ if operator == "≥":+ return left >= right+ return left <= rightraise ValueError(f"Not supported operator: {operator}")diff --git a/internal/agent/component/switch.go b/internal/agent/component/switch.goindex 8b947edd67..e2511e73c6 100644--- a/internal/agent/component/switch.go+++ b/internal/agent/component/switch.go@@ -36,6 +36,7 @@ import ("context""fmt""maps"+ "math""strconv""strings"@@ -226,7 +227,7 @@ func normalizeLegacyGroup(group map[string]any) (string, []any) {operator, _ := item["operator"].(string)clause := map[string]any{"left": left,- "op": normalizeLegacySwitchOperator(operator),+ "op": operator,}if v, ok := item["value"]; ok {clause["right"] = v@@ -254,12 +255,16 @@ func legacySwitchLeft(item map[string]any) string {return cpnRef}-func normalizeLegacySwitchOperator(op string) string {+func normalizeSwitchOperator(op string) string {switch op {- case "", "=":+ case "", "=", "==":return "=="- case "<>":+ case "<>", "≠", "!=":return "!="+ case "≥":+ return ">="+ case "≤":+ return "<="default:return op}@@ -347,9 +352,7 @@ func legacySwitchDefaultTarget(merged map[string]any) string {func evaluateClause(clause map[string]any, state *runtime.CanvasState) (bool, error) {left, _ := clause["left"].(string)op, _ := clause["op"].(string)- if op == "" {- op = "=="- }+ op = normalizeSwitchOperator(op)// "empty" / "not empty" don't read `right`.if op == "empty" {@@ -508,24 +511,26 @@ func indexOf(s, sub string) int {// is a string that doesn't parse as a number (e.g. an LLM response);// numeric operators will then error out with a clear message.func numericize(v any) (float64, bool) {+ var n float64switch x := v.(type) {case int:- return float64(x), true+ n = float64(x)case int64:- return float64(x), true+ n = float64(x)case float64:- return x, true+ n = xcase float32:- return float64(x), true+ n = float64(x)case string:f, err := strconv.ParseFloat(x, 64)if err != nil {return 0, false}- return f, true+ n = fdefault:return 0, false}+ return n, !math.IsNaN(n) && !math.IsInf(n, 0)}// isEmptyValue reports whether a value is "empty" by the canvas DSLdiff --git a/web/src/constants/agent.tsx b/web/src/constants/agent.tsxindex 5152dd5814..f4c10afe80 100644--- a/web/src/constants/agent.tsx+++ b/web/src/constants/agent.tsx@@ -162,6 +162,21 @@ export enum ComparisonOperator {NotIn = 'not in',}+export const CanvasSwitchOperators: ComparisonOperator[] = [+ ComparisonOperator.Equal,+ ComparisonOperator.NotEqual,+ ComparisonOperator.GreatThan,+ ComparisonOperator.GreatEqual,+ ComparisonOperator.LessThan,+ ComparisonOperator.LessEqual,+ ComparisonOperator.Contains,+ ComparisonOperator.NotContains,+ ComparisonOperator.StartWith,+ ComparisonOperator.EndWith,+ ComparisonOperator.Empty,+ ComparisonOperator.NotEmpty,+];+export const SwitchOperatorOptions = [{ value: ComparisonOperator.Equal, label: 'equal', icon: 'equal' },{ value: ComparisonOperator.NotEqual, label: 'notEqual', icon: 'not-equals' },diff --git a/web/src/pages/agent/form/switch-form/index.tsx b/web/src/pages/agent/form/switch-form/index.tsxindex a590bc90f0..48b46f0572 100644--- a/web/src/pages/agent/form/switch-form/index.tsx+++ b/web/src/pages/agent/form/switch-form/index.tsx@@ -11,7 +11,7 @@ import {import { Input } from '@/components/ui/input';import { Separator } from '@/components/ui/separator';import { Textarea } from '@/components/ui/textarea';-import { SwitchLogicOperator } from '@/constants/agent';+import { CanvasSwitchOperators, SwitchLogicOperator } from '@/constants/agent';import { useBuildSwitchOperatorOptions } from '@/hooks/logic-hooks/use-build-operator-options';import { useBuildSwitchLogicOperatorOptions } from '@/hooks/logic-hooks/use-build-options';import { cn } from '@/lib/utils';@@ -142,7 +142,9 @@ function ConditionCards({}: ConditionCardsProps) {const form = useFormContext();- const switchOperatorOptions = useBuildSwitchOperatorOptions();+ const switchOperatorOptions = useBuildSwitchOperatorOptions(+ CanvasSwitchOperators,+ );const name = `${parentName}.${ItemKey}`;@@ -246,7 +248,9 @@ function ConditionCards({function SwitchForm({ node }: IOperatorForm) {const { t } = useTranslation();const values = useValues(node);- const switchOperatorOptions = useBuildSwitchOperatorOptions();+ const switchOperatorOptions = useBuildSwitchOperatorOptions(+ CanvasSwitchOperators,+ );const FormSchema = z.object({conditions: z.array(