📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

You're asked to add an agentic feature to a .NET SaaS product, for example an assistant that can look up and change customer bookings. How do you decide whether it should be an agent at all, and how do you design the guardrails, human-in-the-loop approvals, cost control and evaluation around it?

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.

Senior Architecture Advanced ai ai-agents architecture guardrails human-in-the-loop microsoft-agent-framework

🎯 Key points

  • Start from the task: use an agent only when the path varies per request; otherwise a deterministic workflow with LLM steps
  • Choose an autonomy level per action: suggest → draft for approval → act with undo → act autonomously
  • Tools wrap existing use cases with the user's permissions; reads auto-approved, writes gated
  • Layered guardrails: input checks (Azure AI Content Safety Prompt Shields), tool argument validation, output checks, hard limits
  • Human-in-the-loop via approval requests that pause and resume the agent (Agent Framework workflows or an approval queue)
  • Budgets: max iterations, tokens and cost per request and per tenant; cheaper model for routing; caching
  • Privacy by design: Privacy Act APPs (transparency, APP 11 security), data kept in Australia East, no-retention deployments, redacted logs
  • Evaluate offline before each change, then monitor continuously (task success, rejections, feedback, cost) and recalibrate; feature-flag rollout with a kill switch

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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."


Agent or workflow?

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

Autonomy levels per action

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

Guardrail layers

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate can design an agentic feature as a controlled system with explicit autonomy, permissions, approvals, budgets and evaluation.

Green flags

  • Questions whether an agent is needed and offers a workflow alternative
  • Defines autonomy per action, with approvals for side effects
  • Tools reuse existing handlers with the user's permissions
  • Concrete budgets and caps; per-tenant cost control
  • Evaluation set, feature flag rollout and kill switch

Red flags

  • "The prompt tells it not to" as the safety story
  • One broad tool set for all users
  • No plan for cost or for measuring quality
  • Fully autonomous writes from day one

📚 Learn in depth

1. Reference architecture

 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

2. Choosing the model and framework

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.

3. Designing tools for an agent

  • One tool per business action, with typed, validated parameters.
  • Expose only the tools this user may use (build ChatOptions.Tools per request from their permissions).
  • Writes return a proposal (what will change, cost, reversibility) rather than executing, unless the action is level 2–3.
  • Make writes idempotent with keys so retries don't double-apply.

4. Human-in-the-loop mechanics

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.

5. Cost and latency budgets

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.

6. Evaluation and rollout

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.

7. Privacy and compliance

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.

Try it yourself

  1. Write the same booking change as a workflow and as an agent; compare model calls, latency and failure modes on 50 test requests.
  2. Build ChatOptions.Tools from the user's roles and write a test that a read-only user never gets a write tool.
  3. Implement a proposal/approve flow and a test that a rejected proposal changes nothing.
  4. Add a per-tenant token budget check before each model call and alert at 80%.
  5. Run an evaluation of 100 tasks in CI and fail the build when task success drops by more than 3 points.

💻 Code

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();

⚠ Common mistakes

  • Mistake: Building an agent for a task with a fixed sequence of steps. Why it is wrong: You pay for unpredictability, latency and cost with no benefit. Instead: Use a workflow with LLM calls only where language understanding is needed.
  • Mistake: Relying on the system prompt to stop harmful actions. Why it is wrong: Prompts can be overridden by injection or ignored by the model. Instead: Enforce permissions, validation and approvals in code.
  • Mistake: Giving every user the full tool set. Why it is wrong: The agent can attempt actions the user isn't allowed, and injection has more to work with. Instead: Build the tool list per request from the user's permissions.
  • Mistake: Executing writes directly from tool calls. Why it is wrong: A hallucinated argument changes real data. Instead: Return proposals for approval, or act with undo for low-risk changes.
  • Mistake: No per-tenant cost budget. Why it is wrong: One heavy tenant or a loop can blow the monthly spend. Instead: Reserve and commit token budgets, cap iterations and alert on spend.
  • Mistake: Shipping on demo quality without an evaluation set. Why it is wrong: You can't tell whether a prompt or model change made it better or worse. Instead: Gate changes on an offline evaluation and watch online metrics.
  • Mistake: No fallback path. Why it is wrong: A model outage or a bad release takes the feature down entirely. Instead: A kill switch that returns users to the normal UI flow.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate argues for or against using an agent Why: Checks the agent-versus-workflow decision in more depth
    How to answer

    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.

  2. When: Candidate mentions an evaluation set Why: Checks how they build and use AI evaluation in CI
    How to answer

    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.

  3. When: Candidate mentions budgets or cost per tenant Why: Checks practical LLM cost controls
    How to answer

    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:

    • Use a smaller model for simple steps (routing, classification, extraction), trim history and system prompts, and use retrieval instead of stuffing whole documents.
    • Cap 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).
    • Enforce budgets per user or tenant with rate limiting.

    Re-run your evaluation set after each change, because a cost cut that silently lowers quality is a false saving.

🛠 Real-world problems: how you handle them

Booking assistant rescheduled the wrong booking for customers with similar names
Situation
[A booking SaaS] piloted an agent that could reschedule bookings directly for [2,000] users in [a few] tenants. Each tenant had [hundreds] of bookings per day.
Signals
Support tickets about bookings moved without consent; an increase in reschedule-then-reverse pairs in the audit log; the agent's own traces showed `RescheduleBooking` called with booking ids taken from a list result for a different customer.
Investigation
Pulled OpenTelemetry GenAI traces for the affected conversations in Application Insights; saw that `ListBookings` returned bookings for the whole team account and the model picked one by name match; reviewed the tool permissions and found writes executed directly; replayed the conversations against the evaluation harness to reproduce.
Resolution
Turned the write tool off with the feature flag the same day and reversed the [37] wrong changes from the audit log. Then changed writes to proposals approved in the UI, scoped `ListBookings` to the user's own bookings, and added argument checks that the booking belongs to the user.
Prevention
Evaluation cases with ambiguous names and shared accounts; a metric for proposal rejection rate; an ADR making 'writes are proposals by default' the rule for agent tools; quarterly review of autonomy levels.

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.

More in AI Agents and MCP

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me