Reusing Prompt Snippets

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.

Template Strings are functions that always 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.

Example

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

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!