Baml uses a custom Deserializer to parse a string into the desired type. You don’t have to do anything to enable to deserializer, it comes built in.

Instead of doing the following, you can rely on BAML to do the parsing for you.

# Example parsing code you might be writing today
# without baml
import json

openai_response_text = await openai.completions.create(
  ...
)
response = SomePydanticModel(**json.loads(openai_response_text))

Examples

LLM OutputDesired TypeBaml OutputHow
greatStyleStyle.GREATWe handle case insensitivity
"great"StyleStyle.GREATWe handle extra quotes
greatStyle[][Style.GREAT]Non-array types are automatically wrapped in an array
{ "feeling": "great" }StyleStyle.GREATWhen looking for a singular value, we can parse dictionaries of 1 keys as singular objects
Some text that goes before…
```json
{“feeling”: “great”}
```
Some text that came after
StyleStyle.GREATWe can find the inner json object and parse it even when surrounded by lots of text

Note, we can apply the same parsing logic to any type, not just enums. e.g. in the case of numbers, we can remove commas and parse the number. This page outlines all the rules we use to parse each type.

The deserializer makes 0 external calls and runs fully locally!

Error handling

All parsing errors are handled by the Deserializer and will raise a DeserializerException.

from baml_client import baml as b
from baml_client import DeserializerException

try:
  response = await b.SomeAIFunction(query="I want to buy a car")
except DeserializerException as e:
  # The parser was not able read the response as the expected type
  print(e)

Primitive Types

TODO: Include a section on how each type is parsed and coerced from other types.

Composite/Structured Types

enum

See: Prompt engineering > Enum > @alias

class

See: Prompt engineering > Class

Optional (?)

If the type is optional, the parser will attempt to parse the value as the type, or return null if we failed to parse.

Union (|)

Unions are parsed in left to right order. The first type that successfully parses the value will be returned. If no types are able to parse the value, a DeserializerException will be raised.

List/Array ([])

Lists parse each element in the list as the type specified in the list.

  • It will always return a list, even if the list is empty.
  • If an element fails to parse, it is skipped and not included in the final list.
  • If the value is not a list, the parser will attempt to parse the value as the type and return a list with a single element.