Dynamic Types - TypeBuilder
Sometimes you have output schemas that change at runtime — for example if you have a list of Categories that you need to classify that come from a database, or your schema is user-provided.
TypeBuilder
is used to create or modify dynamic types at runtime to achieve this.
Dynamic BAML Enums
Imagine we want to make a categorizer prompt, but the list of categories to output come from a database.
- Add
@@dynamic
to the class or enum definition to mark it as dynamic in BAML.
- Import the
TypeBuilder
from baml_client in your runtime code and modifyCategory
. All dynamic types you define in BAML will be available as properties ofTypeBuilder
. Think of the typebuilder as a registry of modified runtime types that the baml function will read from when building the output schema in the prompt.
Python
TypeScript
Ruby
OpenAPI
Dynamic BAML Classes
Now we’ll add some properties to a User
class at runtime using @@dynamic.
We can then modify the User
schema at runtime. Since we marked User
with @@dynamic
, it’ll be available as a property of TypeBuilder
.
Creating new dynamic classes or enums not in BAML
The previous examples showed how to modify existing types. Here we create a new Hobbies
enum, and a new class called Address
without having them defined in BAML.
Note that you must attach the new types to the existing Return Type of your BAML function(in this case it’s User
).
TypeBuilder provides methods for building different kinds of types:
Adding descriptions to dynamic types
Building dynamic types from JSON schema
We have a working implementation of this, but are waiting for a concrete use case to merge it. Please chime in on the GitHub issue if this is something you’d like to use.
Testing dynamic types in BAML
This feature is coming soon! Let us know if you’re interested in testing it out!
You can still write tests in Python, TypeScript, Ruby, etc in the meantime.