@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
class Foo {
// @assert will be applied to the field with the name "bar"
bar int @assert(between_0_and_10, {{ this > 0 and this < 10 }})
}
BAML
class Foo {
// @assert will be applied to the field with no name
bar int @assert({{ this > 0 and this < 10 }})
}
BAML
class MyClass {
// @assert will be applied to each element in the array
my_field (string @assert(is_valid_email, {{ this|regex_match("@") }}))[]
}

Parameter Assertion

Asserts can also be applied to parameters.

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

Block Assertion

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

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

See Jinja in Attributes for a longer description of the Jinja syntax available in asserts.