Middleware
Middleware provides an extensible pipeline for adding cross-cutting concerns to AI requests.
Middleware wraps AI clients to add functionality like logging, caching, rate limiting, and custom behavior. Every request passes through the middleware pipeline before reaching the AI provider.
How Middleware Works
Middleware uses the decorator pattern. Each middleware wraps the client and can:
Modify requests before they're sent.
Modify responses before they're returned.
Add side effects (logging, metrics).
Short-circuit requests (caching).
Middleware Types
Chat Middleware
Wraps IChatClient instances:
Embedding Middleware
Wraps IEmbeddingGenerator<string, Embedding<float>> instances:
Example: Logging Middleware
Registering Middleware
Register middleware in a Composer using the collection builder:
Middleware Ordering
Middleware executes in the order it's registered. Use collection builder methods to control order:
Resulting order:
TracingMiddleware
LoggingMiddleware
CachingMiddleware
MetricsMiddleware
M.E.AI Built-in Middleware
Microsoft.Extensions.AI provides middleware you can use:
OpenTelemetryChatClient- Distributed tracingLoggingChatClient- Structured loggingFunctionInvokingChatClient- Tool/function calling
Creating Custom Middleware
See the extending guide for detailed instructions:
Related
Chat API - How middleware affects chat requests
Creating Chat Middleware - Build custom middleware
Last updated
Was this helpful?