@@dynamic

The @@dynamic attribute in BAML allows for the dynamic modification of fields or values at runtime. This is particularly useful when you need to adapt the structure of your data models based on runtime conditions or external inputs.

Usage

Dynamic Classes

The @@dynamic attribute can be applied to classes, enabling the addition of fields dynamically during runtime.

BAML
1class MyClass {
2 property1 string
3 property2 int?
4
5 @@dynamic // allows adding fields dynamically at runtime
6}

Dynamic Enums

Similarly, the @@dynamic attribute can be applied to enums, allowing for the modification of enum values at runtime.

BAML
1enum MyEnum {
2 Value1
3 Value2
4
5 @@dynamic // allows modifying enum values dynamically at runtime
6}

Using @@dynamic with TypeBuilder

To modify dynamic types at runtime, you can use the TypeBuilder from the baml_client. Below are examples for Python, TypeScript, and Ruby.

Python Example

1from baml_client.type_builder import TypeBuilder
2from baml_client import b
3
4async def run():
5 tb = TypeBuilder()
6 tb.MyClass.add_property('email', tb.string())
7 tb.MyClass.add_property('address', tb.string()).description("The user's address")
8 res = await b.DynamicUserCreator("some user info", { "tb": tb })
9 # Now res can have email and address fields
10 print(res)

TypeScript Example

1import TypeBuilder from '../baml_client/type_builder'
2import { b } from '../baml_client'
3
4async function run() {
5 const tb = new TypeBuilder()
6 tb.MyClass.addProperty('email', tb.string())
7 tb.MyClass.addProperty('address', tb.string()).description("The user's address")
8 const res = await b.DynamicUserCreator("some user info", { tb: tb })
9 // Now res can have email and address fields
10 console.log(res)
11}

Ruby Example

1require_relative 'baml_client/client'
2
3def run
4 tb = Baml::TypeBuilder.new
5 tb.MyClass.add_property('email', tb.string)
6 tb.MyClass.add_property('address', tb.string).description("The user's address")
7
8 res = Baml::Client.dynamic_user_creator(input: "some user info", baml_options: {tb: tb})
9 # Now res can have email and address fields
10 puts res
11end