TypeBuilder
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
Dynamic Types
There are two ways to use TypeBuilder:
- Modifying existing BAML types marked with
@@dynamic
- Creating entirely new types at runtime
Modifying Existing Types
To modify an existing BAML type, mark it with @@dynamic
:
Runtime Usage
Runtime Usage
Creating New Types
You can also create entirely new types at runtime:
Type Builders
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
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
ClassBuilder
is a type that represents a class in a type. It can be used to add properties to a class.
ClassPropertyBuilder
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
EnumBuilder
is a type that represents an enum in a type. It can be used to add values to an enum.
EnumValueBuilder
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.
Adding Descriptions
You can add descriptions to properties and enum values to help guide the LLM:
Creating/modyfing dynamic types with the add_baml
method
The TypeBuilder
has a higher level API for creating dynamic types at runtime.
Here’s an example:
Common Patterns
Here are some common patterns when using TypeBuilder:
- Dynamic Categories: When categories come from a database or external source
- Form Fields: When extracting dynamic form fields
- Optional Properties: When some fields might not be present
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.
Testing Dynamic Types
See the advanced dynamic types tests guide for examples of testing functions that use dynamic types. See also the reference for syntax.
Future Features
We’re working on additional features for TypeBuilder:
- JSON Schema support (awaiting use cases)
- OpenAPI schema integration
- Pydantic model support
If you’re interested in these features, please join the discussion in our GitHub issues.