utils.ts


Overview

The utils.ts file provides a comprehensive set of utility functions primarily focused on managing and transforming graph-based data structures that represent workflows composed of nodes and edges. These workflows are related to operators such as Agent, Categorize, Tool, Note, and others in a DSL (Domain Specific Language) environment, likely for a flowchart or pipeline editor interface.

The file contains utilities for:

This file interacts closely with types and interfaces representing nodes, edges, and operator forms, and it is used in the context of a React-based flow management system (e.g., using @xyflow/react).


Detailed Descriptions

Imports and Dependencies


Functions and Exports


buildAgentExceptionGoto(edges: Edge[], nodeId: string): string[]

Filters edges starting from a given node's "AgentException" handle and returns the list of target node IDs.


buildComponentDownstreamOrUpstream(edges: Edge[], nodeId: string, isBuildDownstream = true, nodes: Node[]): string[]

Builds either downstream or upstream node IDs connected to a given node, with specific filtering rules for Agent nodes.


removeUselessDataInTheOperator(operatorName: string, params: Record<string, unknown>): Record<string, unknown>

Curried function cleaning operator parameters by removing unnecessary fields, specifically for Generate and Categorize operators.


buildAgentTools(edges: Edge[], nodes: Node[], nodeId: string): {params: IAgentForm, name?: string, id?: string}

Recursively gathers tools connected under an Agent node, including nested sub-agents connected via the "AgentBottom" handle.


filterTargetsBySourceHandleId(edges: Edge[], handleId: string): string[]

Filters edges by a specific source handle ID and returns target node IDs.


buildCategorize(edges: Edge[], nodes: Node[], nodeId: string): ICategorizeForm

Constructs a Categorize form parameter object by processing edges and nodes, syncing category items with edges.


buildOperatorParams(operatorName: string): (params: any) => any

Creates a pipeline function for processing operator parameters, currently applying removeUselessDataInTheOperator.


isBottomSubAgent(edges: Edge[], nodeId?: string): boolean

Determines if a node is a bottom sub-agent by checking if it is the target of an edge with "AgentTop" handle.


buildDslComponentsByGraph(nodes: RAGFlowNodeType[], edges: Edge[], oldDslComponents: DSLComponents): DSLComponents

Main builder function that constructs DSL components from the graph nodes and edges.


receiveMessageError(res: any): boolean

Simple utility to check if a message response contains an error based on HTTP status and response code.


replaceIdWithText(obj: Record<string, unknown> | unknown[] | unknown, getNameById: (id?: string) => string | undefined): unknown

Recursively replaces string IDs in an object with their corresponding text labels using a provided lookup function.


isEdgeEqual(previous: Edge, current: Edge): boolean

Checks whether two edges are equal based on source, target, and source handle.


buildNewPositionMap(currentKeys: string[], previousPositionMap: Record<string, IPosition>): {intersectionKeys: string[], newPositionMap: Record<string, IPosition>}

Computes a new position map for nodes, attempting to reuse existing positions and assigning new positions from predefined anchor points for new keys.


isKeysEqual(currentKeys: string[], previousKeys: string[]): boolean

Checks if two arrays of keys are equal (ignoring order).


getOperatorIndex(handleTitle: string): string | undefined

Extracts the index (assumed last word) from a handle title string.


getOtherFieldValues(form: FormInstance, formListName = 'items', field: FormListFieldData, latestField: string): any[]

Returns values of a specific field from all form list items except the current one.


generateSwitchHandleText(idx: number): string

Generates switch case handle text like "Case 1".


getNodeDragHandle(nodeType?: string): string | undefined

Returns a CSS selector for the drag handle of a node if applicable.


generateNodeNamesWithIncreasingIndex(name: string, nodes: RAGFlowNodeType[]): string

Generates a new node name by incrementing index suffix to avoid collisions.


duplicateNodeForm(nodeData?: RAGFlowNodeType['data']): RAGFlowNodeType['data']

Creates a deep copy of node form data, removing downstream links for Categorize and Relevant operators to avoid duplicating connections.


getDrawerWidth(): string | number

Returns drawer width based on window size, responsive design.


needsSingleStepDebugging(label: string): boolean

Returns whether an operator supports single-step debugging, excluding operators in NoDebugOperatorsList.


getRelativePositionToIterationNode(nodes: RAGFlowNodeType[], position?: XYPosition): {parentId: string, position: XYPosition} | undefined

Computes the position of a node relative to any Iteration node in the graph.


generateDuplicateNode(position?: XYPosition, label?: string): RAGFlowNodeType

Generates a new node object for duplication with incremented position and unique ID.


convertToStringArray(list?: Array<{ value: string | number | boolean }>): string[]

Converts an array of objects with value property to an array of strings.


convertToObjectArray(list: Array<string | number | boolean>): Array<{ value: string | number | boolean }>

Converts an array of primitive values into objects with value property.


buildCategorizeListFromObject(categorizeItem: ICategorizeItemResult): ICategorizeItem[]

Converts a Categorize form object into a list format.


buildCategorizeObjectFromList(list: ICategorizeItem[]): ICategorizeItemResult

Converts a Categorize items list back into an object keyed by category names.


getAgentNodeTools(agentNode?: RAGFlowNodeType): IAgentForm['tools']

Returns the tools array from an Agent node's form.


getAgentNodeMCP(agentNode?: RAGFlowNodeType): IAgentForm['mcp']

Returns the MCP (multi-component parameter) array from an Agent node's form.


mapEdgeMouseEvent(edges: Edge[], edgeId: string, isHovered: boolean): Edge[]

Returns a new edges array with the specified edge marked as hovered or not.


buildBeginQueryWithObject(inputs: Record<string, BeginQuery>, values: BeginQuery[]): Record<string, BeginQuery>

Builds a new inputs object by merging existing keys with corresponding values from an array.


Important Implementation Details


Interaction With Other System Parts


Usage Example

import { buildDslComponentsByGraph } from './utils';
import { nodes, edges } from './flowData';
import oldDsl from './oldDsl';

// Build the DSL components from current graph state
const newDslComponents = buildDslComponentsByGraph(nodes, edges, oldDsl);

// Now `newDslComponents` can be used to render the DSL or execute workflow logic.

Visual Diagram: Function Flowchart of utils.ts

flowchart TD
  A[buildDslComponentsByGraph] --> B[buildAgentTools]
  A --> C[buildCategorize]
  A --> D[buildComponentDownstreamOrUpstream]
  B --> E[buildAgentTools (recursive)]
  C --> F[filterTargetsBySourceHandleId]
  A --> G[buildOperatorParams]
  G --> H[removeUselessDataInTheOperator]
  A --> I[isBottomSubAgent]
  A --> J[ExcludeOperators list]
  K[replaceIdWithText] -->|Recursive| K
  L[mapEdgeMouseEvent] --> M[edges update]
  N[generateDuplicateNode] --> O[getNodeDragHandle]
  P[buildNewPositionMap] --> Q[CategorizeAnchorPointPositions]
  R[buildCategorizeListFromObject] --> S[convertToObjectArray]
  T[buildCategorizeObjectFromList] --> U[convertToStringArray]

Summary

The utils.ts file is a core utility module for handling graph-based workflow