````skill
---
name: agentbyte-middleware
description: Guide for adding middleware chains in Agentbyte for agent and embedding operations. Use this for logging, guardrails, PII redaction, usage tracking, and tracing.
---

Use this skill when you need to intercept operations via `MiddlewareChain` and `BaseMiddleware`.

## Pattern: Custom Middleware (current interface)

```python
from typing import Any, Optional

from agentbyte.middleware import BaseMiddleware, MiddlewareContext


class MyLogger(BaseMiddleware):
    async def process_request(self, context: MiddlewareContext) -> MiddlewareContext:
        print(f"request: {context.operation} ({context.agent_name})")
        return context

    async def process_response(self, context: MiddlewareContext, result: Any) -> Any:
        print(f"response: {context.operation} ({context.agent_name})")
        return result

    async def process_error(
        self,
        context: MiddlewareContext,
        error: Exception,
    ) -> Optional[Any]:
        print(f"error: {context.operation} ({context.agent_name}): {error}")
        return None
```

## Where middleware is applied

- **Agent-level:** chat model calls, tool calls, memory access.
- **Embedding client-level:** embedding requests (`operation="embedding_call"`) in `BaseEmbeddingClient`.

For embeddings, register middleware directly on the client:

```python
from agentbyte.llm import OpenAIEmbeddingClient
from agentbyte.middleware import LoggingMiddleware, PIIRedactionMiddleware

client = OpenAIEmbeddingClient.from_api_key(model="text-embedding-3-small")
client.add_middleware(LoggingMiddleware())
client.add_middleware(PIIRedactionMiddleware())

result = await client.create("Contact me at demo@example.com")
```

## Built-in Middlewares

- `LoggingMiddleware`: Emits operation request/response/error logs.
- `GuardrailMiddleware`: Blocks configured tools and forbidden patterns.
- `PIIRedactionMiddleware`: Masks common PII patterns in supported payloads.
- `RateLimitMiddleware`: Applies in-memory throttling.
- `MetricsMiddleware`: Tracks operation counts, durations, and errors.
- `OTelMiddleware`: Emits OpenTelemetry traces/metrics when enabled.

## Embedding-specific notes

- `PIIRedactionMiddleware` supports `embedding_call` payload shape: `{"input": [...], "kwargs": {...}}`.
- Logging output appears at INFO level under logger `agentbyte.middleware`.
- In notebooks, configure logging first if middleware logs should appear.

## Guardrails

- **Execution order:** `process_request` runs in list order; `process_response` runs in reverse order.
- **Error handling:** Use `process_error(...)` to recover or propagate failures.
- **Context contract:** Use `MiddlewareContext` (`operation`, `agent_name`, `agent_context`, `data`, `metadata`) to pass state.
- **No duplicate registration:** In notebooks, prefer idempotent middleware registration to avoid stacking duplicate handlers across repeated runs.

````