function
Functions in BAML define the contract between your application and AI models, providing type-safe interfaces for AI operations.
Overview
A BAML function consists of:
- Input parameters with explicit types
- A return type specification
- An LLM client
- A prompt (as a block string)
Function Declaration
Syntax
Parameters
name: The function identifier (must start with a capital letter!)parameters: One or more typed parameters (e.g.,text: string,data: CustomType)return_type: The type that the function guarantees to return (e.g.,string | MyType)llm_specification: The LLM to use (e.g.,"openai/gpt-5-mini",GPT5,Claude4)block_string_specification: The prompt template using Jinja syntax
Type System
Functions leverage BAML’s strong type system, supporting:
Built-in Types
string: Text dataint: Integer numbersfloat: Decimal numbersbool: True/false valuesarray: Denoted with[]suffix (e.g.,string[])map: Key-value pairs (e.g.,map<string, int>)literal: Specific values (e.g.,"red" | "green" | "blue")- See all
Custom Types
Custom types can be defined using class declarations:
Prompt Templates
Jinja Syntax
BAML uses Jinja templating for dynamic prompt generation:
Special Variables
ctx.output_format: Automatically generates format instructions based on return typectx.client: Selected client and model name_.role: Define the role of the message chunk
Error Handling
Functions automatically handle common AI model errors and provide type validation:
- JSON parsing errors are automatically corrected
- Type mismatches are detected and reported
- Network and rate limit errors are propagated to the caller