Skip to main content

Middleware API Reference

Middleware components and patterns for building chat client pipelines.

Overview

The .NET SDK uses the ChatClientBuilder pattern from Microsoft.Extensions.AI to create pipelines of middleware components that wrap an underlying IChatClient. This allows you to add cross-cutting concerns like logging, telemetry, caching, and function invocation.

ChatClientBuilder

Builder for creating pipelines of IChatClient middleware.

Use()

Adds a middleware component to the pipeline.
Func<IChatClient, IServiceProvider?, IChatClient>
required
A factory function that takes the inner client and optional service provider, and returns a new chat client that wraps it.
IChatClient
required
A chat client instance to add to the pipeline.
ChatClientBuilder
The builder instance for method chaining.

Build()

Builds the final IChatClient pipeline.
IServiceProvider?
Optional service provider for dependency injection.
IChatClient
The constructed chat client pipeline.

Example: Basic Pipeline


Built-in Middleware

UseLogging()

Adds logging middleware to the pipeline.
ILoggerFactory?
Optional logger factory. If null, logs are not emitted.

UseOpenTelemetry()

Adds OpenTelemetry instrumentation to the pipeline.
OpenTelemetryChatClientOptions?
Optional configuration for OpenTelemetry instrumentation.

UseFunctionInvocation()

Adds function invocation middleware to the pipeline.
IServiceProvider?
Optional service provider for dependency injection into function parameters.

Example: Full Pipeline with Multiple Middleware


Custom Middleware

You can create custom middleware by implementing a delegating IChatClient.

Example: Retry Middleware

Example: Caching Middleware

Example: Rate Limiting Middleware

Example: Request/Response Transformation


DelegatingChatClient

Base class for implementing custom middleware that wraps another IChatClient.

Overview

DelegatingChatClient provides a convenient base class for creating middleware. Override only the methods you need to intercept, and call base to delegate to the inner client.

Example: Logging Middleware