Back to Baml

Assert

fern/03-reference/baml/attributes/assert.mdx

0.222.01.3 KB
Original Source

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.