Architecture of an agentic feature in a .NET product: agent vs workflow decision, autonomy levels, tool design and permissions, input/output guardrails, human approval for side effects, cost and latency budgets, state, evaluation and rollout.
I start by asking whether the task's path varies per request. If the steps are known, I build a deterministic workflow with LLM calls at specific steps; an agent is only for genuinely open-ended tasks. Then I pick an autonomy level per action: reads run automatically, writes are drafted for human approval or done with undo, and nothing irreversible runs unattended. Tools wrap existing use cases and run with the user's permissions. Guardrails are layered: input screening (Azure AI Content Safety Prompt Shields), validated tool arguments, output checks and hard limits. I set budgets for iterations, tokens and cost per request and per tenant, and gate every change on an evaluation set. Rollout is behind a feature flag with a kill switch. The trade-off: each extra unit of autonomy saves user effort but raises the cost of being wrong.
"The first question is whether it should be an agent at all. For 'change my booking to Friday', the steps are almost always the same: identify the booking, check availability, propose the change, confirm. That's a workflow where the LLM extracts intent and fills slots, and code does the rest. I reach for an agent only where the path really varies, like 'sort out everything for my team's offsite', where the model has to choose among several tools in an order I can't predict.
If it is an agent, I design it around autonomy levels. For example, at [company] we built [a booking assistant] where lookups ran automatically, but any change was returned as a proposed action that the user confirmed in the UI, and cancellations with fees always needed explicit approval. The tools called our existing MediatR handlers with the signed-in user's identity, so the agent could never do more than the user could. We screened input with Prompt Shields, validated every tool argument against the same FluentValidation rules as the API, capped iterations at [8] and tokens per request at [20k], and set a monthly budget per tenant. Before launch we built an evaluation set of [300] real, anonymised requests; we released to [5%] of tenants behind a feature flag, and task completion went from [x] to [y] while support tickets on bookings fell [z%].
The mistake I see is giving the agent broad tools and relying on the system prompt for safety. Prompts are suggestions; permissions, validation and approvals are controls. My senior rule is: let the model decide what to propose, and let code decide what is allowed."
| Signal | Workflow with LLM steps | Agent |
|---|---|---|
| Steps known in advance | Yes | No |
| Need for predictable latency and cost | Strong | Weak |
| Number of tools | 1–3 | Many, chosen per request |
| Auditability | Easy: fixed path | Needs full tracing |
| Typical example | Booking change, ticket classification | Open-ended research or multi-system tasks |
| Level | Behaviour | Use for |
|---|---|---|
| 0 Suggest | Model answers, user acts | Advice, explanations |
| 1 Draft | Model prepares an action, user approves | Booking changes, emails to customers |
| 2 Act with undo | Executes, easy reversal window | Low-risk, reversible edits |
| 3 Autonomous | Executes without review | Read-only tools, internal low-impact tasks |
| Layer | Control | .NET building block |
|---|---|---|
| Input | Prompt injection and harmful content screening | Azure AI Content Safety (Prompt Shields) |
| Planning | Iteration and token caps, allowed tools per user | FunctionInvokingChatClient options, per-request ChatOptions.Tools |
| Tools | Argument validation, authorisation, limits, idempotency | FluentValidation, ASP.NET Core policies, MediatR handlers |
| Approval | Pause for human decision on side effects | Agent Framework human-in-the-loop requests, approval queue |
| Output | Groundedness, PII and safety checks | Content Safety, custom checks |
| Operations | Tracing, cost dashboards, kill switch | OpenTelemetry, Application Insights, feature flags |
A scoped rollout to [5%] of tenants showed an average of [3.2] model calls and [$0.02] per task at p50 but [$0.30] at p99; adding a cheap model to route simple requests straight to the deterministic workflow cut p99 cost by [60%] with no drop in task success on the evaluation set.
Checks whether the candidate can design an agentic feature as a controlled system with explicit autonomy, permissions, approvals, budgets and evaluation.
Green flags
Red flags
Web/mobile UI ──► ASP.NET Core API ──► Router (small model or rules)
│ │
▼ ▼
Deterministic workflow Agent (AIAgent / IChatClient loop)
│ │ tools = per-user subset
▼ ▼
MediatR handlers (validation + authorisation)
│
Approval store ◄───┤ writes need approval
▼
Domain + database (audit log, idempotency keys)
Cross-cutting: Content Safety, OpenTelemetry GenAI spans, cost meter, feature flags
Microsoft.Extensions.AI (IChatClient) is the abstraction for model calls; the Microsoft Agent Framework (1.0 GA in April 2026, the successor to Semantic Kernel agents and AutoGen) adds agents with threads, middleware, context providers and graph-based workflows with checkpointing and human-in-the-loop requests. A common split: a cheaper, faster model for routing and extraction, a stronger model for multi-step reasoning. Keep the model and deployment in configuration so you can switch after evaluation.
ChatOptions.Tools per request from their permissions).The agent run must be able to pause and resume. Options: return a pending-approval response to the UI and continue the conversation on approval; or use Agent Framework workflows that emit an approval request, checkpoint state and resume when the response arrives. For long approvals (a manager approving a refund), persist the thread and resume from a queue message.
Cost per task ≈ Σ over steps (input tokens × input price + output tokens × output price). Controls: iteration cap, history trimming or summarisation, compact tool results, prompt caching of stable prefixes, routing simple requests away from the agent, per-tenant budgets enforced before each call, and streaming the final answer to improve perceived latency.
Offline: a versioned dataset of real (anonymised) tasks with expected outcomes and tool sequences, scored for task success, correct tool use, groundedness and safety (Microsoft.Extensions.AI.Evaluation can run quality and safety evaluators in xUnit/CI). Online: task completion, approval rejection rate, escalation to human, cost per task, p95 latency. Release behind a flag to a small cohort, compare with control, and keep a kill switch that falls back to the non-AI flow.
Keep data in Azure Australia East where required, use deployments with no data retention for training, redact PII in logs, and record AI-assisted decisions in the audit trail so you can explain them under the Privacy Act's transparency obligations (APP 1) and respond to access requests.
ChatOptions.Tools from the user's roles and write a test that a read-only user never gets a write tool.Per-user tool selection, proposals instead of direct writes, and a budget check before the agent runs.
using System.ComponentModel;
using Microsoft.Extensions.AI;
namespace Bookings.Assistant;
public sealed record ProposedChange(Guid BookingId, DateOnly NewDate, decimal Fee, bool Reversible);
public sealed class BookingTools(ISender mediator, IProposalStore proposals, ICurrentUser user)
{
[Description("Lists the signed-in user's upcoming bookings.")]
public Task<IReadOnlyList<BookingSummary>> ListMyBookings(CancellationToken ct) =>
mediator.Send(new ListBookingsQuery(user.Id), ct);
[Description("Proposes moving a booking to a new date. Does NOT change anything; the user must approve.")]
public async Task<string> ProposeReschedule(Guid bookingId, DateOnly newDate, CancellationToken ct)
{
// Same validation and authorisation as the API, via the handler.
var quote = await mediator.Send(new QuoteRescheduleQuery(user.Id, bookingId, newDate), ct);
if (!quote.Allowed) return quote.Reason!;
var id = await proposals.SaveAsync(user.Id, new ProposedChange(bookingId, newDate, quote.Fee, quote.Reversible), ct);
return $"Proposal {id}: move to {newDate:d}, fee {quote.Fee:C}. Waiting for the user's approval in the app.";
}
}
public sealed class BookingAssistant(IChatClient chat, BookingTools tools, ITenantBudget budget, ICurrentUser user)
{
public async Task<string> AskAsync(IList<ChatMessage> history, CancellationToken ct)
{
if (!await budget.TryReserveAsync(user.TenantId, estimatedTokens: 20_000, ct))
return "The assistant is unavailable for your organisation right now. You can still manage bookings directly.";
List<AITool> allowed = [AIFunctionFactory.Create(tools.ListMyBookings)];
if (user.HasPermission("bookings.change"))
allowed.Add(AIFunctionFactory.Create(tools.ProposeReschedule)); // write tools only for users allowed to write
var response = await chat.GetResponseAsync(history,
new ChatOptions { Tools = allowed, MaxOutputTokens = 800 }, ct);
await budget.CommitAsync(user.TenantId, response.Usage?.TotalTokenCount ?? 0, ct);
return response.Text;
}
}
// Program.cs: the loop caps live in the pipeline
builder.Services.AddChatClient(sp => sp.GetRequiredService<AzureOpenAIClient>()
.GetChatClient(builder.Configuration["AI:AgentDeployment"]!).AsIChatClient())
.UseFunctionInvocation(configure: c => { c.MaximumIterationsPerRequest = 8; c.MaximumConsecutiveErrorsPerRequest = 2; })
.UseOpenTelemetry();
Autonomy is a dial you set per action, not a property of the product. I ask, for each action: what does it cost if the model is wrong, and how quickly would we notice? Reads and reversible changes can be automatic; anything involving money, other people or deletion gets an approval step until data shows it is safe to relax. The architecture should make that dial a configuration change, not a rewrite.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Workflow with LLM steps | Known steps, high volume, strict latency | Low, predictable | Open-ended tasks |
| Agent with proposals (level 1) | Variable tasks that change data | Extra user click | Purely read-only tasks |
| Agent acting with undo (level 2) | Reversible, low-value changes | Undo infrastructure | Irreversible or external effects |
| Multi-agent workflow | Distinct specialised sub-tasks with checkpoints | Most complex, most tokens | A single agent with 5 tools works |
I measure task success, approval rejection rate (a high rate means the agent proposes badly), escalations, cost per successful task and p95 latency, per tenant.
A workflow runs steps you wrote in code and calls the model at known points: classify an email, extract fields, draft a reply. Control flow and state live in your code (or a durable orchestrator), so each step has a known input and output that you can unit-test, retry and cost up front. An agent gets a goal and tools and chooses the steps itself in a loop until it decides it is done. An example is a support assistant that investigates an order across several systems in whatever order the case needs.
Workflows are cheaper, faster and predictable. Agents handle open-ended tasks with unknown paths, at the cost of more calls, variable latency and harder evaluation. Choose a workflow when you can write the steps down, and an agent only when you can't. Then add an iteration and token cap, least-privilege tools, human approval for actions with real-world effect, and tracing of every step.
You can't unit-test an LLM into correctness, so you measure it. Build a golden set of real cases with expected sources or reference answers, including out-of-scope and adversarial ones. Measure retrieval (recall@k) separately from answers (groundedness, relevance, completeness). Run deterministic checks first (valid JSON, valid citations, refusals), then LLM-as-judge evaluators such as those in Microsoft.Extensions.AI.Evaluation, calibrated against human grades.
Treat prompts, model versions and retrieval settings as code: every change runs the suite in CI against thresholds. In production, track feedback and add new failures to the set. The trade-off: a bigger, richer evaluation set catches more regressions but costs more tokens and expert time to build and run.
Measure first: log input and output tokens per request from ChatResponse.Usage and chart cost per feature and per tenant; set Azure Cost Management budgets and alerts on the Azure OpenAI / Foundry resource so spend never surprises you. Then reduce:
ChatOptions.MaxOutputTokens, and cache repeated answers with Microsoft.Extensions.AI's UseDistributedCache() on the ChatClientBuilder (it wraps an ASP.NET Core IDistributedCache such as Redis; exact-match only, so it helps for identical prompts).Re-run your evaluation set after each change, because a cost cut that silently lowers quality is a false saving.
How to tell it (STAR)
**S:** We piloted a booking assistant that could reschedule bookings directly for [about 2,000] users. **T:** After [a week] support reported bookings moved without consent, and I owned the fix. **A:** Traces showed the list tool returned the whole team's bookings and the model chose by name, then the write executed straight away. I disabled the write tool behind the flag, reversed the [37] changes from the audit log, and redesigned writes as proposals the user approves, with tools scoped to the user's own data and ownership checks on every argument. We added ambiguous-name cases to the evaluation set. **R:** Over the next [two months] there were zero unintended changes, and [92%] of proposals were approved first time, which told us the agent was proposing well.
Last updated 23 Nov 2026.