How BAML Provides Type-Safe Prompt Functions with Built-In Tests
BAML (Boundary AI Markup Language) treats LLM prompts as typed functions inside .baml files (baml_src/), with a compiler that generates strongly typed client SDKs (for TypeScript, Python, Ruby, Go, and more) along with a fault-tolerant structured parser and built-in test blocks.
- Schema-driven prompts and resilient parsing (
{{ ctx.output_format }}): Instead of hand-writing brittle JSON Schemas or string-slicing model outputs, you declareclass,enum, union/literal types, andfunctionsignatures in BAML. BAML injects output-format instructions into the prompt and uses a compiler-generated parser that handles extra prose, coerces compatible types, and validates against your declared return type. - First-class
testblocks alongside functions: You definetest <Name>blocks directly in.bamlfiles—passing sample inputs (args) and running assertions against the typed return value—so you can execute and filter prompt tests via CLI (baml-cli test) or the editor playground without wiring separate test harnesses just to inspect prompt outputs. - Generated typed client (
baml_client) and streaming partials: Runningbaml-cli generate(or saving in the VS Code/Cursor BAML extension) generatesbaml_clientso your TypeScript orchestration code callsb.MyFunction(...)with full static types andb.stream.MyFunction(...)for typed incremental partials.
Steps to Build and Test Typed BAML Prompt Functions
- Initialize
baml_srcand configuregeneratorandclientblocks: Set upbaml_src/(vianpx baml-cli initor your.bamlfiles) with ageneratorblock (such astypescript) and one or moreclientblocks (such as OpenAI, Anthropic, or fallback/retry clients). - Define typed models and
functionprompts: Declareclass/enumtypes and afunction Name(params...) -> ReturnTypeblock containingclientandprompt #"..."#with template variables and{{ ctx.output_format }}. - Add
testblocks withfunctionsandargs: Writetestblocks referencing the target function(s), input arguments, and assertion checks, then run them withbaml-cli test(using-i/-xfilters and--parallelin CI). - Generate
baml_clientand call from TypeScript: Runnpx baml-cli generateon schema/prompt changes and importb(and generated types) from./baml_clientin your Node.js/TypeScript service.
TypeScript / BAML Example: Typed Ticket Triage Function, Built-In Tests, and Client Call
// baml_src/generators.baml
generator ts_client {
output_type "typescript"
output_dir "../src/baml_client"
module_format "esm"
}
// baml_src/clients.baml
client<llm> FastOpenAI {
provider openai
options {
model "gpt-4o-mini"
api_key env.OPENAI_API_KEY
}
}
// baml_src/triage.baml
enum TicketPriority {
LOW
MEDIUM
HIGH
URGENT
}
class TriageResult {
category string @description(#"Short domain tag such as billing, auth, webhook, or timeout"#)
priority TicketPriority
requiresHumanEscalation bool
summary string @description(#"One-sentence summary of the issue"#)
}
function TriageSupportTicket(ticketText: string, customerTier: "free" | "pro" | "enterprise") -> TriageResult {
client FastOpenAI
prompt #"
Classify and summarize the following customer support ticket.
Customer tier: {{ customerTier }}
Ticket:
{{ ticketText }}
{{ ctx.output_format }}
"#
}
test UrgentEnterpriseTimeout {
functions [TriageSupportTicket]
args {
customerTier "enterprise"
ticketText "Production checkout webhooks are returning HTTP 524 after 100s since 02:15 UTC."
}
@@assert {{ this.priority == "URGENT" }}
@@assert {{ this.requiresHumanEscalation == true }}
@@assert {{ this.summary | length > 10 }}
}
test BasicBillingQuestion {
functions [TriageSupportTicket]
args {
customerTier "free"
ticketText "Where can I download last month's invoice PDF?"
}
@@assert {{ this.priority == "LOW" or this.priority == "MEDIUM" }}
@@assert {{ this.requiresHumanEscalation == false }}
}
// src/runTriage.ts
import { b } from "./baml_client/index.js";
import type { TriageResult } from "./baml_client/types.js";
export async function runTicketTriage(
ticketText: string,
customerTier: "free" | "pro" | "enterprise"
): Promise<TriageResult> {
// Return type is statically TriageResult and parsed/validated at runtime by BAML
const result = await b.TriageSupportTicket(ticketText, customerTier);
return result;
}
export async function streamTicketTriage(
ticketText: string,
customerTier: "free" | "pro" | "enterprise",
onPartial: (partialSummary?: string) => void
): Promise<TriageResult> {
const stream = b.stream.TriageSupportTicket(ticketText, customerTier);
for await (const partial of stream) {
onPartial(partial.summary ?? undefined);
}
return await stream.getFinalResponse();
}
Helpful Tips for Production BAML Workflows
- Commit
.bamlsource files and regeneratebaml_clientin builds/CI: Treatbaml_src/*.bamlas your source of truth and runnpx baml-cli generatebeforetscin your build/CI pipeline so generated types never drift from prompt definitions. - Scope
baml-cli testruns in CI with filters and concurrency caps: Use-i/-xpatterns and--parallelinbaml-cli testto target critical functions or fast smoke tests on pull requests while keeping full suite runs isolated from live rate limits. - Pair
.bamltests with deterministic HTTP fixture tests in TypeScript: Built-in BAML tests validate prompt behavior and assertions cleanly, while deterministic HTTP replay fixtures in your Node.js test suite let you test app-level retry/timeout/error wrappers without hitting live APIs on every unit test run.
You must log in or register to comment.
