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:

1function FunctionName(param: Type) -> ReturnType {
2 client ModelName
3 prompt #"
4 Template content
5 "#
6}

Function Declaration

Syntax

1function name(parameters) -> return_type {
2 client llm_specification
3 prompt block_string_specification
4}

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-4o-mini", GPT4Turbo, Claude2)
  • block_string_specification: The prompt template using Jinja syntax

Type System

Functions leverage BAML’s strong type system, supporting:

Built-in Types

  • string: Text data
  • int: Integer numbers
  • float: Decimal numbers
  • bool: True/false values
  • array: 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:

1class CustomType {
2 field1 string
3 field2 int
4 nested NestedType
5}
6
7function ProcessCustomType(data: CustomType) -> ResultType {
8 // ...
9}

Prompt Templates

Jinja Syntax

BAML uses Jinja templating for dynamic prompt generation:

1prompt #"
2 Input data: {{ input_data }}
3
4 {% if condition %}
5 Conditional content
6 {% endif %}
7
8 {{ ctx.output_format }}
9"#

Special Variables

  • ctx.output_format: Automatically generates format instructions based on return type
  • ctx.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

Usage Examples

Basic Function

1function ExtractEmail(text: string) -> string {
2 client GPT4Turbo
3 prompt #"
4 Extract the email address from the following text:
5 {{ text }}
6
7 {{ ctx.output_format }}
8 "#
9}

Complex Types

1class Person {
2 name string
3 age int
4 contacts Contact[]
5}
6
7class Contact {
8 type "email" | "phone"
9 value string
10}
11
12function ParsePerson(data: string) -> Person {
13 client "openai/gpt-4o"
14 prompt #"
15 {{ ctx.output_format }}
16
17 {{ _.role('user') }}
18 {{ data }}
19 "#
20}

baml_client Integration

1from baml_client import b
2from baml_client.types import Person
3
4async def process() -> Person:
5 result = b.ParsePerson("John Doe, 30 years old...")
6 print(result.name) # Type-safe access
7 return result