TypeBuilder is used to create or modify output schemas at runtime. It’s particularly useful when you have dynamic output structures that can’t be determined at compile time - like categories from a database or user-provided schemas.
Here’s a simple example of using TypeBuilder to add new enum values before calling a BAML function:
BAML Code
Runtime Usage
There are two ways to use TypeBuilder:
@@dynamicTo modify an existing BAML type, mark it with @@dynamic:
Runtime Usage
Runtime Usage
You can also create entirely new types at runtime:
TypeBuilder provides methods for building different kinds of types:
In addition to the methods above, all types marked with @@dynamic will also appear in the TypeBuilder.
FieldType is a type that represents a field in a type. It can be used to add descriptions, constraints, and other metadata to a field.
ClassBuilder is a type that represents a class in a type. It can be used to add properties to a class.
ClassPropertyBuilder is a type that represents a property in a class. It can be used to add descriptions, constraints, and other metadata to a property.
EnumBuilder is a type that represents an enum in a type. It can be used to add values to an enum.
EnumValueBuilder is a type that represents a value in an enum. It can be used to add descriptions, constraints, and other metadata to a value.
You can add descriptions to properties and enum values to help guide the LLM:
add_baml methodThe TypeBuilder has a higher level API for creating dynamic types at runtime.
Here’s an example:
Here are some common patterns when using TypeBuilder:
All types added through TypeBuilder must be connected to the return type of your BAML function. Standalone types that aren’t referenced won’t affect the output schema.
See the advanced dynamic types tests guide for examples of testing functions that use dynamic types. See also the reference for syntax.
We’re working on additional features for TypeBuilder:
If you’re interested in these features, please join the discussion in our GitHub issues.