Lesson 23 of 64 · 4 min read · Updated
Termination and Guardrails
On this page
Termination in the Microsoft Agent Framework means that a middleware component returns an AgentResponse directly without ever calling innerAgent.RunAsync(). The agent's actual processing is completely skipped. This pattern is the foundation of guardrail middleware: a protective layer that sits in front of (or behind) an agent and enforces safety, compliance, or quality rules.
Why Guardrails?
Production AI agents need more than just good prompts. They need deterministic walls:
- Input guardrails – Block requests that contain sensitive keywords, off-topic content, or policy violations before they ever reach the LLM.
- Output guardrails – Inspect or transform the agent's response after it is generated. Truncate excessively long replies, redact PII, or inject a disclaimer.
The Termination Pattern
A normal middleware delegates to the next agent in the chain:
Termination middleware skips that delegation and returns a synthetic response:
The AgentResponse(IList<ChatMessage>) constructor lets you craft a fully custom response as if the agent had replied.
Demo: GuardrailMiddleware
The demo in Lesson6/Demo1_Termination.cs registers a single middleware function that performs both a pre-check and a post-check.
Step 1 – Build the base agent
Step 2 – Wrap it with the guardrail
Every call to guardedAgent.RunAsync() now passes through GuardrailMiddleware first.
Step 3 – The middleware itself
Step 4 – Run the demo
How the Two Checks Differ
| Check | Position | Calls innerAgent? | Purpose |
|---|---|---|---|
| Pre-execution | Before innerAgent.RunAsync() | No (terminated) | Block forbidden input, enforce topic restrictions |
| Post-execution | After innerAgent.RunAsync() | Yes (already ran) | Truncate, redact, or replace unwanted output |
Composing Multiple Guardrails
Because guardrails are just middleware, you can stack them with .Use() calls:
Middleware is applied in reverse registration order: the last .Use() call wraps outermost. Keep that in mind when ordering input vs output checks.
Key Types
| Type / Member | Package | Role |
|---|---|---|
AgentResponse(IList<ChatMessage>) | Microsoft.Agents.AI | Construct a synthetic response to return from a terminated middleware |
AIAgent.AsBuilder().Use().Build() | Microsoft.Agents.AI | Register middleware on an existing agent |
AgentRunMiddleware delegate | Microsoft.Agents.AI | Task<AgentResponse>(messages, session, options, innerAgent, ct) |
ChatMessage(ChatRole, string) | Microsoft.Extensions.AI | Create a single message to include in the synthetic response |