This sample demonstrates how to add middleware to intercept:
- Chat client calls (global and per‑request)
- Agent runs (guardrails and PII filtering)
- Function calling (logging/override)
- Microsoft Foundry integration via
AIProjectClientandDefaultAzureCredential - Chat client middleware using
ChatClientBuilder.Use(...) - Agent run middleware (PII redaction and wording guardrails)
- Function invocation middleware (logging and overriding a tool result)
- Per‑request chat client middleware
- Per‑request function pipeline with approval
- Combining agent‑level and per‑request middleware
- MessageAIContextProvider middleware via
AIAgentBuilder.Use(...)for injecting additional context messages - AIContextProvider middleware via
ChatClientBuilder.Use(...)for enriching messages, tools, and instructions at the chat client level
Not all agents support function invocation middleware.
Attempting to use function middleware on agents that do not wrap a ChatClientAgent or derives from it will throw an InvalidOperationException.
Note: Function invocation middleware applies to tools registered on the agent. This includes tools passed to the
ChatClientAgentconstructor, passed toAsAIAgent, configured throughChatClientAgentOptions.ChatOptions.Tools, or supplied for an individual run. These tools are passed throughChatOptions.Tools. Functions added directly toFunctionInvokingChatClient.AdditionalToolsbypass this middleware entirely, so don't rely on the middleware to enforce checks for those functions.
- Environment variables:
FOUNDRY_PROJECT_ENDPOINT: Your Foundry project endpointFOUNDRY_MODEL: Model name (optional; defaults togpt-5.4-mini)
- Sign in with Azure CLI (PowerShell):
az login
Use PowerShell:
cd dotnet/samples/02-agents/Agents/Agent_Step11_Middleware
dotnet run