BAML Snippets

Template String

Writing prompts requires a lot of string manipulation. BAML has a template_string to let you combine different string templates together. Under-the-hood they use jinja to evaluate the string and its inputs.

Think of template strings as functions that have variables, and return a string. They can be used to define reusable parts of a prompt, or to make the prompt more readable by breaking it into smaller parts.


1// Inject a list of "system" or "user" messages into the prompt.
2template_string PrintMessages(messages: Message[]) #"
3 {% for m in messages %}
4 {{ _.role(m.role) }}
5 {{ m.message }}
6 {% endfor %}
9function ClassifyConversation(messages: Message[]) -> Category[] {
10 client GPT4Turbo
11 prompt #"
12 Classify this conversation:
13 {{ PrintMessages(messages) }}
15 Use the following categories:
16 {{ ctx.output_format}}
17 "#

In this example we can call the template_string PrintMessages to subdivide the prompt into “user” or “system” messages using _.role() (see message roles). This allows us to reuse the logic for printing messages in multiple prompts.

You can nest as many template strings inside each other and call them however many times you want.

The BAML linter may give you a warning when you use template strings due to a static analysis limitation. You can ignore this warning. If it renders in the playground, you’re good!

Use the playground preview to ensure your template string is being evaluated correctly!