Variables
Learn how to define, interpret, and interpolate variables in PromptL
Overview
Variables in PromptL allow you to store and reuse dynamic values across your prompt. They make your prompts more maintainable and adaptable by eliminating repetitive text and enabling dynamic content generation.
Variables are defined using double curly braces ({{ }}
) and can be used directly in text or as part of logic expressions.
Defining Variables
You can define a variable by assigning a value inside {{ }}
:
In this example:
- The variable
name
is assigned the value"Alice"
. - The variable is interpolated into the text when the prompt is processed.
Interpolating Variables
Variables can be used anywhere in your prompt. When interpolated, their value replaces the placeholder in the text.
Input Parameters
Variables don’t have to be defined in the prompt. Instead, their values can be provided as dynamic input parameters when the prompt is executed.
In this example, the name
variable can be defined in the code when running this prompt, allowing you to dynamically customize the output without modifying the prompt.
Default Values
You can define default values for variables using the ||
operator. If the variable is not defined in the prompt or provided as an input parameter, the default value will be used.
Here, the name
variable will default to "Alice"
if no value is provided.
Tip: Use default values to ensure your prompts remain functional even if some parameters are missing.
Expressions
PromptL supports logic expressions, enabling you to perform calculations or transformations directly in the prompt.
Simple Expressions
Conditional Expressions
You can use ternary-like conditions to modify variable values dynamically:
Advanced Examples
Combining Input Parameters, Defaults, and Expressions
Nested or Structured Variables
Variables can represent objects or arrays, making it easy to handle structured data:
Best Practices
- Use Clear Variable Names: Choose descriptive names to make your prompts easy to understand.
- Good:
user.name
,weather.currentTemp
- Bad:
x
,temp
- Good:
- Avoid Redefinition: Define variables once and reuse them instead of redefining them unnecessarily.
- Default Values for Robustness: Use default values to handle missing inputs gracefully.
- Combine with Logic: Use expressions to preprocess data directly in the prompt, reducing complexity elsewhere.
Debugging Variables
If a variable isn’t working as expected:
- Check Scope: Ensure the variable is defined or provided as an input parameter.
- Validate Expressions: Double-check calculations or transformations.
- Use Defaults: Add default values to catch undefined variables.
Summary
Variables in PromptL enable dynamic and reusable prompts. By combining definitions, input parameters, defaults, and expressions, you can create highly flexible and maintainable conversations tailored to any use case.