Middleware
Add pre and post-processing logic to your agent operations
Overview
Middleware in Magma allows you to intercept and modify agent behavior at key points in the execution flow. Using middleware, you can add custom logic that runs before or after completions are generated and tools are executed. You can manipulate the inputs of middleware directly, or throw an error to modify the flow of execution.
Middleware Types
Magma supports four types of middleware:
preCompletion
: Runs before an LLM completion is generatedonCompletion
: Runs after an LLM completion is generatedpreToolExecution
: Runs before a tool is executedonToolExecution
: Runs after a tool is executed
Middleware Error handling
If a middleware function throws an error, the agent flow will be modified to handle it accordingly.
preCompletion
: The agent will not generate a completion, and the error message will be returned as if it were the agent’s response.onCompletion
: The agent will be notified of the error, and a completion will be re-generated.preToolExecution
: The agent will not execute the tool, and the error message will be returned as if it were the tool’s response.onToolExecution
: The agent will replace the tool’s response with the error message.
Implementation
To add middleware to your agent, use the @middleware
decorator:
Chaining Middleware
You can add as many middleware functions as you want to your agent. Middleware functions of the same type are executed in order of definition.
Common Use Cases
Middleware is particularly useful for:
- Input validation and sanitization
- Response filtering and modification
- Logging and monitoring
- Rate limiting
- Access control
- Response formatting
Best Practices
- Keep middleware functions focused and single-purpose
- Handle errors appropriately within middleware
- Use TypeScript types for better type safety
- Add clear documentation about what each middleware does
- Consider the order of middleware execution
- Return meaningful error messages when validation fails