Custom Middleware
Middleware in AgentLIB provides a powerful way to intercept and modify agent behavior at different points in the execution lifecycle. Middleware follows a Koa-style async pipeline pattern where each middleware can run code before and after callingnext().
Middleware Scopes
Middleware can hook into different lifecycle events:run:before- Before the agent starts processingrun:after- After the agent completesstep:before- Before each reasoning stepstep:after- After each reasoning steptool:before- Before a tool is executedtool:after- After a tool completes
Basic Middleware Structure
Example 1: Request Validation Middleware
Validate and sanitize user input before processing:Example 2: Tool Caching Middleware
Cache tool results to avoid redundant API calls:Example 3: Performance Monitoring Middleware
Track timing and token usage across executions:Example 4: Error Handling & Retry Middleware
Automatically retry failed tool calls:Combining Multiple Middleware
Middleware runs in registration order:Accessing Execution Context
Middleware has full access to the execution context:Best Practices
- Always call
next()unless you intentionally want to short-circuit execution - Use specific scopes to avoid unnecessary overhead
- Handle errors gracefully to prevent middleware from breaking the pipeline
- Keep middleware focused - each middleware should have a single responsibility
- Use TypeScript generics to maintain type safety with custom data types
- Clean up resources after execution (timers, connections, etc.)
Next Steps
- Explore the Logger Middleware for structured logging
- Learn about Custom Reasoning Engines
- See Multi-Agent Orchestration for complex workflows