For the complete documentation index, see llms.txt. This page is also available as Markdown.

Middleware

Add cross-cutting concerns to AI operations with middleware.

Middleware lets you wrap AI client operations to add cross-cutting concerns like logging, caching, rate limiting, and telemetry. Middleware is applied to all AI requests without modifying application code.

How Middleware Works

Middleware wraps the underlying AI client, intercepting requests and responses:

Each middleware receives a client and returns a wrapped client with additional behavior.

Middleware Types

Type
Interface
Wraps

Chat

IAIChatMiddleware

IChatClient

Embedding

IAIEmbeddingMiddleware

IEmbeddingGenerator<string, Embedding<float>>

Quick Example

LoggingMiddleware.cs
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Logging;
using Umbraco.AI.Core.Chat;

public class LoggingChatMiddleware : IAIChatMiddleware
{
    private readonly ILoggerFactory _loggerFactory;

    public LoggingChatMiddleware(ILoggerFactory loggerFactory)
    {
        _loggerFactory = loggerFactory;
    }

    public IChatClient Apply(IChatClient client)
    {
        return client.AsBuilder()
            .UseLogging(_loggerFactory)
            .Build();
    }
}

Key Concepts

Middleware Order Matters

Middleware is applied to the client in registration order. The first registered middleware wraps the underlying client (innermost), the second wraps that, and so on. As a result, the last registered middleware is the outermost wrapper and sees requests first.

Middleware Receives Dependencies

Middleware classes support constructor injection:

Using M.E.AI Middleware

Microsoft.Extensions.AI includes built-in middleware. Use the AsBuilder() extension to apply them:

In This Section

Chat MiddlewareEmbedding MiddlewareMiddleware Ordering

Last updated

Was this helpful?