What is Jinja / Cookbook

BAML Prompt strings are essentially Minijinja templates, which offer the ability to express logic and data manipulation within strings. Jinja is a very popular and mature templating language amongst Python developers, so Github Copilot or another LLM can already help you write most of the logic you want.

Jinja Cookbook

When in doubt — use the BAML VSCode Playground preview. It will show you the fully rendered prompt, even when it has complex logic.

Basic Syntax

  • {% ... %}: Use for executing statements such as for-loops or conditionals.
  • {{ ... }}: Use for outputting expressions or variables.
  • {# ... #}: Use for comments within the template, which will not be rendered.

Loops / Iterating Over Lists

Here’s how you can iterate over a list of items, accessing each item’s attributes:

Jinja
1function MyFunc(messages: Message[]) -> string {
2 prompt #"
3 {% for message in messages %}
4 {{ message.user_name }}: {{ message.content }}
5 {% endfor %}
6 "#
7}

Conditional Statements

Use conditional statements to control the flow and output of your templates based on conditions:

Jinja
1function MyFunc(user: User) -> string {
2 prompt #"
3 {% if user.is_active %}
4 Welcome back, {{ user.name }}!
5 {% else %}
6 Please activate your account.
7 {% endif %}
8 "#
9}

Setting Variables

You can define and use variables within your templates to simplify expressions or manage data:

1function MyFunc(items: Item[]) -> string {
2 prompt #"
3 {% set total_price = 0 %}
4 {% for item in items %}
5 {% set total_price = total_price + item.price %}
6 {% endfor %}
7 Total price: {{ total_price }}
8 "#
9}

Including other Templates

To promote reusability, you can include other templates within a template. See template strings:

1template_string PrintUserInfo(arg1: string, arg2: User) #"
2 {{ arg1 }}
3 The user's name is: {{ arg2.name }}
4"#
5
6function MyFunc(arg1: string, user: User) -> string {
7 prompt #"
8 Here is the user info:
9 {{ PrintUserInfo(arg1, user) }}
10 "#
11}

Built-in filters

See jinja docs