@assert

The @assert attribute in BAML is used for strict validations. If a type fails an @assert validation, it will not be returned in the response, and an exception will be raised if it’s part of the top-level type.

Usage

Asserts can be named or unnamed.

Field Assertion

BAML
1class Foo {
2 // @assert will be applied to the field with the name "bar"
3 bar int @assert(between_0_and_10, {{ this > 0 and this < 10 }})
4}
BAML
1class Foo {
2 // @assert will be applied to the field with no name
3 bar int @assert({{ this > 0 and this < 10 }})
4}
BAML
1class MyClass {
2 // @assert will be applied to each element in the array
3 my_field (string @assert(is_valid_email, {{ this.contains("@") }}))[]
4}

Parameter Assertion

Asserts can also be applied to parameters.

BAML
1function MyFunction(x: int @assert(between_0_and_10, {{ this > 0 and this < 10 }})) {
2 client "openai/gpt-4o"
3 prompt #"Hello, world!"#
4}

Block Assertion

Asserts can be used in a block definition, referencing fields within the block.

BAML
1class Foo {
2 bar int
3 baz string
4 @@assert(baz_length_limit, {{ this.baz|length < this.bar }})
5}