Middleware
The middleware system in@ag-ui/client provides a powerful way to transform, filter, and augment event streams flowing through agents. Middleware can intercept and modify events, add logging, implement authentication, filter tool calls, and more.
Types
MiddlewareFunction
A function that transforms the event stream.Middleware
Abstract base class for creating middleware.Function-Based Middleware
The simplest way to create middleware is with a function. Function middleware is ideal for stateless transformations.Basic Example
Transforming Events
Error Handling
Class-Based Middleware
For stateful operations or complex logic, extend theMiddleware class.
Basic Implementation
Configuration-Based Middleware
Built-in Middleware
FilterToolCallsMiddleware
Filters tool calls based on allowed or disallowed lists.Configuration
Allow Specific Tools
Block Specific Tools
Middleware Patterns
Timing Middleware
Rate Limiting
Retry Logic
Caching
Chaining Middleware
Multiple middleware can be combined to create sophisticated processing pipelines.Advanced Usage
Conditional Middleware
Event Filtering
Stream Manipulation
Best Practices
- Single Responsibility: Each middleware should focus on one concern
- Error Handling: Always handle errors gracefully and consider recovery strategies
- Performance: Be mindful of processing overhead in high-throughput scenarios
- State Management: Use class-based middleware when state is required
- Testing: Write unit tests for each middleware independently
- Documentation: Document middleware behavior and side effects