use-get-begin-query.tsx
Overview
The file use-get-begin-query.tsx provides a collection of React hooks and utility functions designed to manage, build, and query the data inputs and outputs associated with the "Begin" node in a visual flow-based agent system. It primarily facilitates the extraction, transformation, and presentation of input/output variables and query parameters tied to the initial node of a flow graph.
Key functionalities include:
Extracting and formatting input data from the Begin node for use in forms or queries.
Determining the mode of the Begin node (e.g., Task mode).
Building selectable options for variables and component outputs based on the graph structure.
Validating the safety of Begin node queries with respect to file type inputs.
Providing label lookup utilities for variable and component options.
Filtering nodes and edges to identify upstream dependencies in the flow graph.
The file heavily interacts with the global graph store (useGraphStore), the agent form context (AgentFormContext), and external hooks such as useFetchAgent to access DSL globals.
Detailed Explanations
Imports and Dependencies
React hooks:
useState,useEffect,useMemo,useCallback,useContextUtilities:
lodashfunctions (get,isEmpty)UI & i18n: Ant Design select types,
tfrom i18next for translations, and ReactNode for JSX elements.Custom imports: Agent constants, flow interfaces, operator icons, and store/hooks related to the agent flow graph.
Key Constants and Types
BeginId: Identifier for the Begin node in the graph.
BeginQueryType, Operator, VariableType: Enumerations used to classify query and variable types.
ExcludedNodes: Operators/nodes excluded from some option lists (e.g., Categorize, Note).
StringList: Query types that are mapped as string variables.
Hooks and Functions
1. useSelectBeginNodeDataInputs()
Purpose: Retrieves and builds a list of input data fields for the Begin node.
Returns: An array of formatted input objects derived from the Begin node's form inputs.
Usage:
const inputs = useSelectBeginNodeDataInputs(); console.log(inputs); // Array of input descriptors
2. useIsTaskMode()
Purpose: Determines if the Begin node is operating in "Task" dialogue mode.
Returns: Boolean indicating task mode status.
Implementation: Uses
useMemoto memoize the mode check based on the Begin node's form mode.Usage:
const isTask = useIsTaskMode();
3. useGetBeginNodeDataQuery()
Purpose: Returns a callback that generates the Begin node's data query inputs.
Returns: A function that, when called, returns an array of inputs.
Usage:
const getQuery = useGetBeginNodeDataQuery(); const queryInputs = getQuery();
4. useGetBeginNodeDataInputs()
Purpose: Similar to
useSelectBeginNodeDataInputs, but memoizes the inputs list.Returns: Memoized array of Begin node inputs.
Usage:
const beginInputs = useGetBeginNodeDataInputs();
5. useGetBeginNodeDataQueryIsSafe()
Purpose: Checks if the Begin node data query is safe — specifically, that no required input is of file type.
Returns: Boolean indicating safety.
Implementation: Uses
useEffectto update safety state whenever inputs or nodes change.Usage:
const isSafe = useGetBeginNodeDataQueryIsSafe();
6. filterAllUpstreamNodeIds(edges: Edge[], nodeIds: string[])
Purpose: Recursively finds all upstream node IDs for given node IDs by traversing edges.
Parameters:
edges: Array of graph edges.nodeIds: Starting node IDs to find upstream from.
Returns: Array of all upstream node IDs.
Algorithm: Recursively collects source nodes for edges targeting the given nodes, ensuring no duplicates.
Usage:
const upstreamNodes = filterAllUpstreamNodeIds(edges, [currentNodeId]);
7. buildOutputOptions(outputs: Record<string, any>, nodeId?, parentLabel?, icon?)
Purpose: Builds option objects for node outputs to be used in selects.
Parameters:
outputs: Object mapping output keys to output metadata.nodeId: ID of the node the outputs belong to.parentLabel: Label or ReactNode for the option group.icon: Icon ReactNode to display with options.
Returns: Array of option objects with labels and values.
Usage:
const options = buildOutputOptions(nodeOutputs, nodeId, 'Parent Node', <Icon />);
8. useBuildNodeOutputOptions(nodeId?: string)
Purpose: Builds grouped output options from all upstream nodes of the given node.
Parameters:
nodeId: The node for which to gather upstream output options.
Returns: Array of grouped option objects.
Usage:
const outputOptions = useBuildNodeOutputOptions('node123');
9. useBuildBeginVariableOptions()
Purpose: Builds variable options specifically from Begin node inputs.
Returns: An array with grouped variable options labeled as "Begin Input".
Implementation Detail: Converts specific query types to
VariableType.String.Usage:
const beginVarOptions = useBuildBeginVariableOptions();
10. useBuildVariableOptions(nodeId?: string, parentId?: string)
Purpose: Combines Begin variable options, node output options, and parent node output options into a single list.
Parameters:
nodeId: Current node ID.parentId: Parent node ID.
Returns: Combined array of variable options.
Usage:
const variableOptions = useBuildVariableOptions('nodeId', 'parentId');
11. useBuildQueryVariableOptions(n?: RAGFlowNodeType)
Purpose: Extends variable options by adding global DSL variables fetched via
useFetchAgent.Parameters:
n: Optional node context.
Returns: Extended variable options including globals.
Usage:
const queryVarOptions = useBuildQueryVariableOptions(node);
12. useBuildComponentIdOptions(nodeId?: string, parentId?: string)
Purpose: Builds options for component output nodes, filtered by parent scope and excluding certain node types.
Parameters:
nodeId: Current node ID.parentId: Parent node ID.
Returns: Grouped options labeled "Component Output".
Usage:
const componentOptions = useBuildComponentIdOptions('nodeId', 'parentId');
13. useBuildComponentIdAndBeginOptions(nodeId?: string, parentId?: string)
Purpose: Combines Begin variable options with component ID options.
Returns: Combined array of options.
Usage:
const combinedOptions = useBuildComponentIdAndBeginOptions('nodeId', 'parentId');
14. useGetComponentLabelByValue(nodeId: string)
Purpose: Provides a function to get the label of a component option by its value.
Parameters:
nodeId: Node ID for which to build options.
Returns: Function
(val?: string) => ReactNode | undefinedUsage:
const getLabel = useGetComponentLabelByValue('nodeId'); const label = getLabel('someValue');
15. useGetVariableLabelByValue(nodeId: string)
Purpose: Similar to above but for variable options.
Parameters:
nodeId: Node ID for context.
Returns: Label lookup function.
Usage:
const getVarLabel = useGetVariableLabelByValue('nodeId'); const label = getVarLabel('variableValue');
Important Implementation Details and Algorithms
Recursive Upstream Node Filtering:
ThefilterAllUpstreamNodeIdsfunction recursively collects all upstream nodes of a given node or set of nodes by traversing edges backward. This is crucial for building context-aware variable and output options limited to relevant nodes.Memoization for Performance:
Most hooks useuseMemoanduseCallbackto avoid unnecessary recalculations, especially important given that graph nodes and edges may update frequently.Type Translation:
The functiontransferToVariableTypemaps certainBeginQueryTypevalues (like lines or paragraphs) to a generic string variable type, standardizing variable representation.Exclusion Logic:
Some nodes are excluded from component option lists based on their operator type to avoid invalid or irrelevant references.Global Variables Integration:
The querying variable options are extended with global variables fetched from the agent's DSL globals, supporting dynamic and external context variables.
Interaction with Other Parts of the System
Graph Store (
useGraphStore):
Central to the file, the graph store provides access to nodes, edges, and node data. The hooks depend on it to retrieve the current state of the flow graph.Agent Form Context (
AgentFormContext):
Provides context about the currently active node form, used to build variable options and label lookups.Agent Fetch Hook (
useFetchAgent):
Fetches agent metadata, including global DSL variables, to be included in variable options.UI Components:
The output option builders utilizeOperatorIconcomponents and Ant Design's select option types to prepare inputs for UI dropdowns and selectors.Constants and Interfaces:
Enumerations and types imported from../constantand../interfaceenforce consistency in variable and operator typing.
Usage Example
import React from 'react';
import { useGetBeginNodeDataInputs, useBuildVariableOptions } from './use-get-begin-query';
function BeginNodeInputsDisplay() {
const inputs = useGetBeginNodeDataInputs();
const variableOptions = useBuildVariableOptions('currentNodeId', 'parentNodeId');
return (
<div>
<h3>Begin Node Inputs</h3>
<ul>
{inputs.map(input => (
<li key={input.key}>{input.name} ({input.type})</li>
))}
</ul>
<h3>Variable Options</h3>
<select>
{variableOptions.map(group => (
<optgroup label={typeof group.label === 'string' ? group.label : 'Variables'} key={group.label?.toString()}>
{group.options.map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</optgroup>
))}
</select>
</div>
);
}
Visual Diagram
flowchart TD
subgraph GraphStore
G[getNode, nodes, edges]
end
subgraph BeginNodeHooks
A[useSelectBeginNodeDataInputs]
B[useIsTaskMode]
C[useGetBeginNodeDataQuery]
D[useGetBeginNodeDataInputs]
E[useGetBeginNodeDataQueryIsSafe]
end
subgraph OptionBuilders
F[useBuildNodeOutputOptions]
G1[useBuildBeginVariableOptions]
H[useBuildVariableOptions]
I[useBuildQueryVariableOptions]
J[useBuildComponentIdOptions]
K[useBuildComponentIdAndBeginOptions]
end
subgraph LabelGetters
L[useGetComponentLabelByValue]
M[useGetVariableLabelByValue]
end
subgraph Utils
N[filterAllUpstreamNodeIds]
O[buildOutputOptions]
P[transferToVariableType]
end
G -->|used by| A
G -->|used by| B
G -->|used by| C
G -->|used by| D
G -->|used by| E
A -->|inputs| G1
G -->|provides nodes, edges| F
F -->|calls| N
F -->|calls| O
G1 -->|calls| P
H -->|combines| G1
H -->|combines| F
H -->|combines| J
I -->|extends| H
I -->|uses| useFetchAgent
K -->|combines| G1
K -->|combines| J
L -->|uses| K
M -->|uses| I
Summary
The use-get-begin-query.tsx file is a vital utility and hook collection that supports the flow-based agent's Begin node data handling and variable option management. It bridges the graph data model with UI components by providing structured, memoized, and context-sensitive variable and output options, ensuring the frontend forms and selectors remain consistent, performant, and intuitive.
This file exemplifies best practices in React hook design, recursive graph traversal, and integration of external context data into complex UI state management.