Variable Resolution and Template Substitution#
Overview#
Variable resolution in Dify workflows centers on the VariablePool โ a single shared store (provided by the external graphon package) that every node reads from and writes to during execution. Cross-node references use the {{#<node_id>.<variable_name>#}} template syntax, resolved at runtime by convert_template() from graphon.variables.template_resolution.
Key backend entry points:
| File | Purpose |
|---|---|
api/core/workflow/variable_pool_initializer.py | add_variables_to_pool(), add_node_inputs_to_pool() โ pool bootstrap and node input registration |
api/core/workflow/system_variables.py | SystemVariableKey enum โ system-level variable names |
api/core/workflow/node_factory.py | DifyNodeFactory.create_node() โ wires each node type to its template resolution dependencies |
Key frontend entry points:
| File | Purpose |
|---|---|
web/.../nodes/_base/components/variable/utils.ts | getNodeUsedVars(), updateNodeVars(), toNodeOutputVars(), getVarType() |
web/.../workflow/hooks/use-workflow.ts | isVarUsedInNodes(), removeUsedVarInNodes() |
web/.../block-selector/snippets/use-insert-snippet.ts | Snippet insertion with ID remapping and variable selector rewriting |
VariablePool Lifecycle#
The pool lives in graphon's RuntimeState (Graphon 0.8; replaces the earlier GraphRuntimeState) and is bootstrapped once at workflow start.
Bootstrap โ add_variables_to_pool() seeds four fixed namespaces, each keyed by a sentinel node ID:
| Namespace | Contents |
|---|---|
SYSTEM_VARIABLE_NODE_ID | query, files, conversation_id, user_id, workflow_run_id, etc. |
ENVIRONMENT_VARIABLE_NODE_ID | Workflow-level env vars |
CONVERSATION_VARIABLE_NODE_ID | Persisted conversation state |
RAG_PIPELINE_VARIABLE_NODE_ID | Knowledge base pipeline inputs |
User inputs from the START node are added via add_node_inputs_to_pool(), which registers each value under the primary node ID plus any aliases (e.g., snippet workflows register inputs under both __snippet_virtual_start__ and the alias start).
Debug runs โ Individual-node and container (loop/iteration) debugging registers the supplied node inputs into the pool via WorkflowEntry.mapping_user_inputs_to_variable_pool(). Supplied values are preserved, including falsy values (e.g., 0, false, empty strings) and nested selectors; only a missing or None input is skipped. Whole-object selectors are applied before nested overrides, regardless of editor field order, and values are written with add_node_input_to_variable_pool().
Execution โ After each node completes, it writes outputs back via variable_pool.add((node_id, key), value). Downstream templates are resolved against the pool as each node runs.
Template Syntax: {{#โฆ#}}#
The placeholder format is {{#<node_id>.<variable_name>#}}. The regex used by the template engine accepts only alphanumeric characters and underscores in both segments โ node IDs with hyphens will silently pass through unsubstituted as raw text.
convert_template() returns a typed object with three rendering properties:
.textโ plain-text rendering (strings viastr(), objects viajson.dumps).logโ log-friendly rendering (objects indented).markdownโ markdown rendering (used for Human Input form content; arrays formatted as- itemlists)
The ArrayObjectSegment type renders its .text via str() (Python repr), not json.dumps โ this can produce Python-style output (e.g., single quotes, True/False) when an Array[Object] variable is interpolated into a plain-text context.
Special namespaces โ On the frontend, selectors beginning with sys, env, conversation, or rag are mapped to their sentinel node IDs. System variables like sys.query and sys.files appear under the Start node's output in the variable picker.
Template Substitution by Node Type#
DifyNodeFactory.create_node() wires the correct rendering helper for each node type.
| Node Type | Template Rendering |
|---|---|
| LLM / Template Transform | jinja2_template_renderer |
| HTTP Request | graphon Executor with variable_pool; URL, headers, params, and body all substituted |
| Human Input | convert_template() โ .markdown; stored as rendered_content in DB at pause time |
| Code | Variables injected as named arguments โ not template-rendered |
| Answer / End | replaceOldVarInText() on text fields |
| Agent | runtime_support.py resolves inputs and tool parameters from pool |
Human Input v2 notification subjects can include workflow-variable references inserted with the variable picker in MessageTemplateSubject. This is a single-line editor: Enter does not insert a line break, and pasted line breaks are normalized to spaces.
HTTP Request Node: JSON Body Escaping#
Body type handling differs by content type:
form-data/x-www-form-urlencoded:convert_template()is called; substituted values become strings.json: Usesconvert_template_escape(), which additionally escapes"โ\"and\nโ\\nin string values before callingjson.loads(). Non-string segments (numbers, objects) are left unescaped.
Type-aware substitution in JSON bodies:
- Numbers remain unquoted:
{"count": {{#node.count#}}}โ{"count": 42} - Unquoted strings in the template are auto-quoted via
json_repair(v0.60.1) as a fallback Array[Object]variables expand via Pythonrepr, which may produce non-JSON-safe output (single quotes, Python booleans)
Unit tests for these cases (including UUID string preservation) are in test_http_request_executor.py.
Frontend: Variable Discovery and Selector Rewriting#
All frontend variable management flows through utils.ts and use-workflow.ts.
getNodeUsedVars(node)โ returns allValueSelector[]arrays a node references; authoritative source for node variable dependencies.updateNodeVars(oldNode, oldSelector, newSelector)โ rewrites all references fromoldSelectortonewSelectorusing Immer'sproduce; called on upstream node rename, deletion, or snippet insertion.isVarUsedInNodes/removeUsedVarInNodesโ gate deletion confirmation dialogs and clean up downstream references when a variable is deleted.
Snippet Insertion: ID Remapping#
When a snippet is inserted via useInsertSnippet, every node gets a fresh ID. remapSnippetGraph applies:
remapSnippetNodeStructuralReferencesโ rewritesiteration_id,loop_id,start_node_id,output_selector.remapSnippetNodeVariableReferencesโ callsgetNodeUsedVars()+updateNodeVars()to remap all intra-snippetValueSelectorarrays. (Added in PR #39843; prior to this, stale node IDs were silently retained.)remapSnippetAssignerReferencesโ handles Assigner nodes separately (v2:items[].variable_selector/items[].variable_input; legacy v1:assigned_variable_selector/input_variable_selector). External namespace selectors (env,conversation) are preserved.
Variable Assigner vs. Variable Aggregator#
Two similarly named node types serve distinct roles:
BlockEnum.Assigner(current) /BlockEnum.VariableAssigner(legacy BC alias) โ writes a value into a conversation or environment variable. Types defined inassigner/types.ts.BlockEnum.VariableAggregator(legacy alias:VariableAssigner) โ merges outputs from multiple upstream branches into a singleoutputvariable, silently ignoring skipped branches. This is the recommended fix for "Variable Not Found" on branch convergence.
Common Failure Modes#
LLM node receives model config instead of template output
Root cause: the VariablePool does not yet contain the upstream node's output. Confirm the upstream node is connected by an edge; check for parallel-branch race conditions.
Human Input node shows raw {{#โฆ#}} after page refresh
Root cause: render_form_content_before_submission() failed to call convert_template() at pause time (pool not populated), or the API returned the raw form_content field instead of rendered_content. The frontend does not resolve variables client-side.
"Variable Not Found" on branch convergence
Skipped conditional branches leave output variables undefined. Wrap the variable in a Variable Aggregator node. As of PR #42750, the publish endpoint also returns a non-blocking warning toast when a consumer can execute in a run that skips its producer.
Silent substitution failure for hyphenated node IDs
The {{#โฆ#}} regex only accepts [a-zA-Z0-9_] in the node ID segment. Hyphens cause the placeholder to pass through unsubstituted with no error.
Empty variable selector fails backend validation
Clearing an optional file input in a tool or agent node saves value_selector: [], which the backend rejects. Fix: delete the parameter row entirely rather than clearing the value.