Skip to main content

Loops

Iterate over collections in BAML prompts using {% for %} loops.

Syntax​

{% for item in items %}
{{ item }}
{% endfor %}

Basic Example​

function MyFunc(messages: Message[]) -> string {
prompt #"
{% for message in messages %}
{{ message.user_name }}: {{ message.content }}
{% endfor %}
"#
}

Loop Variable​

The loop object provides information about the current iteration:

VariableDescription
loop.indexCurrent iteration (1-indexed)
loop.index0Current iteration (0-indexed)
loop.revindexIterations from end (1-indexed)
loop.revindex0Iterations from end (0-indexed)
loop.firstTrue if first iteration
loop.lastTrue if last iteration
loop.lengthTotal number of items
loop.cycleCycle through a list of values
loop.depthRecursion depth (starts at 1)
loop.depth0Recursion depth (starts at 0)
loop.previtemPrevious item (undefined on first)
loop.nextitemNext item (undefined on last)
loop.changed(*val)True if called with different value

Examples​

Numbered List​

{% for item in items %}
{{ loop.index }}: {{ item }}
{% endfor %}

Conditional Formatting​

{% for item in items %}
{{ item }}{% if not loop.last %}, {% endif %}
{% endfor %}

First and Last​

{% for item in items %}
{% if loop.first %}First: {% endif %}
{{ item }}
{% if loop.last %} (End){% endif %}
{% endfor %}

Alternating Roles​

{% for m in messages %}
{{ _.role("user" if loop.index % 2 == 1 else "assistant") }}
{{ m }}
{% endfor %}

Empty Loop Fallback​

{% for item in items %}
{{ item }}
{% else %}
No items found.
{% endfor %}

Nested Loops​

{% for category in categories %}
Category: {{ category.name }}
{% for item in category.items %}
- {{ item }}
{% endfor %}
{% endfor %}

Loop Filtering​

{% for user in users if user.is_active %}
{{ user.name }}
{% endfor %}

See Also​