filterMiddleware

Middleware hooks let you intercept agent lifecycle events for logging, retry, guardrails, tool control, and human-in-the-loop patterns.

circle-info

Since BoxLang AI v3.0+

Middleware lets you intercept and control an agent's execution at key lifecycle points — before/after each agent run, before/after each LLM call, and before/after each tool invocation. This enables logging, retry logic, content guardrails, rate limiting, and human approval workflows without modifying agent logic.

Adding Middleware to an Agent

agent = aiAgent(
    name      : "SafeAgent",
    middleware: [
        new LoggingMiddleware(),
        new RetryMiddleware( maxRetries: 3 ),
        new GuardrailMiddleware()
    ]
)

Middleware fires in order on inbound hooks (beforeAgentRun, beforeLLMCall, beforeToolCall) and in reverse order on outbound hooks (afterToolCall, afterLLMCall, afterAgentRun).

Built-In Middleware

LoggingMiddleware

Logs lifecycle events to the BoxLang ai log and optionally to console:

agent = aiAgent(
    name      : "TracedAgent",
    middleware: [
        new LoggingMiddleware(
            logToFile   : true,
            logToConsole: true,
            logLevel    : "info",
            prefix      : "[Support Bot]"
        )
    ]
)

RetryMiddleware

Automatically retries failed LLM calls with exponential backoff:

GuardrailMiddleware

Block, filter, or rewrite requests and responses based on content rules:

MaxToolCallsMiddleware

Prevent runaway tool-call loops:

HumanInTheLoopMiddleware

Suspend the agent mid-run for human approval before continuing:

FlightRecorderMiddleware

Record the full execution trace for debugging and auditing:

Struct-Based Middleware (Inline)

For quick one-off interceptions without creating a class:

Adding Middleware After Construction

Middleware Result Actions

Each hook returns an AiMiddlewareResult that controls execution flow:

Result
Effect

AiMiddlewareResult::proceed()

Continue to the next middleware/hook

AiMiddlewareResult::cancel( message )

Abort execution, return message

AiMiddlewareResult::suspend( state )

Pause execution, save state for resume

AiMiddlewareResult::approve()

Approve a tool call (used in beforeToolCall)

AiMiddlewareResult::reject( reason )

Reject a tool call

Lifecycle Hooks

Hook
Fires When
Context Available

beforeAgentRun

Agent run() begins

agent, input, messages, params, options

afterAgentRun

Agent run() completes

+ response

beforeLLMCall

Each HTTP call to AI provider

model, chatRequest, messages

afterLLMCall

Each HTTP call completes

+ response

beforeToolCall

Each tool invocation

tool, toolName, toolArgs, toolCallId

afterToolCall

Each tool invocation completes

+ result

onError

Any hook throws an exception

error, phase, context

Custom Middleware

Extend BaseAiMiddleware and override only the hooks you need:

Last updated