BAML Python Bindings

0.220.0 · active · verified Wed Apr 15

BAML (Basically a Made-up Language) is a domain-specific language and toolchain designed to build reliable AI workflows and agents by transforming prompt engineering into schema engineering. It generates type-safe client code for Python (and other languages like TypeScript, Ruby, Go), enabling structured outputs from Large Language Models with built-in features like streaming, retries, and broad model support. The library is actively maintained with frequent releases, currently at version 0.220.0.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `baml-py` after initializing a BAML project and generating client code. First, install `baml-py` and use `baml-cli init` to create a `baml_src` directory with example BAML functions (e.g., `ExtractResume` defined in a `.baml` file). Then, run `baml-cli generate` to create the `baml_client` Python module. The generated client (`b`) allows you to call your BAML-defined functions directly from Python with type-safety. Ensure necessary LLM API keys (e.g., `OPENAI_API_KEY`) are set in your environment.

import os

# NOTE: This example assumes you have run 'baml-cli init' and 'baml-cli generate'.
# A 'baml_src' directory with a BAML function (e.g., ExtractResume) and a 'baml_client'
# directory with generated code must exist in your project.

# Example BAML function definition (e.g., in baml_src/main.baml):
# class Resume {
#   name string
#   title string
# }
# function ExtractResume(resume_text: string) -> Resume {
#   client "openai/gpt-4o"
#   prompt """
#     Parse the following resume and return structured data.
#     {{ resume_text }}
#     {{ ctx.output_format }}
#   """
# }

# Ensure your OpenAI API key is set as an environment variable
os.environ['OPENAI_API_KEY'] = os.environ.get('OPENAI_API_KEY', 'sk-fake-key-for-test')

from baml_client.sync_client import b
from baml_client.types import Resume

def process_resume(resume_text: str) -> Resume:
    print(f"Processing resume: {resume_text[:50]}...")
    try:
        # Call your BAML function, which is now a Python method on 'b'
        response = b.ExtractResume(resume_text=resume_text)
        print("Successfully extracted resume data:")
        print(f"  Name: {response.name}")
        print(f"  Title: {response.title}")
        return response
    except Exception as e:
        print(f"An error occurred: {e}")
        # In a real application, you'd handle specific BAML errors like BamlValidationError
        raise

if __name__ == "__main__":
    sample_resume = (
        "Name: Alice Wonderland\n"
        "Title: Software Engineer\n"
        "Experience: 5 years at ExampleCorp, developing scalable backend services.\n"
        "Education: M.S. Computer Science, University of XYZ"
    )
    
    # This call would only succeed if a baml_src/main.baml with ExtractResume is defined 
    # and baml-cli generate has been run.
    # mock_resume_data = process_resume(sample_resume)
    print("To run this, ensure baml-cli init and baml-cli generate have been executed.")
    print("And OPENAI_API_KEY is set in your environment.")

view raw JSON →