For the complete documentation index, see llms.txt. Markdown versions of documentation pages are available by appending .md to page URLs.
Skip to content

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:

  1. TracingMiddleware

  2. LoggingMiddleware

  3. CachingMiddleware

  4. MetricsMiddleware

M.E.AI Built-in Middleware

Microsoft.Extensions.AI provides middleware you can use:

  • OpenTelemetryChatClient - Distributed tracing

  • LoggingChatClient - Structured logging

  • FunctionInvokingChatClient - Tool/function calling

Creating Custom Middleware

See the extending guide for detailed instructions:

Middleware

Last updated

Was this helpful?