Jinja Filters
Jinja filters allow you to transform and format values within your BAML prompts. Filters are applied using the pipe operator (|).
Basic Usage
BAML Custom Filters
format
Serializes values into structured text while preserving all BAML-specific aliases. Use the required type argument to choose the output representation.
Signature: value|format(type="yaml" | "json" | "toon", **kwargs)
Required arguments:
type(string):"yaml","json", or"toon"(alias for TOON serializer)
Format-specific behavior:
All formats reuse the same alias-aware serializer, so enums emit their @alias values and class properties honor @alias names at every nesting level (lists, maps, nested classes, etc.).
Examples:
TOON options (only when format="toon"):
indent(int, default 2): spaces per indent leveldelimiter("comma" | "tab" | "pipe", default"comma"): column separator for arrayslength_marker(single char, optional): prefix to annotate array lengths
Invalid combinations raise a template error (e.g., missing type or an unknown delimiter for TOON).
About TOON:
TOON (Token-Oriented Object Notation) combines YAML’s indentation with CSV-style tabular layout. It’s designed for uniform arrays of objects (multiple fields per row, same structure across items), where it can provide significant token savings while maintaining LLM-friendly structure validation through explicit array lengths and field headers.
When TOON works best:
- Uniform arrays of objects (e.g., lists of users, transactions, products)
- Highly structured, tabular data
When other formats may be better:
- Deeply nested structures (compact JSON may use fewer tokens)
- Semi-uniform or mixed data
- Pure flat tables (CSV is more compact)
For benchmarks, detailed comparisons, and the full specification, see the TOON repository.
regex_match
Tests if a string matches a regular expression pattern.
Signature: value|regex_match(pattern)
Example:
sum
Sums all numeric values in an array.
Signature: array|sum
Example:
Standard Jinja Filters
BAML supports all standard Minijinja filters. Here are some commonly used ones:
length
Returns the length of a string, array, or object.
upper / lower
Converts string to uppercase or lowercase.
title
Converts string to title case.
trim
Removes whitespace from both ends of a string.
default
Provides a default value if the variable is undefined or empty.
join
Joins array elements into a string with a separator.
first / last
Returns the first or last element of an array.
sort
Sorts an array.
unique
Removes duplicate values from an array.
reverse
Reverses an array or string.
replace
Replaces occurrences of a substring.
round
Rounds a number to a specified precision.
abs
Returns the absolute value of a number.
Chaining Filters
You can chain multiple filters together:
More Information
For a complete list of standard Jinja filters, see the Minijinja documentation.