Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Expressions & Variables Reference

Complete reference for the Juglans Expression Language (JEL). Covers variables, operators, built-in functions, type system, and usage contexts.


1. Variable System

Overview

VariableSourceWritableScopeExample
inputCLI --input JSON or API bodyNoEntire workflowinput.name, input.items[0]
outputReturn value of the last executed nodeNoOverwritten each stepoutput, output.text
Context varsAssignment syntaxYesEntire workflowcount, user.name
replyAI response metadataNoAfter chat()reply.output, reply.chat_id
errorSet when on error triggersNoError patherror.node, error.message
node_id.outputSpecific node’s outputNoEntire workflowclassify.output

input

Data passed when the workflow starts. Read-only.

[greet]: print(message="Hello, " + input.name)
[done]: print(message="Done")
[greet] -> [done]

Sources:

# CLI
juglans workflow.jg --input '{"name": "Alice", "items": [1, 2, 3]}'

# API
# POST /api/workflows/my-flow/execute  body: {"name": "Alice"}

Access nested fields with dot notation. Arrays use numeric indices:

input              # Entire object
input.name         # "Alice"
input.items[0]     # 1 (first element)
input.user.address.city   # Deep nesting

Missing fields resolve to null (no error).

output

Return value of the most recently executed node. Overwritten after each step.

[step1]: print(message="hello")
[step2]: print(message="step1 said: " + output)
[step1] -> [step2]

<node_id>.output

Access a specific node’s output by its ID. Persists for the entire workflow – use this to reach back to earlier nodes.

[a]: print(message="first")
[b]: print(message="second")
[c]: print(message=a.output + " and " + b.output)
[a] -> [b] -> [c]

Context Variables

User-defined shared storage. Write with assignment syntax, read as bare identifiers.

[init]: count = 0, name = "Alice"
[inc]: count = count + 1
[show]: print(message=name + ": " + str(count))
[init] -> [inc] -> [show]

Context persists across all nodes in the workflow.

reply

Metadata from the most recent AI response (after chat()).

FieldTypeDescription
reply.outputstringAccumulated AI response text
reply.chat_idstringConversation session ID
reply.statusstringLatest notify() status message
reply.user_message_idintegerID of the user message that triggered execution (web server only)
[ask]: chat(agent="assistant", message=input.query)
[log]: print(message="Response: " + reply.output)
[ask] -> [log]

error

Available on on error paths. Contains information about the failure.

FieldTypeDescription
error.messagestringError message
error.nodestringNode ID that failed
[risky]: fetch_url(url=input.url)
[handler]: print(message="Failed at " + error.node + ": " + error.message)
[risky] on error -> [handler]

Namespaced Variables (Flow Imports)

When using flows: imports, subworkflow node outputs are accessed via namespace prefix:

flows: { auth: "./auth.jg", trading: "./trading.jg" }

# auth.verify.output     — output of the verify node in the auth subworkflow
# trading.extract.output — output of extract in the trading subworkflow
[a]: notify(status=auth.verify.output)
[b]: notify(status=trading.extract.output)
[a] -> [b]

Global variables (input, output, context variables) are not prefixed.

Loop Context Variables

Available inside foreach and while blocks:

VariableTypeDescription
loop.indexnumberCurrent index (0-based)
loop.firstbooleanFirst iteration?
loop.lastbooleanLast iteration?
[process]: foreach(item in input.items) {
  [log]: print(message="Item " + str(loop.index + 1) + ": " + item)
}

2. Operators

Arithmetic

OperatorDescriptionExample
+Addition / string concatenationa + 1, "hi" + " " + "there"
-Subtractiona - b
*Multiplicationprice * quantity
/Divisiontotal / count
%Moduloindex % 2
[calc]: sum = a + b, diff = a - b, product = a * b

The + operator also concatenates strings:

[greet]: print(message="Hello, " + input.name + "!")
[done]: print(message="ok")
[greet] -> [done]

Comparison

OperatorDescription
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to
[check]: print(message="checking")
[high]: print(message="high")
[low]: print(message="low")
[check] if score >= 80 -> [high]
[check] if score < 80 -> [low]

Logical

OperatorAliasDescription
and&&Logical AND
or||Logical OR
not!Logical NOT
[check]: print(message="checking")
[allow]: print(message="allowed")
[deny]: print(message="denied")
[check] if logged_in && is_admin -> [allow]
[check] if !logged_in -> [deny]

Membership

OperatorDescription
inValue is contained in collection
not inValue is not contained in collection

Works with strings (substring check), arrays (element check), and objects (key check).

String Concatenation

Use + to join strings. Non-string values must be converted with str() first:

[show]: print(message="Count: " + str(count) + " items")
[done]: print(message="ok")
[show] -> [done]

Operator Precedence (low to high)

  1. or, ||
  2. and, &&
  3. in, not in
  4. ==, !=, >, <, >=, <=
  5. +, -
  6. *, /, %
  7. not, !, unary -
  8. . (dot access), [] (bracket access), () (function call)

Use parentheses to override precedence:

[check]: print(message="checking")
[target]: print(message="target")
[check] if (a > 0 && b > 0) || force -> [target]

3. Built-in Functions

Type Conversion

FunctionSignatureDescription
str(x)str(value) -> strConvert any value to string
int(x)int(value) -> intConvert to integer (truncates floats, parses strings)
float(x)float(value) -> floatConvert to float
bool(x)bool(value) -> boolConvert using truthiness rules
[conv]: s = str(42), n = int("100"), f = float("3.14"), b = bool(1)

Type Checking

FunctionSignatureDescription
type(x)type(value) -> strReturns type name: "str", "number", "bool", "list", "dict", "None"
is_null(x)is_null(value) -> boolTrue if value is null
is_string(x)is_string(value) -> boolTrue if value is a string
is_number(x)is_number(value) -> boolTrue if value is a number
is_bool(x)is_bool(value) -> boolTrue if value is a boolean
is_array(x)is_array(value) -> boolTrue if value is a list
is_object(x)is_object(value) -> boolTrue if value is a dict
[check]: print(message="Type is: " + type(value))
[done]: print(message="ok")
[check] -> [done]

String Functions

FunctionSignatureDescription
upper(s)upper(str) -> strConvert to uppercase
lower(s)lower(str) -> strConvert to lowercase
trim(s)trim(str) -> strRemove leading/trailing whitespace (alias: strip)
replace(s, old, new)replace(str, str, str) -> strReplace all occurrences
split(s, sep)split(str, str) -> listSplit string by separator
join(arr, sep)join(list, str) -> strJoin list elements with separator
contains(s, sub)contains(str, str) -> boolCheck if string contains substring
startswith(s, prefix)startswith(str, str) -> boolCheck if string starts with prefix
endswith(s, suffix)endswith(str, str) -> boolCheck if string ends with suffix
find(s, sub)find(str, str) -> intIndex of first occurrence (-1 if not found)
count(s, sub)count(str, str) -> intCount occurrences of substring
capitalize(s)capitalize(str) -> strCapitalize first letter, lowercase rest
title(s)title(str) -> strTitle Case each word
truncate(s, n)truncate(str, int) -> strTruncate to n chars, append ... if truncated
lpad(s, w, c?)lpad(str, int, str?) -> strLeft-pad to width w with char c (default: space)
rpad(s, w, c?)rpad(str, int, str?) -> strRight-pad to width w with char c (default: space)
repeat(s, n)repeat(str, int) -> strRepeat string n times
slice(s, start, end?)slice(str, int, int?) -> strSubstring (supports negative indices)
reverse(s)reverse(str) -> strReverse a string
[demo]: up = upper("hello"), lo = lower("WORLD"), t = trim("  spaced  "), r = replace("foo bar foo", "foo", "baz"), parts = split("a,b,c", ","), joined = join(["x", "y", "z"], "-")
[pad]: left = lpad("42", 5, "0"), right = rpad("hi", 10, "."), sub = slice("hello world", 0, 5)

Collection Functions

FunctionSignatureDescription
len(x)len(str|list|dict) -> intLength of string, array, or object
keys(d)keys(dict) -> listGet all keys of an object
values(d)values(dict) -> listGet all values of an object
items(d)items(dict) -> listGet [key, value] pairs
has(x, key)has(dict|list, value) -> boolCheck if key exists in dict or element in list
get(x, key, default?)get(dict|list, key, value?) -> valueSafe access with optional default
append(arr, item)append(list, value) -> listReturn new list with item appended
range(end) / range(start, end) / range(start, end, step)range(...) -> listGenerate a list of integers
sort(arr)sort(list) -> listSort list (numbers numerically, others lexicographically)
reverse(arr)reverse(list) -> listReverse a list
unique(arr)unique(list) -> listRemove duplicates, preserving order
flatten(arr)flatten(list) -> listFlatten one level of nested lists
slice(arr, start, end?)slice(list, int, int?) -> listSub-list (supports negative indices)
first(arr)first(list) -> valueFirst element (null if empty)
last(arr)last(list) -> valueLast element (null if empty)
chunk(arr, size)chunk(list, int) -> listSplit list into chunks of given size
sum(arr)sum(list) -> numberSum all numeric elements
zip(a, b)zip(list, list) -> listPair elements from two lists
enumerate(arr)enumerate(list) -> listPairs of [index, element]
all(arr)all(list) -> boolTrue if all elements are truthy
any(arr)any(list) -> boolTrue if any element is truthy
[init]: items = [3, 1, 2]
[ops]: length = len(items), sorted = sort(items), added = append(items, 4), total = sum(items)
[init] -> [ops]
[range_demo]: five = range(5), evens = range(0, 10, 2), rev = reverse(range(5))

Math Functions

FunctionSignatureDescription
round(x, digits?)round(number, int?) -> numberRound to n decimal places (default: 0)
abs(x)abs(number) -> numberAbsolute value
min(a, b, ...)min(number, number, ...) -> numberMinimum of two or more values
max(a, b, ...)max(number, number, ...) -> numberMaximum of two or more values
floor(x)floor(number) -> intRound down
ceil(x)ceil(number) -> intRound up
pow(base, exp)pow(number, number) -> numberExponentiation
sqrt(x)sqrt(number) -> numberSquare root
log(x, base?)log(number, number?) -> numberLogarithm (natural log if no base)
clamp(x, min, max)clamp(number, number, number) -> numberClamp value to range
random()random() -> floatRandom float in [0, 1)
randint(min, max)randint(int, int) -> intRandom integer in [min, max]
[math]: r = round(3.14159, 2), a = abs(-42), lo = min(10, 20, 5), hi = max(10, 20, 5), clamped = clamp(150, 0, 100)

JSON / Data Functions

FunctionSignatureDescription
json(x)json(value) -> str|valueEncode non-string to JSON string; decode JSON string to value
json_pretty(x)json_pretty(value) -> strPretty-print value as indented JSON
from_json(s)from_json(str) -> valueParse JSON string (strict – errors on invalid JSON)
merge(a, b)merge(dict, dict) -> dictMerge two objects (b overwrites a)
pick(obj, keys)pick(dict, list) -> dictKeep only listed keys
omit(obj, keys)omit(dict, list) -> dictRemove listed keys
from_entries(pairs)from_entries(list) -> dictConvert [[key, value], ...] to object
[data]: encoded = json({"name": "Alice", "age": 30}), merged = merge({"a": 1}, {"b": 2}), picked = pick({"a": 1, "b": 2, "c": 3}, ["a", "c"])

Date/Time Functions

FunctionSignatureDescription
now()now() -> strCurrent UTC time as ISO 8601 string
timestamp()timestamp() -> intCurrent UTC Unix timestamp (seconds)
timestamp_ms()timestamp_ms() -> intCurrent UTC Unix timestamp (milliseconds)
format_date(iso, fmt)format_date(str, str) -> strFormat an ISO 8601 string with strftime syntax
parse_date(s, fmt)parse_date(str, str) -> strParse a date string into ISO 8601
[time]: current = now(), ts = timestamp(), formatted = format_date(now(), "%Y-%m-%d")

Encoding Functions

FunctionSignatureDescription
base64_encode(s)base64_encode(str) -> strBase64 encode
base64_decode(s)base64_decode(str) -> strBase64 decode
url_encode(s)url_encode(str) -> strURL-encode a string
url_decode(s)url_decode(str) -> strURL-decode a string
md5(s)md5(str) -> strMD5 hash (hex)
sha256(s)sha256(str) -> strSHA-256 hash (hex)
[encode]: b64 = base64_encode("hello world"), url = url_encode("a=1&b=2"), hash = sha256("secret")

Regex Functions

FunctionSignatureDescription
regex_match(s, pattern)regex_match(str, str) -> boolTest if string matches pattern
regex_find(s, pattern)regex_find(str, str) -> str|nullFirst match (null if none)
regex_find_all(s, pattern)regex_find_all(str, str) -> listAll matches
regex_replace(s, pattern, rep)regex_replace(str, str, str) -> strReplace all matches
[rx]: is_email = regex_match("[email protected]", "^[^@]+@[^@]+$"), digits = regex_find_all("abc123def456", "[0-9]+"), cleaned = regex_replace("Hello   World", "\\s+", " ")

Path Functions

FunctionSignatureDescription
basename(path)basename(str) -> strFile name from path
dirname(path)dirname(str) -> strDirectory from path
extname(path)extname(str) -> strExtension (e.g., ".txt")
join_path(a, b, ...)join_path(str, str, ...) -> strJoin path segments
[paths]: name = basename("/home/user/data.csv"), dir = dirname("/home/user/data.csv"), ext = extname("/home/user/data.csv"), full = join_path("/home", "user", "data.csv")

Other Functions

FunctionSignatureDescription
if(cond, then, else)if(bool, value, value) -> valueTernary — returns then when cond is truthy, else else. Both branches are evaluated; for short-circuit semantics use and / or
default(x, fallback)default(value, value) -> valueReturn fallback if x is null or empty string
format(template, args...)format(str, ...) -> strPython-style {} formatting
uuid()uuid() -> strGenerate a UUID v4
env(name, default?)env(str, value?) -> str|nullRead environment variable
chr(n)chr(int) -> strUnicode code point to character
ord(s)ord(str) -> intFirst character to Unicode code point
hex(n)hex(int) -> strInteger to hex string ("0x2a")
bin(n)bin(int) -> strInteger to binary string ("0b101010")
oct(n)oct(int) -> strInteger to octal string ("0o52")
is_ok(x)is_ok(value) -> boolRust-style result check: true unless x is null or {err: ...}
is_err(x)is_err(value) -> boolRust-style result check: true when x is null or {err: ...}
unwrap_or(x, fallback)unwrap_or(value, value) -> valueReturn x unless it is null or {err: ...}, in which case return fallback
review(x, prompt?)review(value, str?) -> boolInteractive CLI review gate — prints x and prompts the user for y/n
[misc]: name = default(input.name, "anonymous"), msg = format("Hello {}, you have {} items", "Alice", 5), id = uuid()

Higher-Order Functions (Lambda Support)

These functions accept lambda expressions (x => expr or (x, y) => expr):

FunctionSignatureDescription
map(arr, fn)map(list, lambda) -> listTransform each element
filter(arr, fn)filter(list, lambda) -> listKeep elements where fn returns truthy
reduce(arr, fn, init)reduce(list, lambda, value) -> valueFold list to single value
sort_by(arr, fn)sort_by(list, lambda) -> listSort by computed key
find_by(arr, fn)find_by(list, lambda) -> value|nullFirst element where fn is truthy
group_by(arr, fn)group_by(list, lambda) -> dictGroup elements by computed key
flat_map(arr, fn)flat_map(list, lambda) -> listMap then flatten one level
count_by(arr, fn)count_by(list, lambda) -> dictCount elements by computed key
min_by(arr, fn)min_by(list, lambda) -> value|nullElement minimizing the computed key
max_by(arr, fn)max_by(list, lambda) -> value|nullElement maximizing the computed key
every(arr, fn)every(list, lambda) -> boolTrue iff every element satisfies the predicate
some(arr, fn)some(list, lambda) -> boolTrue iff at least one element satisfies the predicate

Lambda syntax: param => body for single parameter, (a, b) => body for multiple.

[transform]: doubled = map([1, 2, 3], x => x * 2), evens = filter([1, 2, 3, 4, 5], x => x % 2 == 0), total = reduce([1, 2, 3, 4], (acc, x) => acc + x, 0)
[advanced]: sorted = sort_by(["banana", "apple", "cherry"], x => len(x)), grouped = group_by([1, 2, 3, 4, 5], x => x % 2)

Method call syntax is also supported – lambdas can be chained:

[chain]: result = [1, 2, 3, 4, 5].filter(x => x > 2).map(x => x * 10)

Pipe Syntax

Jinja-style pipe filters can be used as an alternative to function calls:

value | upper              # upper(value)
value | truncate(20)       # truncate(value, 20)
value | replace("a", "b")  # replace(value, "a", "b")

The value before | is passed as the first argument to the filter function.


4. Expression Usage Contexts

Expressions can appear in these positions within a workflow:

Node Parameter Values

[step]: print(message="Count: " + str(len(items)))
[done]: print(message="ok")
[step] -> [done]

Conditional Edges (if)

[check]: print(message="checking")
[pass]: print(message="pass")
[fail]: print(message="fail")
[check] if score > 80 && verified -> [pass]
[check] if score <= 80 -> [fail]

Switch Values

[route]: print(message="routing")
[en]: print(message="english")
[zh]: print(message="chinese")
[other]: print(message="other")

[route] -> switch language {
  "en": [en]
  "zh": [zh]
  default: [other]
}

While Conditions

[loop]: while(count < 10) {
  [inc]: count = count + 1
}

Assignment Syntax

Assignment syntax sets context variables directly:

[init]: count = 0, name = "Alice"
[show]: print(message=name + ": " + str(count))
[init] -> [show]

5. Type System

Types

TypeLiteral SyntaxJEL type()Example
nullnull, none, None"None"null
booltrue, false, True, False"bool"true
number (int)42, -1, 0"number"42
number (float)3.14, -0.5"number"3.14
string"hello", 'hello', """multiline""""str""hello"
array[1, 2, 3]"list"[1, "two", true]
object{"key": "value"}"dict"{"a": 1}

F-Strings (Interpolated Strings)

F-strings allow embedding expressions inside string literals:

f"Hello {name}, you have {count} items"
f"Result: {score * 100}%"

Triple-quoted f-strings support multi-line content:

f"""
Name: {name}
Score: {score}
"""

Truthiness

Juglans uses Python-like truthiness rules. The following values are falsy:

ValueFalsy?
null / NoneYes
falseYes
0 (zero)Yes
"" (empty string)Yes
[] (empty array)Yes
{} (empty object)Yes

Everything else is truthy.

[check]: print(message="checking")
[has_data]: print(message="data exists")
[no_data]: print(message="no data")

# Empty list is falsy, non-empty list is truthy
[check] if results -> [has_data]
[check] if !results -> [no_data]

Type Coercion

  • Arithmetic operators coerce operands to numbers. Strings are parsed; bools become 0/1; null becomes 0.
  • + with a string operand on either side performs concatenation (non-strings converted via str()).
  • Comparison operators compare numbers numerically and strings lexicographically.

6. Comprehensive Examples

Data Processing Pipeline

[init]: results = [], total = 0, processed = 0

[process]: foreach(item in input.records) {
  [validate]: valid = item.score >= 0 && item.score <= 100

  [transform]: normalized = round(item.score / 100, 2), label = upper(slice(item.name, 0, 3)), processed = processed + 1, total = total + item.score, results = append(results, {
      "name": item.name,
      "score": item.score,
      "label": upper(slice(item.name, 0, 3))
    })

  [validate] -> [transform]
}

[report]: print(
  message="Processed " + str(processed) + " items. Avg: " + str(round(total / processed, 1))
)

[init] -> [process] -> [report]

Dynamic Routing with Expressions

[evaluate]: score = input.score, tier = default(input.tier, "standard")

[done]: print(message="Routed to handler")
[excellent]: print(message="Excellent!")
[good]: print(message="Good")
[retry]: print(message="Needs improvement")

[evaluate] if score >= 90 && tier == "premium" -> [excellent]
[evaluate] if score >= 60 -> [good]
[evaluate] -> [retry]

[excellent] -> [done]
[good] -> [done]
[retry] -> [done]

Collection Transformation

[setup]: numbers = [5, 3, 8, 1, 9, 2, 7], words = ["hello", "world", "juglans"]

[transform]: sorted = sort(numbers), top3 = slice(sort(numbers), 4), total = sum(numbers), avg = round(sum(numbers) / len(numbers), 2), upper_words = map(words, w => upper(w)), long_words = filter(words, w => len(w) > 5), lengths = map(words, w => len(w)), word_str = join(words, ", ")

[result]: print(
  message="Sum=" + str(total) + " Avg=" + str(avg) + " Words: " + word_str
)

[setup] -> [transform] -> [result]