Principle:Langgenius Dify PromptEngineering
| Knowledge Sources | Dify |
|---|---|
| Domains | Frontend, AI, Prompts |
| Last Updated | 2026-02-12 07:00 GMT |
Overview
Dify supports prompt engineering workflows through template variable extraction and management utilities that parse Template:Variable placeholders from prompt text and enforce naming conventions for variable keys.
Description
The utils/var.ts module provides the core infrastructure for working with prompt template variables. The getVars function scans a prompt string using the regex pattern /\{\{([a-z_]\w*)\}\}/gi to extract all Template:Variable name placeholders, while filtering out system-reserved placeholders ({{#context#}}, {{#histories#}}, {{#query#}}, {{#pre_prompt#}}). The extracted variables are deduplicated and length-limited according to MAX_VAR_KEY_LENGTH, producing a clean list of user-defined template variables that need input values at runtime.
The getNewVar and getNewVarInWorkflow factory functions create properly structured variable definitions from extracted keys, applying templates (VAR_ITEM_TEMPLATE for standard apps, VAR_ITEM_TEMPLATE_IN_WORKFLOW for workflow nodes) that set default values, type information, and display labels. Variable keys are validated through checkKey and checkKeys, which enforce naming rules: keys must be alphanumeric with underscores only (/^\w+$/), must not start with a digit, must not be empty (unless explicitly allowed), and must not exceed the maximum length. Validation returns typed i18n error message keys (canNoBeEmpty, tooLong, notStartWithNumber, notValid) for localized error display.
The module also includes the hasDuplicateStr utility for detecting duplicate variable names, and exposes the basePath configuration and marketplace URL construction functions. Together, these utilities form the tooling that powers the prompt editor's variable auto-detection, the configuration panel's variable table, and the workflow node's input parameter management.
Usage
Use this principle when:
- Building or extending prompt editor components that need to extract and display template variables
- Implementing variable management for new node types in the workflow builder
- Adding validation for variable naming in any context where users define template parameters
Theoretical Basis
Template variable extraction implements Template Processing from the domain of text templating engines, where placeholders in a template string are identified and resolved at runtime. The Template:Variable syntax follows the Mustache templating convention widely used in web development. The variable naming validation applies Identifier Rules similar to those in programming languages, ensuring that variable names are machine-parseable and unambiguous. The system-reserved placeholder filtering implements Reserved Word handling, preventing collisions between user-defined variables and platform-internal placeholders.