---
name: agentbyte-middleware
description: Guide for adding middleware chains to Agentbyte agents. Use this for logging, guardrails, PII redaction, usage tracking, or custom pre/post run logic.
---

Use this skill when you need to intercept agent execution.

## Pattern: Custom Middleware
```python
from agentbyte.middleware import BaseMiddleware, MiddlewareContext
from agentbyte.messages import Message

class MyLogger(BaseMiddleware):
    async def before_run(self, context: MiddlewareContext):
        print(f"Starting agent: {context.agent_name}")

    async def after_run(self, context: MiddlewareContext, response: list[Message]):
        print(f"Finished agent: {context.agent_name}")

agent = Agent(
    ...,
    middlewares=[MyLogger()]
)
```

## Built-in Middlewares
- `LoggingMiddleware`: Outputs detailed step logic.
- `GuardrailMiddleware`: Enforces constraints on responses.
- `PIIRedactionMiddleware`: Automatically masks sensitive patterns.
- `RateLimitMiddleware`: Prevents LLM client flooding.

## Guardrails
- **Execution Order:** Middlewares execute in the list order.
- **Error Handling:** Use `on_error` implementation in the middleware to handle exceptions in the pipeline.
- **Context:** Use `MiddlewareContext` to pass information between `before_run` and `after_run`.
