Types and Schemas
BAML’s type system enables you to extract structured, validated data from LLMs. Every BAML function has a return type that defines the schema of the output.Why Types Matter
BAML transforms prompt engineering into schema engineering. Instead of wrestling with string outputs, you define the structure you want and BAML handles:- Generating schema instructions for the LLM
- Parsing and validating responses
- Type-safe code generation in your target language
- Flexible parsing that works even with imperfect LLM outputs
Primitive Types
BAML supports standard primitive types:Example
Literal Types
Constrain primitives to specific values:"bug" or "enhancement" - BAML validates this.
Enums
For a fixed set of named values, use enums:Enum with Descriptions
Add descriptions to help the LLM choose correctly:Enum Aliases
Map enum values to different string representations:Classes
Classes define structured objects with named fields:Field Modifiers
Optional fields use?:
[]:
Field Attributes
@description: Guide the LLM on what to extractMultimodal Types
BAML supports rich media inputs:Image
Audio
Video
Arrays
Arrays work with any type:Unions
Return one of multiple types:- Tool calling / function selection
- Success/error responses
- Multiple output formats
Maps/Dictionaries
For key-value pairs:Nested Structures
BAML handles deeply nested schemas:Dynamic Types
For types that need to be modified at runtime:Type Validation
BAML validates outputs to ensure they match your schema:- Primitive types: Checks type correctness (int vs string, etc.)
- Enums: Validates against allowed values
- Classes: Verifies all required fields are present
- Arrays: Ensures all elements match the expected type
- Optionals: Allows null or missing values
Flexible Parsing
BAML’s Schema-Aligned Parsing (SAP) is more forgiving than strict JSON validation:- Handles markdown code blocks around JSON
- Accepts chain-of-thought reasoning before the JSON
- Tolerates minor formatting issues
- Works with models that don’t support native tool calling
Generated Types
BAML generates idiomatic types in your target language:- Python
- TypeScript
- Ruby
- Go
Best Practices
- Use descriptions liberally: They guide the LLM and serve as documentation
- Make optional what might be missing: Use
?for fields that may not exist - Prefer enums over string literals: When you have a known set of values
- Keep schemas focused: Break complex extractions into multiple functions
- Test with real data: Use the BAML playground to validate your schemas
Next Steps
Functions
Learn how functions use types
Prompts
Use types in your prompts
Testing
Test your type schemas
Type Reference
Complete type system reference