filterMiddleware

Intercept, modify, log, retry, and guard agent execution at every stage using the middleware pipeline.

circle-info

Since BoxLang AI v3.0+

Middleware provides hooks into every stage of agent execution — before and after LLM calls, tool invocations, and the full agent run. Use it for logging, retrying failures, enforcing guardrails, and more without touching your agent code.

How It Works

Middleware wraps agent execution in layers. Each layer can inspect and modify the request/response, or halt execution entirely.

Agent.run(input)

  ▼ beforeAgentRun (all middleware, in order)

  ▼ beforeLLMCall → (LLM call) → afterLLMCall

  ▼ beforeToolCall → (tool execution) → afterToolCall

  ▼ afterAgentRun (all middleware, in reverse order)

  ▼ result

Inbound hooks (before*) run in registration order. Outbound hooks (after*) run in reverse order.

Adding Middleware to an Agent

Or with the fluent API:

Lifecycle Hooks

Hook
Fires When
Context Keys

beforeAgentRun

Before agent starts processing

agent, input, messages, params, options

afterAgentRun

After agent finishes

agent, input, messages, params, options, response

beforeLLMCall

Before each LLM API call

model, chatRequest, messages

afterLLMCall

After each LLM API call

model, chatRequest, messages, response

beforeToolCall

Before each tool execution

tool, toolName, toolArgs, toolCallId

afterToolCall

After each tool execution

tool, toolName, toolArgs, toolCallId, result

onError

On any exception

error, phase (hook name), context (hook context)

Middleware Return Values (AiMiddlewareResult)

Each hook returns an AiMiddlewareResult to control the flow:

Factory Method
Effect

AiMiddlewareResult::continue()

Proceed normally (default)

AiMiddlewareResult::cancel( reason )

Stop execution, return reason as error

AiMiddlewareResult::approve()

Explicitly approve (used in Human-in-the-Loop)

AiMiddlewareResult::reject( reason )

Reject with explanation

AiMiddlewareResult::edit( args )

Modify tool arguments before execution

AiMiddlewareResult::suspend( pending )

Pause execution (async Human-in-the-Loop)

Built-in Middleware

BoxLang AI ships with six battle-tested middleware classes covering the most common cross-cutting concerns. All live in bxModules.bxai.models.middleware.core.

Middleware
When to Use It

LoggingMiddleware

Audit every LLM call and tool invocation — write to console, file, or both with a configurable log level

RetryMiddleware

Automatically retry failed LLM calls with exponential back-off; essential for flaky or rate-limited providers

GuardrailMiddleware

Block dangerous tools entirely and enforce regex-based argument validation before any tool runs

MaxToolCallsMiddleware

Prevent runaway agents by capping the total number of tool invocations per run

HumanInTheLoopMiddleware

Require explicit human approval (CLI prompt or custom callback) before sensitive tools execute

FlightRecorderMiddleware

Record live LLM/tool interactions to a JSON fixture and replay them offline — ideal for testing and debugging

LoggingMiddleware

Logs every agent lifecycle event.

RetryMiddleware

Retries failed LLM calls with exponential backoff.

GuardrailMiddleware

Blocks specified tools and validates tool arguments against regex patterns.

MaxToolCallsMiddleware

Caps the total number of tool invocations in a single run.

HumanInTheLoopMiddleware

Requires human approval before specified tools execute.

FlightRecorderMiddleware

Records LLM and tool interactions to a JSON fixture for debugging and replay.

Struct-Based Inline Middleware

For simple cases, pass a struct with hook functions — no class required:

Custom Middleware Class

Extend BaseAiMiddleware for reusable, configurable middleware:

Combining Middleware

Stack middleware to compose behaviors:

Last updated