How do you use BAML (Basically a Made-up Language) to write type-safe prompt functions with built-in tests? | A1Lab@HamzaM to AI & LLMEnglish • 4 days ago

How do you use BAML (Basically a Made-up Language) to write type-safe prompt functions with built-in tests?

message-square
0

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 declare class, enum, union/literal types, and function signatures 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 test blocks alongside functions: You define test <Name> blocks directly in .baml files—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: Running baml-cli generate (or saving in the VS Code/Cursor BAML extension) generates baml_client so your TypeScript orchestration code calls b.MyFunction(...) with full static types and b.stream.MyFunction(...) for typed incremental partials.

Steps to Build and Test Typed BAML Prompt Functions

  1. Initialize baml_src and configure generator and client blocks: Set up baml_src/ (via npx baml-cli init or your .baml files) with a generator block (such as typescript) and one or more client blocks (such as OpenAI, Anthropic, or fallback/retry clients).
  2. Define typed models and function prompts: Declare class / enum types and a function Name(params...) -> ReturnType block containing client and prompt #"..."# with template variables and {{ ctx.output_format }}.
  3. Add test blocks with functions and args: Write test blocks referencing the target function(s), input arguments, and assertion checks, then run them with baml-cli test (using -i / -x filters and --parallel in CI).
  4. Generate baml_client and call from TypeScript: Run npx baml-cli generate on schema/prompt changes and import b (and generated types) from ./baml_client in 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 .baml source files and regenerate baml_client in builds/CI: Treat baml_src/*.baml as your source of truth and run npx baml-cli generate before tsc in your build/CI pipeline so generated types never drift from prompt definitions.
  • Scope baml-cli test runs in CI with filters and concurrency caps: Use -i / -x patterns and --parallel in baml-cli test to target critical functions or fast smoke tests on pull requests while keeping full suite runs isolated from live rate limits.
  • Pair .baml tests 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.