Skip to main content

Functions

Functions in BAML define type-safe contracts between your application and AI models.

Syntax​

function FunctionName(param: Type) -> ReturnType {
client ModelSpec
prompt #"
Template content
"#
}

Components​

ComponentDescriptionExample
nameFunction identifier (must start with capital letter)ExtractEmail
parametersTyped input parameterstext: string, data: MyClass
return_typeGuaranteed output typestring, MyClass, "a" | "b"
clientLLM specification"openai/gpt-4o", GPT4
promptJinja templateBlock string with {{ }}

Basic Example​

function ExtractEmail(text: string) -> string {
client "openai/gpt-4o"
prompt #"
Extract the email address from the following text:
{{ text }}

{{ ctx.output_format }}
"#
}

Client Specification​

Shorthand Syntax​

function MakeHaiku(topic: string) -> string {
client "openai/gpt-4o"
prompt #"
Write a haiku about {{ topic }}.
"#
}

Named Client​

client<llm> MyClient {
provider "openai"
options {
model "gpt-4o"
}
}

function MakeHaiku(topic: string) -> string {
client MyClient
prompt #"
Write a haiku about {{ topic }}.
"#
}

Type System​

Functions support all BAML types:

Built-in Types​

TypeDescription
stringText data
intInteger numbers
floatDecimal numbers
boolTrue/false values
Type[]Arrays
map<K, V>Key-value pairs
"a" | "b"Literal unions

Custom Types​

class Person {
name string
age int
contacts Contact[]
}

class Contact {
type "email" | "phone"
value string
}

function ParsePerson(data: string) -> Person {
client "openai/gpt-4o"
prompt #"
{{ ctx.output_format }}

{{ _.role('user') }}
{{ data }}
"#
}

Prompt Templates​

Jinja Syntax​

prompt #"
Input data: {{ input_data }}

{% if condition %}
Conditional content
{% endif %}

{{ ctx.output_format }}
"#

Special Variables​

VariableDescription
ctx.output_formatAuto-generated format instructions based on return type
ctx.clientSelected client and model name
_.role()Define message role (system, user, assistant)

Error Handling​

BAML functions automatically handle:

  • JSON parsing errors (auto-corrected)
  • Type mismatches (detected and reported)
  • Network and rate limit errors (propagated to caller)

Generated Client Usage​

from baml_client import b
from baml_client.types import Person

async def process() -> Person:
result = await b.ParsePerson("John Doe, 30 years old...")
print(result.name) # Type-safe access
return result

See Also​