BAML
QuickstartPodcastTeamChangelogagent tries baml
DiscordGitHub8,423Learn BAML
Learn BAMLQuickstartPodcastTeamChangelogagent tries baml
DiscordGitHub8,423
Back to Episodes
#28
9 months ago

πŸ¦„ Agentic RAG + Context Engineering

In this conversation, Vaibhav Gupta and Dex explore the intricacies of building an Agentic Retrieval-Augmented Generation (RAG) system. They discuss the differences between traditional RAG and Agentic RAG, emphasizing the flexibility and decision-making capabilities of the latter. The conversation includes a live demo of a coding agent, insights into the coding architecture, challenges faced during tool implementation, and the iterative process of refining the system. They also touch on the integration of web search functionalities and the evaluation of tool effectiveness, providing a comprehensive overview of the development process and the underlying principles of Agentic RAG systems. In this conversation, Vaibhav Gupta and Dex discuss the intricacies of building dynamic AI systems, focusing on tool implementation, user interface optimization, and model performance. They explore the importance of reinforcement learning in training models, the challenges of debugging AI systems, and the significance of writing code to enhance understanding and efficiency in AI development. The dialogue emphasizes the balance between different AI approaches and the necessity of real use cases in building effective solutions.

Project Details

Open in GitHub

Exploring the intricacies of building an Agentic Retrieval-Augmented Generation (RAG) system, emphasizing the flexibility and decision-making capabilities that distinguish it from traditional RAG approaches.

Episode Summary

Vaibhav Gupta demonstrates building a complete Agentic RAG system from scratch in just 3 hours, showing the crucial difference between deterministic RAG pipelines and agent-driven context assembly. The live coding session reveals that while the agent loop itself is straightforward, the real complexity lies in tool implementation details - from handling relative paths in grep results to managing working directories and truncation notices.

Key Insights

Agentic RAG vs Traditional RAG

"RAG is a system that takes in a user query and looks into some database... Traditional RAG uses vector search 100% of the time. Agentic RAG lets the model decide if it needs to RAG anything at all."

  • Traditional RAG: Deterministic code fetches context based on vector similarity every time
  • Agentic RAG: Model decides which tools to use and what context to retrieve
  • Trade-off: Flexibility and capability vs speed and predictability

The 3-Hour Build Breakdown

  • Hour 1: Basic agent loop and tool definitions (30% hand-written, 70% AI-generated)
  • Hour 2: Building UI/TUI for effective iteration and debugging
  • Hour 3: Refining tool implementations based on testing

"Most of the time actually came from UI time, not from anything else."

Critical Tool Implementation Details

What Actually Mattered:

  • Using relative paths instead of absolute paths in grep results
  • Tracking and injecting current working directory into prompts
  • Adding clear truncation notices with line numbers
  • Implementing proper timeouts for all subprocess calls
  • Using ripgrep (rg) instead of standard grep

What Didn't Matter:

  • Tool definition prompts (never changed after initial write)
  • Complex retry logic
  • Structured tool response formats

The Architecture Pattern

User Query β†’ [Agent Loop with Tools] β†’ Response
           ↓
    Iterations (tool calls)
           ↓
    Tool Results β†’ Back to Agent

Each iteration can call tools or respond to user. Sub-agents spawn fresh contexts but can't spawn more sub-agents (preventing infinite recursion).

Context Engineering Lessons

"That's context engineering. How do you make it more context efficient? Every single token counts. When you save 20 tokens per call and you're gonna grep 30 times, that makes a huge difference."

Key Optimizations:

  • Render tools in simplified format, not full JSON
  • Use [Dir] and [File] prefixes in ls output
  • Truncate file reads at 20K chars or 5K lines with clear instructions
  • Strip HTML to text in web fetch, save full content to file if needed

Error Handling Philosophy

Instead of forcing models to retry on parse errors, detect intent:

  • If response starts with backticks but not JSON β†’ probably meant for user
  • Keep error corrections temporary, don't pollute context history
  • Add "invalid response" feedback but remove after correction

When to Use Agentic RAG

Use Agentic RAG When:

  • Problem scope is unbounded
  • User queries vary widely
  • You need web search + code search + docs
  • Flexibility matters more than speed

Avoid Agentic RAG When:

  • Problem scope is well-defined
  • Speed is critical
  • Most queries follow similar patterns
  • You can predict needed context

"Most people should not build agentic RAG systems for their workflows. If you're building a software stack, most problems are not so wide that you need an agentic rag system."

Model Considerations

  • GPT-4o works well out of the box
  • Smaller models (GPT-4o-mini) struggle with complex tool orchestration
  • Line numbers in file reads work without special training
  • RL/fine-tuning helps but isn't required for basic functionality

The Build Philosophy

"Writing the code helps me understand how it works. If I use a Claude Agent SDK, I don't actually understand what a system is doing."

Build from first principles to understand:

  • System design trade-offs
  • Where complexity actually lives
  • What optimizations matter
  • How to debug when things fail

Practical Implementation Tips

  1. Start with a baseline: Build deterministic RAG first, then add agent capabilities
  2. Invest in UI early: Good debugging UI is crucial for iteration
  3. Test with consistent queries: Use the same 10 queries repeatedly during development
  4. Track tool sequences: Focus on which tools are called in what order, not just final output
  5. Handle state carefully: Preserve working directory, track file modifications
  6. Optimize for context: Every token saved in tool responses compounds across iterations

The Bottom Line

Agentic RAG isn't technically complex - you can build one in 3 hours. The challenge is making tools context-efficient and deciding if you actually need the flexibility versus a faster, deterministic pipeline. As Dex summarizes: "The answer is what solves your user's problem."

Running the Code

Quick Start

# Clone the repository
git clone https://github.com/ai-that-works/ai-that-works.git
cd ai-that-works/2025-10-21-agentic-rag-context-engineering

# Install dependencies
uv sync

# Generate BAML client
uv run baml-cli generate

# Set your API keys
export OPENAI_API_KEY="your-key-here"
export EXA_API_KEY="your-exa-key-here"  # Optional, for WebSearch tool

# Run the agent (CLI mode)
uv run python main.py "What files are in this directory?"

# Run in beautiful TUI mode (recommended)
uv run python main.py "Start" --tui

# Interactive mode
uv run python main.py "Start" --interactive

Available Commands

# Single query
uv run python main.py "What does the fern folder do?"

# Work in a specific directory
uv run python main.py "Find all Python files" --dir /path/to/project

# TUI with specific directory
uv run python main.py "Start" --tui --dir ~/myproject

Whiteboards

To be added during the session

Links

  • Episode Recording
  • Source Code
  • BAML Language
  • Discord Community

Code Demo: Agent System Built with BAML

An agent system built with BAML that can execute various tools using pattern matching.

Overview

This project demonstrates an agentic system that:

  • Uses BAML to define tool schemas and agent behavior
  • Implements tool handlers using Python's match statement
  • Supports 16 different tool types for file operations, code execution, web fetching, and more

Architecture

BAML Components

  • baml_src/agent-tools.baml: Defines all tool types with full descriptions embedded in @description annotations
  • baml_src/agent.baml: Defines the agent loop function that decides which tools to call
  • main.py: Python implementation with tool handlers using pattern matching

Tool Types

The agent supports the following tools:

  1. AgentTool - Launch recursive sub-agents (fully implemented)
  2. BashTool - Execute bash commands (fully implemented)
  3. GlobTool - Find files by glob patterns (fully implemented)
  4. GrepTool - Search file contents with regex (fully implemented)
  5. LSTool - List directory contents (fully implemented)
  6. ReadTool - Read files with line numbers (fully implemented)
  7. EditTool - Edit files with string replacement (fully implemented)
  8. MultiEditTool - Multiple edits in one operation (fully implemented)
  9. WriteTool - Write new files (fully implemented)
  10. NotebookReadTool - Read Jupyter notebooks (fully implemented)
  11. NotebookEditTool - Edit Jupyter notebook cells (fully implemented)
  12. WebFetchTool - Fetch and process web content (requires requests + beautifulsoup4)
  13. TodoReadTool - Read todo list (in-memory storage)
  14. TodoWriteTool - Write todo list (in-memory storage)
  15. WebSearchTool - Search the web (stub - requires search API)
  16. ExitPlanModeTool - Exit planning mode

Tool Handler Pattern

All tools are handled through a single async execute_tool() function using Python 3.10+ match statements on the action field:

async def execute_tool(tool: types.AgentTools) -> str:
    """Execute a tool based on its type using match statement"""
    match tool.action:
        case "Bash":
            return execute_bash(tool)
        case "Glob":
            return execute_glob(tool)
        case "Agent":
            return await execute_agent(tool)  # Async for recursive calls
        # ... etc for all 16 tools
        case other:
            return f"Unknown tool type: {other}"

Setup

Prerequisites

  • Python 3.10+ (required for match statements)
  • OpenAI API key (set as OPENAI_API_KEY environment variable)
  • Exa API key (set as EXA_API_KEY environment variable) - for WebSearch tool

Installation

# Install dependencies
uv sync

# Generate BAML client
uv run baml-cli generate

Running

# Set your API keys
export OPENAI_API_KEY="your-key-here"
export EXA_API_KEY="your-exa-key-here"  # Optional, for WebSearch tool

# Run a single command (uses current directory)
uv run python main.py "What files are in this directory?"

# Interactive mode - keeps asking for commands
uv run python main.py "List files" --interactive

# TUI mode - beautiful text user interface 🎨
uv run python main.py "Start" --tui

# TUI with specific directory
uv run python main.py "Start" --tui --dir ~/myproject

# Specify a working directory (CLI mode)
uv run python main.py "Find all Python files" --dir /path/to/project

# View all options
uv run python main.py --help

User Interfaces

TUI Mode (Recommended) 🎨

Beautiful text user interface with real-time updates:

uv run python main.py "Start" --tui

Features:

  • Status Bar: Shows working directory, iteration count, and agent status
  • Main Log: Pretty-formatted output with panels for tools, results, and agent replies
    • Auto-scrolls to latest content
    • Real-time updates as tools execute
  • Todo Panel: Live view of the todo list on the right side
  • Input Box: Command input at the bottom
  • Conversation History: Maintained across commands for context continuity
  • Responsive UI: Agent runs in background thread, UI stays snappy
  • Keyboard Shortcuts:
    • Enter: Submit command
    • Enter (empty): Continue agent execution after text replies
    • Ctrl+R: Reset conversation history
    • Ctrl+X: Interrupt agent execution
    • Ctrl+C: Quit application

CLI Modes

Single Command Mode:

uv run python main.py "What files are in this directory?"

Interactive Mode:

uv run python main.py "Start" --interactive
  • Prompts for commands via input() after each task
  • Type exit, quit, or q to exit
  • Ctrl+C returns to prompt instead of exiting

Agent Loop

The agent loop:

  1. Takes a user message
  2. Calls the BAML AgentLoop function
  3. Executes any tools the LLM requests
  4. Feeds tool results back to the LLM
  5. Repeats until the LLM replies to the user (default max: 999 iterations)

Key Features

Type-Safe Tool Calling

BAML generates Pydantic models for all tools, ensuring type safety:

class BashTool(BaseModel):
    action: Literal['Bash']
    command: str
    timeout: Optional[int] = None
    description: Optional[str] = None

Rich Tool Descriptions

Each tool includes its full usage documentation in the @description annotation, providing the LLM with comprehensive context about when and how to use each tool.

Modular Tool Handlers

Each tool has its own handler function that can be tested and maintained independently:

def execute_bash(tool: types.BashTool) -> str:
    """Execute a bash command and return the output"""
    try:
        result = subprocess.run(
            tool.command,
            shell=True,
            capture_output=True,
            text=True,
            timeout=tool.timeout / 1000 if tool.timeout else 120,
            cwd=os.getcwd()
        )
        return result.stdout
    except Exception as e:
        return f"Error: {str(e)}"

Dependencies

Core dependencies:

  • baml-py - BAML Python SDK
  • pydantic - Data validation
  • typing-extensions - Type hints support
  • python-dotenv - Environment variable management
  • textual - Beautiful TUI framework
  • rich - Rich text formatting

Optional dependencies for specific tools:

  • requests + beautifulsoup4 - For WebFetch tool (install with uv add requests beautifulsoup4)
  • exa-py - For WebSearch tool (install with uv add exa-py)
  • ripgrep (system package) - For Grep tool (usually pre-installed)

In-Memory State

The agent maintains in-memory state for:

  • Todo list - Stored in _todo_store global variable, persists for the lifetime of the process
  • Agent loop - Supports recursive sub-agent calls with reduced max iterations

Sub-Agents

The agent can launch sub-agents to handle focused tasks. Sub-agents use a different BAML function (SubAgentLoop) that doesn't include the AgentTool, preventing infinite recursion.

Architecture:

  • Main agent uses AgentLoop - has access to all tools including AgentTool
  • Sub-agents use SubAgentLoop - has all tools EXCEPT AgentTool
  • Sub-agents run in isolated message contexts
  • Results are returned to the main agent

In the TUI, sub-agents are visualized with indentation and depth indicators:

Iteration 1
πŸ”§ Tool: Glob
βœ… Result: [files found]

πŸ”„ Launching Sub-agent (Level 1)
  └─ Sub-agent Iteration 1
    └─ πŸ”§ Read (1/2)
       βœ“ File contents...
    └─ πŸ”§ Grep (2/2)
       βœ“ Matches found...
  βœ“ Sub-agent L1 Complete

Iteration 2
...

Visualization Features:

  • Indentation shows nesting level
  • Tool progress: (1/3) shows current tool of total
  • Depth indicator: [Sub-agent L1] in status bar
  • Compact sub-agent output to reduce visual clutter
  • Full interrupt support for sub-agents

Important Note: Sub-agents cannot spawn additional sub-agents (by design). The main agent uses AgentLoop which includes the AgentTool, while sub-agents use SubAgentLoop which excludes it. This prevents infinite recursion and keeps sub-agents focused on their specific goals.

Example Usage

Command Line

# Find package.json files
uv run python main.py "What directory contains the file 'package.json'?"

# Work in a specific directory
uv run python main.py "List all JavaScript files" --dir ~/my-project

# Interactive mode for multiple tasks
uv run python main.py "List files" --interactive

Programmatic Usage

# Find package.json files
user_query = 'What directory contains the file "package.json"?'
result = asyncio.run(agent_loop(user_query))

The agent will:

  1. Use GlobTool to find all package.json files
  2. Analyze the results
  3. Reply to the user with the answer

Command Line Options

usage: main.py [-h] [--dir DIR] [--interactive] [--tui] [--verbose] query

positional arguments:
  query                 The query or task for the agent to perform

options:
  -h, --help            show this help message and exit
  --dir DIR, -d DIR     Working directory for the agent (defaults to current directory)
  --interactive, -i     Run in interactive mode (keep asking for commands)
  --tui, -t            Run in TUI mode (beautiful text user interface)
  --verbose, -v         Enable verbose output

Note: The agent runs with a very high iteration limit (999) by default, allowing it to complete complex tasks. Sub-agents get a limit of 50 iterations.

TUI Layout

The TUI provides a beautiful interface with:

  • Color-coded tool executions (magenta panels)
  • Success results in green panels
  • User queries in blue panels
  • Live todo list updates on the right
  • Real-time status bar at the top

See TUI_LAYOUT.md for a detailed visual layout diagram.

Project Structure

2025-10-21-agentic-rag-context-engineering/
β”œβ”€β”€ baml_src/
β”‚   β”œβ”€β”€ agent-tools.baml      # Tool type definitions (AgentTools, SubAgentTools)
β”‚   β”œβ”€β”€ agent.baml             # Agent loop functions (AgentLoop, SubAgentLoop)
β”‚   β”œβ”€β”€ clients.baml           # LLM client configs
β”‚   └── generators.baml        # Code generation config
β”œβ”€β”€ baml_client/               # Auto-generated BAML client
β”œβ”€β”€ agent_runtime.py           # Shared agent state & execution logic
β”œβ”€β”€ main.py                    # Tool handlers & CLI interface
β”œβ”€β”€ tui.py                     # Beautiful TUI interface
β”œβ”€β”€ ARCHITECTURE.md            # Architecture documentation
β”œβ”€β”€ TUI_LAYOUT.md              # Visual TUI documentation
β”œβ”€β”€ pyproject.toml             # Dependencies
└── README.md                  # This file

Key Design:

  • agent_runtime.py contains all agent logic (zero duplication)
  • Both CLI and TUI use AgentRuntime with different callbacks
  • Sub-agents use SubAgentLoop (no AgentTool access)
  • All code is async using baml_client.async_client

Agent Capabilities

BAMMY is a sophisticated AI agent with professional-grade capabilities:

Core Features:

  • File System Operations: Read, write, edit, and search files
  • Code Analysis: Understand and manipulate codebases
  • Web Research: Fetch information and perform web searches
  • Task Management: Plan, track, and execute complex workflows
  • Bash Execution: Run system commands and scripts
  • Sub-Agent Delegation: Delegate complex tasks to focused sub-agents

Professional Standards:

  • Security-First: Refuses to work on malicious code
  • Convention-Aware: Follows existing code patterns and standards
  • Efficient Communication: Concise, direct responses
  • Proactive Task Management: Uses todo tools extensively
  • Quality Assurance: Runs lint/typecheck after code changes

Technical Details:

  • Uses gpt-4o-mini by default (configurable in agent.baml)
  • Tool handlers include comprehensive error handling
  • Supports recursive sub-agent delegation with infinite recursion protection
  • Maintains conversation context across iterations
  • Some tools (WebSearch, TodoRead/Write) are stubs requiring external services
  • The agent loop has a configurable max iteration limit (default: 10)
Demo CodeWatch on YouTube

All Episodes

#65
2 days ago

SOTA Coding Agent Benchmarks

We've had a lot of benchmarks for coding agents for a long time. We'll talk about the past generation and the new generation, what they're doing differently, as well as... I don't know. come hang it will be good. Meet the SpeakersπŸ§‘β€πŸ’»β€‹ ​​Meet Vaibhav Gupta, one of the creators of BAML and YC alum. He spent 10 years in AI performance optimization at places like Google, Microsoft, and D. E. Shaw. He loves diving deep and chatting about anything related to Gen AI and Computer Vision! ​Meet Dex Horthy, founder at HumanLayer and coiner of the term Context Engineering. He spent 10+ years building devops tools at Replicated, Sprout Social and JPL. DevOps junkie turned AI Engineer.

agent observability
#64
9 days ago

agent observability

In this episode, we will dive into AI agent observability and answer a question every production engineer eventually faces: how do you diagnose why an autonomous agent went off the rails three days ago? When you are dealing with non-deterministic tools, old-school debugging habits like inserting `print("here")` statements fails to scale. We will break down the essentials of modern agent tracking, from implementing structured logging for complex tool calls to establishing robust tracing that allows you to replay and reconstruct an agent's exact decision tree.

Software Factory for Agent Tools
#63
23 days ago

Software Factory for Agent Tools

Everyone's obsessed with software factories, and the core of a software factory is a persistent feedback loop - in this episode Vaibhav and Dhilan will showcase a loop they built to test new BAML language features 24/7 and improve the language based on feedback from coding agents trying to implement features.

Product Specs with AI
#62
30 days ago

Product Specs with AI

We've talked a lot about design discussions for planning work with AI and getting leverage before writing the code, but this process has a common pitfall: it combines product decisions (how does it work, what is the user experience) with technical decisions (how do we build it, what patterns do we follow). This complecting of concerns can cause important questions to be missed. On today's AI that works we'll dig into techniques to split out product vs. technical questions to enable less-technical folks to participate in product specification that is grounded in codebase research, and ensure technical depth is achieved without getting distracted by product questions.

Hands-on with Fable 5
#61
about 1 month ago

Hands-on with Fable 5

We had agent observability on the schedule, but Anthropic shipped Fable 5 about twenty minutes before we went live, so we tossed the plan and got hands-on with the new model instead. Zero prep, all live. This is an unscripted look at exactly how we kick the tires on a fresh model release: take the hardest problem you're already deep in, hand it over, and watch whether it finds leverage you didn't. Vaibhav ran it against an in-progress design doc for the BAML VM's observability layer, Dex ran it against an old race-condition benchmark he keeps around, and we talk through what the model caught, what it missed, and why most model releases are more hype than the value they deliver day to day.

How to Build AI Agents that Work in Any Language
#60
about 1 month ago

How to Build AI Agents that Work in Any Language

In this episode, we discuss the challenge of building multilingual AI applications that perform consistently whether your user is interacting in English, Spanish, French, whatever. Can you simply run an English prompt through a basic translator? Or will that break down in production? We'll be breaking down practical engineering strategies for designing flexible, cross-lingual prompt architectures that maintain semantic alignment without forcing you to build and manage separate pipelines for every language.

#59
about 2 months ago

No Vibes Allowed: Performance Engineering

This week on the podcast, we are doing another no vibes allowed episode focusing on performance engineering. We will dive into high-performance engineering on virtual machines to help you maximize efficiency out of your compute infrastructure. When you are deploying heavy LLM workloads or complex pipelines, an unoptimized VM can lead to crippling latency, memory bottlenecks, and ballooning costs that break your application in the real world. We break down practical techniques to configure your environments, manage resources, and eliminate overhead so your models run flawlessly under pressure.

How AI Agents Can Safely Ship Code to Production
#58
about 2 months ago

How AI Agents Can Safely Ship Code to Production

This week, the top headline is vibe coders realizing that they can use feature flags to ship experimental (read: slop) features to production without impacting all customers. Shipping code is a lot harder when everything is changing all the time. Feature flags can be a good technique to test various things, but how do you set that up? Do you feature flag new models? New prompts? New harnesses? We'll dive into details here and see where feature flags improve your product delivery vs. just giving you an excuse to ship more slop.

"Code Mode" Deep Dive
#57
2 months ago

"Code Mode" Deep Dive

On Monday, Pash from OpenAI shared that Codex has a secret "code mode" feature - an alternative to traditional tool calling. There's a lot of debate going on around the best way to give tools to models - skills vs. mcps, CLIs and bash vs custom tools, or letting the model write code for everything. In this episode we're going to cut through the hype and dive deep on the differences and tradeoffs between these methods. β€’ What is "code mode" and how does it work β€’ Tradeoffs between MCP vs. Bash+CLI vs. Code mode β€’ Why it matters to agent or harness builders

OpenAI tells you not to build your own harness
#56
2 months ago

OpenAI tells you not to build your own harness

Harness engineering is all the hype now, so on this week on the podcast we're looking back to an article written by OpenAI in February about harness engineering, "Harness engineering: leveraging Codex in an agent-first world". In this article, they claim that the era of "hand-written code" is officially over. We break down their experiment of shipping a million-line product with zero manual coding, shifting the human role from "coder" to "environment designer."

No Vibes Allowed - Building Design Docs with AI
#55
3 months ago

No Vibes Allowed - Building Design Docs with AI

In this month's no vibes allowed episode, Vaibhav will show how he uses AI to make design docs for complicated tasks by building out an actual design doc for a feature in BAML. As always for our no vibes allowed series, we will be solving real problems in real production systems.

Harness Engineering Without the Hype
#54
3 months ago

Harness Engineering Without the Hype

This week on the pod we are going to cut through the hype around harness engineering and separate the signal from the noise. Join us to watch Dex crash out about this and expose the reality.

Agentic Coding for Frontend Apps
#53
3 months ago

Agentic Coding for Frontend Apps

We do a lot of deep research and planning advice for building complex backend systems but in this week's episode, we're gonna talk about ways you can move faster and maintain quality for frontend code. While backend systems rely on good overall design and tend to be programatically verifiable, frontends require much tighter iteration loops and taste, and these explorations just don't suit themselves to complex up front planning. On the other hand, that shouldn't be an excuse to just regress to yoloing prompts. Good frontend code requires taste, judgement, and is just as vulnerable to a descent into chaotic spaghetti slop. Similar to our learning tests episode, this chat will cover small tactical side quests you can incorporate into your planning and development workflow to improve your frontend throughput. We'll primarily explore storybook as a vessel for interacting with and previewing UI, and approaches to separate presentation logic from business logic. By the end, you may find yourself wanting to ditch figma altogether and just write the components live.

SSE Streaming
#52
3 months ago

SSE Streaming

This week we build a real-time site summarizer using Server-Sent Events (SSE) streaming. We crawl a website, summarize each page with an LLM using BAML's semantic streaming, and stream partial results back to the browser as they're generated. We cover batched async concurrency, FastAPI SSE endpoints, and BAML's @stream.done/@stream.not_null attributes for controlling what streams and what waits.

No Vibes Allowed March Edition
#51
4 months ago

No Vibes Allowed March Edition

This week on the podcast is our March episode of our no vibes allowed series! Join us to watch how we implement everything we discuss on a weekly basis in our company's product. Real code, real trade-offs, and real production systems

MCP is Dead?
#50
4 months ago

MCP is Dead?

MCP isn't dead...or is it? This week on the podcast, we'll dive into this debate. What is the state of MCP today?

Prompt Injections Guardrails
#49
4 months ago

Prompt Injections Guardrails

A major risk factor in agentic coding is Prompt Injections. Tool output, document retrieval, system prompts all get inputted into the LLM and are all at risk of prompt injections. This week on the podcast, we're going to cover how to handle this risk. We will discuss how to protect system prompts, avoid hijacking, and implementing ethical guards

Claude Agent Skills Deep Dive
#48
4 months ago

Claude Agent Skills Deep Dive

Claude Code has exploded in its abilities over the past 8 months, and it can be hard to keep up. Seemingly overnight, everyone is discussing claude's skills, commands, agents, and subagents, and a lot of the literature out there already assumes you know what these are. This week on the podcast, we're going to go over all of them. We will discuss what each one is, how and when to use it, what the benefits and drawbacks are, and how they fit into the broader context engineering picture.

PII Redaction and Sensitive Data Scrubbing
#47
4 months ago

PII Redaction and Sensitive Data Scrubbing

When building generative AI systems, one of the biggest risks companies face is the LLM accidentally exposing PII or PHI to an end user that isn't cleared to see it. This week on the podcast, we'll cover how to fix this problem. We'll discuss what prompting techniques you can use, and more importantly, we'll discuss how you can build evals to get comfortable with shipping these systems to users.

No Vibes Allowed February
#46
5 months ago

No Vibes Allowed February

In our February edition of our No Vibes Allowed series, we will be coding and shipping real features in our products using all of the concepts we cover on this podcast, including using advanced context engineering and backpressure. Join us to see how these concepts apply to real code and real products.

AI Content Pipeline Revisited
#45
5 months ago

AI Content Pipeline Revisited

We have another meta episode this week! Several months ago, we did an episode back about automating the pipeline for generating the artifacts and content for this podcast. That pipeline became stale, and so we breathed some life back into it and we're going to discuss the different parts of that pipeline on the podcast. This episode will discuss everything that goes into bringing you an episode. We'll discuss - Details of the entire pipeline and tools we use to bring you each episode - How to get AI to have the right tone in freeform generation and not sound like AI - Browser agents - Finding clippable content from the transcript - Image generation - How far should automation go?

Agentic Backpressure Deep Dive
#44
5 months ago

Agentic Backpressure Deep Dive

In our next installment of advanced coding agent workflows, we'll explore some alternatives to research for improving results from coding agents. Code and web research is great for understanding the current codebase and finding documentation, but neither of these things is as concrete, and can still lead to hallucinations or incorrect assumptions. In this episode, we'll talk about learning tests and proof-driven-dev - writing small PoC programs and tests that lay the groundwork to confirm understanding of external systems, *before* you get deep into implementation. This will extend our previous conversation about agentic backpressure and building deterministic feedback loops to help coding agents work more autonomously.

Prompting Is Becoming a Product Surface
#43
5 months ago

Prompting Is Becoming a Product Surface

Prompting used to be an engineering problem. Write the right string, tweak it until the model behaves, ship it behind the scenes. That breaks the moment real users show up. Customers don't think in prompts β€” they think in goals. They want to explain what they're trying to accomplish, not debug a magic sentence. So prompting is moving into the product. Interfaces matter. Structure matters. Guardrails and feedback matter. The real work now isn't prompt cleverness β€” it's building systems that let people express intent in a way software can actually understand and trust.

No Vibes Allowed
#42
6 months ago

No Vibes Allowed

We received great feedback from our previous live coding sessions, so this week we are bringing it back this week by live streaming while we add more features to BAML. We have discussed a lot of topics over the past several months, and we will be digging into the how to put many of these concepts into practice as we build out actual features in the product.

Email is All You Need
#41
6 months ago

Email is All You Need

Email is about as adversarial as inputs get: malformed HTML, inconsistent templates, human writing, forwarded junk, zero standards. And yet entire business workflows depend on it. This week we're digging into what it takes to build a real email workflow engine where LLMs aren't demos, but are part of production infrastructure. We'll cover: - Handling long-tail edge cases and weird inbox behavior - Validating and correcting extractions before they break downstream systems - Maintaining accuracy across thousands of formats and senders

Applying 12-Factor Principles to Coding Agent SDKs
#40
6 months ago

Applying 12-Factor Principles to Coding Agent SDKs

We've done a lot of talking in the last few months about prompting coding agents and context engineering w/ markdown files, but today we'll talk about how to squeeze even more out of agents by using agent loops as smaller elements of a deterministic workflow. In this session we'll cover: - using the claude agent sdk to stitch together microagent workflows - accumulating user rules across context windows - json state and structured outputs with zod - session continuation and forking vs. direct compaction

Understanding Latency in AI Applications
#39
6 months ago

Understanding Latency in AI Applications

A deep dive into performance engineering for AI applications. We explore all the bottlenecks in agent systems - from prompt caching and token optimization to semantic streaming and UI design. Learn how to make your agents feel faster through strategic latency reduction and smart UX choices.

Founding Boundary: Vaibhav's Journey
#38
7 months ago

Founding Boundary: Vaibhav's Journey

End of year special part 2: Vaibhav shares his journey from building card games in 7th grade to founding Boundary and creating BAML. From Microsoft to Google to 12 pivots as a YC founder, hear the story behind the programming language for AI pipelines.

Founding HumanLayer: Dex's Journey
#37
7 months ago

Founding HumanLayer: Dex's Journey

End of year special part 1: Dex shares his journey from physics undergrad with half a CS minor to founding HumanLayer. From Sprout Social to Replicated to building AI agents for data warehouses, hear how the path to founding a developer tools company is never a straight line.

Building a Prompt Optimizer
#36
7 months ago

Building a Prompt Optimizer

What happens when models can write really good prompts? We dive deep into prompt optimization, exploring JEPA (Genetic Pareto) algorithm, how it works under the hood, and whether you can build your own optimizer. Live demo of a prompt optimizer built with BAML.

Git Worktrees for AI Coding Agents
#35
7 months ago

Git Worktrees for AI Coding Agents

Since ~ May 2025, there's been a ton of buzz around AI coding agents, parallelizing workflows, and it's not stopping any time soon. On this episode we'll go deep on the tech that can help you push the limits of these tools, including: - Crash course on Git Worktrees - File and Spec Management, tradeoffs in hardlinks vs symlinks - tmux as a building block for collaborative agent workflows

Multimodal Evals
#34
8 months ago

Multimodal Evals

Building evals for multimodal AI - testing vision models, document understanding, and image analysis with structured evaluation frameworks.

No Vibes Allowed: Using CodeLayer to Build CodeLayer
#33
8 months ago

No Vibes Allowed: Using CodeLayer to Build CodeLayer

Live coding with CodeLayer, we'll use Research / Plan / Implement live to ship 3 new features to CodeLayer.

Building an Animation Pipeline
#32
8 months ago

Building an Animation Pipeline

We do a lot of work with Excalidraw, and this session shows the AI-first workflow for turning any sketch into a finished animation. We'll blend Claude Code with custom TypeScript scripts, wire up interactive slash commands, and add browser automation to existing OSS tools to export polished WebM assets.

Dates, Times, and LLMs
#31
8 months ago

Dates, Times, and LLMs

How do you make an LLM amazing at dates? Relative dates, absolute dates, timezones, all that madness. Let's talk dates, times, and all that goodness.

Event-driven agentic loops
#30
8 months ago

Event-driven agentic loops

Key takeaway: treat agent interactions as an event log, not mutable state. Modeling user inputs, LLM chunks, tool calls, interrupts, and UI actions as a single event stream lets you project state for the UI, agent loop, and persistence without drift. We walk through effect-ts patterns for subscribing to the bus, deriving β€œcurrent” state via pure projections, and deciding when to persist or replay eventsβ€”plus trade-offs for queuing, cancelation, and tool orchestration in complex agent UX.

Ralph Wiggum under the hood: Coding Agent Power Tools
#29
9 months ago

Ralph Wiggum under the hood: Coding Agent Power Tools

We've talked a lot about how to use context engineering to get more out of coding agents. In this episode, we dive deep on the Ralph Wiggum technique and why this different approach can reshape your coding workflow. We explore how Ralph handles greenfield work, refactors, and spec generationβ€”surprise: it's all about higher-quality context engineering.

No Vibes Allowed - Live Coding with AI Agents
#27
9 months ago

No Vibes Allowed - Live Coding with AI Agents

Vaibhav Gupta and Dex demonstrate the power of AI-assisted coding by implementing a complex timeout feature for BAML (a programming language for AI applications) in a live coding session. Starting from a GitHub issue that had been open since March, they showcase a systematic workflow: specification refinement, codebase research, implementation planning, and phased execution. Using Claude and specialized coding agents, they navigate a 400,000+ line codebase, implementing timeout configurations for HTTP clients including connection timeouts, request timeouts, idle timeouts, and time-to-first-token for streaming responses. The session highlights key practices like context engineering, frequent plan validation, breaking complex features into testable phases, and the importance of reading AI-generated code. In under 3 hours of live coding, they achieve what would typically take 1-2 days of engineering time, successfully implementing parsing, validation, error handling, and Python integration tests.

Anthropic Post Mortem
#26
9 months ago

Anthropic Post Mortem

In this conversation, Vaibhav Gupta and Aaron discuss various aspects of AI model performance, focusing on the recent downtime experienced by Anthropic and the implications for AI systems. They explore the sensitivity of models to context windows, the challenges of output corruption, and the complexities of token selection mechanisms. The discussion also highlights the importance of debugging and observability in AI systems, as well as the role of user-friendly workflows and integrations in making AI accessible to non-technical users. The conversation concludes with thoughts on the future of AI development and the need for effective metrics to monitor product performance.

Dynamic Schemas
#25
10 months ago

Dynamic Schemas

In this episode, Dex and Vaibhav explore the concept of dynamic UIs and how to build systems that can adapt to unknown data structures. They discuss the importance of dynamic schema generation, meta programming with LLMs, and the potential for creating dynamic React components. The conversation also delves into the execution and rendering of these dynamic schemas, highlighting the challenges and opportunities in this evolving field. They conclude with thoughts on future directions and the importance of building robust workflows around schema management.

Evals for Classification
#24
10 months ago

Evals for Classification

In this episode of AI That Works, hosts Vaibhav Gupta and Dex, along with guest Kevin Gregory, explore the intricacies of building AI systems that are ready for production. They discuss the concept of dynamic UIs, the challenges of large-scale classification, and the importance of user experience in AI applications. The conversation delves into the use of LLMs for enhancing classification systems, the evaluation and tuning of these systems, and the subjective nature of what constitutes a 'correct' classification. The episode emphasizes the need for engineers to focus on accuracy and user experience while navigating the complexities of AI engineering. The speakers also discuss model upgrades, user feedback, and the importance of building effective user interfaces, emphasizing iterative development and rapid prototyping for chatbot performance evaluation.

Bash vs. MCP - token efficient coding agent tooling
#23
10 months ago

Bash vs. MCP - token efficient coding agent tooling

In this conversation, Dex and Vaibhav delve into the intricacies of coding agents, focusing on the debate between using MCP (Model Control Protocol) and Bash for tool integration. They explore the importance of understanding context windows, token management, and the efficiency of using different tools. The discussion emphasizes the significance of naming conventions, dynamic context engineering, and the engineering efforts required to optimize performance. They also share real-world applications, best practices for using MCPs, and engage with the community through a Q&A session.

Generative UIs and Structured Streaming
#22
10 months ago

Generative UIs and Structured Streaming

We'll explore hard problems in building rich UIs that rely on streaming data from LLMs. ​Specifically, we'll talk through techniques for rendering **STRUCTURED** outputs from LLMs, with real-world examples of how to handle partially-streamed outputs over incomplete JSON data. We'll explore advanced needs like * Fields that should be required for stream to start * ​Rendering React Components with partial data ​* Handling nullable fields vs. yet-to-be-streamed fields * ​Building high-quality User feedback * ​Handling errors mid-stream

Voice Agents and Supervisor Threading
#21
11 months ago

Voice Agents and Supervisor Threading

Exploring voice-based AI agents and supervisor threading patterns for managing complex conversational workflows.

Claude for Non-Code Tasks
#20
11 months ago

Claude for Non-Code Tasks

On #17 we talked about advanced context engineering workflows for using Claude code to work in complex codebases. This week, we're gonna get a little weird with it, and show off a bunch of ways you can use Claude Code as a generic agent to handle non-coding tasks. We'll learn things like: Skipping the MCP and having claude write its own scripts to interact with external systems, Creating internal knowledge graphs with markdown files, How to blend agentic retrieval and search with deterministic context packing

Interruptible Agents
#19
11 months ago

Interruptible Agents

Anyone can build a chatbot, but the user experience is what truly sets it apart. Can you cancel a message? Can you queue commands while it's busy? How finely can you steer the agent? We'll explore these questions and code a solution together.

Decoding Context Engineering Lessons from Manus
#18
11 months ago

Decoding Context Engineering Lessons from Manus

A few weeks ago, the Manus team published an excellent paper on context engineering. It covered KV Cache, Hot-swapping tools with custom samplers, and a ton of other cool techniques. On this week's episode, we'll dive deep on the manus Article and put some of the advice into practice, exploring how a deep understanding of models and inference can help you to get the most out of today's LLMs.

Context Engineering for Coding Agents
#17
11 months ago

Context Engineering for Coding Agents

By popular demand, AI That Works #17 will dive deep on a new kind of context engineering: managing research, specs, and planning to get the most of coding agents and coding CLIs. You've heard people bragging about spending thousands/mo on Claude Code, maxing out Amp limits, and much more. Now Dex and Vaibhav are gonna share some tips and tricks for pushing AI coding tools to their absolute limits, while still shipping well-tested, bug-free code. This isn't vibe-coding, this is something completely different.

Evaluating Prompts Across Models
#16
12 months ago

Evaluating Prompts Across Models

AI That Works #16 will be a super-practical deep dive into real-world examples and techniques for evaluating a single prompt against multiple models. While this is a commonly heralded use case for Evals, e.g. 'how do we know if the new model is better' / 'how do we know if the new model breaks anything', there's not a ton of practical examples out there for real-world use cases.

PDFs, Multimodality, Vision Models
#15
12 months ago

PDFs, Multimodality, Vision Models

Dive deep into practical PDF processing techniques for AI applications. We'll explore how to extract, parse, and leverage PDF content effectively in your AI workflows, tackling common challenges like layout preservation, table extraction, and multi-modal content handling.

Implementing Decaying-Resolution Memory
#14
about 1 year ago

Implementing Decaying-Resolution Memory

Last week on #13, we did a conceptual deep dive on context engineering and memory - this week, we're going to jump right into the weeds and implement a version of Decaying-Resolution Memory that you can pick up and apply to your AI Agents today. For this episode, you'll probably want to check out episode #13 in the session listing to get caught up on DRM and why its worth building from scratch.

Building AI with Memory & Context
#13
about 1 year ago

Building AI with Memory & Context

How do we build agents that can remember past conversations and learn over time? We'll explore memory and context engineering techniques to create AI systems that maintain state across interactions.

Boosting AI Output Quality
#12
about 1 year ago

Boosting AI Output Quality

This week's session was a bit meta! We explored 'Boosting AI Output Quality' by building the very AI pipeline that generated this email from our Zoom recording. The real breakthrough: separating extraction from polishing for high-quality AI generation.

Building an AI Content Pipeline
#11
about 1 year ago

Building an AI Content Pipeline

Content creation involves a lot of manual work - uploading videos, sending emails, and other follow-up tasks that are easy to drop. We'll build an agent that integrates YouTube, email, GitHub and human-in-the-loop to fully automate the AI that Works content pipeline, handling all the repetitive work while maintaining quality.

Entity Resolution: Extraction, Deduping, and Enriching
#10
about 1 year ago

Entity Resolution: Extraction, Deduping, and Enriching

Disambiguating many ways of naming the same thing (companies, skills, etc.) - from entity extraction to resolution to deduping. We'll explore breaking problems into extraction β†’ resolution β†’ enrichment stages, scaling with two-stage designs, and building async workflows with human-in-loop patterns for production entity resolution systems.

Cracking the Prompting Interview
#9
about 1 year ago

Cracking the Prompting Interview

Ready to level up your prompting skills? Join us for a deep dive into advanced prompting techniques that separate good prompt engineers from great ones. We'll cover systematic prompt design, testing tools / inner loops, and tackle real-world prompting challenges. Perfect prep for becoming a more effective AI engineer.

Humans as Tools: Async Agents and Durable Execution
#8
about 1 year ago

Humans as Tools: Async Agents and Durable Execution

Agents are great, but for the most accuracy-sensitive scenarios, we some times want a human in the loop. Today we'll discuss techniques for how to make this possible. We'll dive deep into concepts from our 4/22 session on 12-factor agents and extend them to handle asynchronous operations where agents need to contact humans for help, feedback, or approvals across a variety of channels.

12-factor agents: selecting from thousands of MCP tools
#7
about 1 year ago

12-factor agents: selecting from thousands of MCP tools

MCP is only as great as your ability to pick the right tools. We'll dive into showing how to leverage MCP servers and accurately use the right ones when only a few have actually relevant tools.

Policy to Prompt: Evaluating w/ the Enron Emails Dataset
#6
about 1 year ago

Policy to Prompt: Evaluating w/ the Enron Emails Dataset

One of the most common problems in AI engineering is looking at a set of policies/rules and evaluating evidence to determine if the rules were followed. In this session we'll explore turning policies into prompts and pipelines to evaluate which emails in the massive Enron email dataset violated SEC and Sarbanes-Oxley regulations.

Designing Evals
#5
about 1 year ago

Designing Evals

Minimalist and high-performance testing/evals for LLM applications. Stay tuned for our season 2 kickoff topic on testing and evaluation strategies.

Twelve Factor Agents
#4
about 1 year ago

Twelve Factor Agents

Learn how to build production-ready AI agents using the twelve-factor methodology. We'll cover the core concepts and build a real agent from scratch.

Code Generation with Small Models
#3
over 1 year ago

Code Generation with Small Models

Large models can do a lot, but so can small models. We'll discuss techniques for how to leverage extremely small models for generating diffs and making changes in complete codebases.

Reasoning Models vs Reasoning Prompts
#2
over 1 year ago

Reasoning Models vs Reasoning Prompts

Models can reason but you can also reason within a prompt. Which technique wins out when and why? We'll find out by adding reasoning to an existing movie chat agent.

Large Scale Classification
#1
over 1 year ago

Large Scale Classification

LLMs are great at classification from 5, 10, maybe even 50 categories. But how do we deal with situations when we have over 1000? Perhaps it's an ever changing list of categories?

Boundary

The programming language for agents.

  • Company
  • About Us
  • Why BAML?
  • Privacy Policy
  • Terms of Service
  • Resources
  • Changelog
  • Docs
  • Jobs
  • Blog
  • Pricing
  • Social
  • GitHub
  • Twitter
  • Discord
  • LinkedIn
  • YouTube