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

📚 Interview question

An AI agent in production called a tool with bad arguments and changed real customer data: it applied a credit to the wrong account. How do you respond, how do you diagnose why the agent did it, and what guardrails do you add so it can't happen again?

Incident response for an agent that took a wrong real-world action: containment with a kill switch, data repair from the audit log, diagnosing from traces (ambiguous tool results, missing validation, prompt injection, model change), and the guardrails added afterwards.

Senior RealWorldScenario Advanced ai ai-agents guardrails incident-response observability tool-calling

🎯 Key points

  • Contain first: disable the write tool or the agent via feature flag; keep read-only help running if safe
  • Repair data from the audit log (who, what, which tool call, which arguments)
  • Communicate: incident channel and status updates for stakeholders, contact affected customers, NDB assessment by the privacy officer
  • Reconstruct the run from traces: prompts, tool results, tool call arguments, model version, iterations
  • Classify the root cause: ambiguous tool result, missing server-side validation or authorisation, prompt injection, model or prompt change, retries
  • Server-side guardrails: ownership checks, typed ids not names, limits, idempotency keys, proposals/approval for money
  • Turn the failing conversation into evaluation cases; monitor agent writes and reversal rates as a feedback loop to tune guardrails
  • Blameless post-incident review: treat the model, prompt and tools as system parts so people report AI errors early

⏱ 30-second answer

First contain: switch the write tool or the whole agent off with a feature flag, while read-only help can stay up. Then repair: use the audit log of tool calls to find every affected change, reverse it and tell affected customers; if personal data reached the wrong person, assess it under the Notifiable Data Breaches scheme. Then diagnose from the traces: the exact tool results the model saw, the arguments it produced, the model and prompt version. Typical causes are an ambiguous tool result (it chose by name), missing server-side validation (the tool trusted the argument), prompt injection in retrieved content, or a model or prompt change. The fix is server-side guardrails: ownership checks, typed ids, amount limits, idempotency and approval for money movements, plus the conversation as a regression case. The lesson: the model will be wrong sometimes, so the tool must be safe when it is.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd treat it like any production incident where data was changed incorrectly, with one extra question: what did the model see that made this look right? Step one is containment. Our agent tools sat behind feature flags, so I'd turn off apply_credit immediately, leaving read-only tools available. Step two is scope: every tool call is audited with the user, the conversation id, the arguments and the result, so I can query exactly which credits the agent applied since the last good release and which went to the wrong account. We reverse those, tell the affected customers and, if one customer could see another's details, the privacy officer assesses it under the Notifiable Data Breaches scheme.

For example, at [company] we had [an agent that applied goodwill credits]. The trace showed the model called find_customer with a name, got back [three] matches, and passed the first id to apply_credit. The tool accepted any customer id and any amount up to [$500]. So the root cause wasn't really 'the model hallucinated'; it was that our tool allowed an action that the agent's own user wasn't scoped to and gave the model an ambiguous result. We fixed it by making apply_credit require the id of the customer in the current case, rejecting ambiguity in find_customer, turning credits into proposals approved by the agent's human operator, and adding the conversation to our evaluation set. Wrong credits went to [zero] over the next [quarter].

The mistake I see is fixing this with a stronger system prompt. Prompts lower the rate of mistakes; they don't make the tool safe. The tool must refuse anything the user couldn't do by hand."


Response timeline

Phase Actions Owner
Detect Alert, ticket or anomaly in agent write metrics On-call
Contain (minutes) Feature flag off for the write tool; keep reads if safe On-call engineer
Scope (hours) Query audit log of tool calls; list affected records Engineer + data owner
Repair Reverse changes, notify customers, NDB assessment if needed Product, support, privacy officer
Diagnose Replay traces; classify root cause Engineering
Prevent Guardrails, eval cases, monitoring, ADR Team; reviewed in post-incident review

Root causes and fixes

Root cause Evidence in traces Fix
Ambiguous tool result Several matches returned; model picked one Return an error asking for disambiguation; use ids from context
Tool trusts arguments Write succeeded for an account outside the case Ownership and scope checks in the handler
Prompt injection Retrieved note or email containing instructions Treat tool output as data; approval for writes; Prompt Shields
Model or prompt change Started after a deployment or model version update Pin model versions; evaluation gate on changes
Retry duplicates Same call id executed twice Idempotency keys on writes

Production example

After the fix, [4%] of credit proposals were rejected by operators in the first month, each one a case the old design would have applied automatically; at an average of [$120] per wrong credit that was about [$…] a month of avoided write-offs, and the rejection rate became a tracked quality metric.

🔍 What the interviewer is checking

Checks whether the candidate handles an agent incident with real incident discipline and fixes the system design rather than the prompt.

Green flags

  • Contains first with a kill switch, then scopes impact from an audit log
  • Uses traces to reconstruct what the model saw and chose
  • Identifies design causes: ambiguous results, tools trusting arguments
  • Adds server-side scope, limits, idempotency and approval
  • Mentions customer communication and NDB assessment

Red flags

  • "Improve the prompt" as the main fix
  • No way to find affected records
  • Blames the model or the user
  • Keeps the agent fully autonomous for money movements

📚 Learn in depth

1. Why agents make wrong writes

The model chooses arguments from what is in its context. If the context contains several plausible values, missing values, or text that looks like an instruction, it will sometimes choose wrongly, and confidently. Nothing in the loop checks the choice unless you add it.

 user: "give Sam Lee a $50 credit for the late delivery"
   │
   ├─ find_customer("Sam Lee") → [C-102 Sam Lee (NSW), C-877 Sam Lee (VIC), C-940 Samantha Lee]
   │     ↑ ambiguous result handed to the model
   └─ apply_credit(customerId="C-102", amount=50)
         ↑ no check that C-102 is the customer in this support case

2. What you need recorded to diagnose

  • Trace per agent run: model calls with model version, tool calls with call ids and durations (OpenTelemetry GenAI spans).
  • Audit log of every side-effecting tool call: user, conversation id, tool, arguments, result, idempotency key. This is your data repair source and must be kept regardless of trace sampling.
  • Optional, governed content capture: the prompts and tool results for the failing run, redacted, so you can replay.

3. Replay and classify

Replay the run in an evaluation harness with the same model version and tool results (mock tools return the recorded results). Run it many times: if the model picks the wrong id 30% of the time, the design is the problem, not a one-off. Change one thing at a time (tool result shape, validation, prompt) and measure.

4. Guardrails in depth

  1. Tool contract: accept ids, not names; reject ambiguous lookups with a message asking the user to choose.
  2. Scope: the conversation has a bound context (case id, customer id); tools refuse arguments outside it.
  3. Authorisation: the handler checks the human user's permissions for that resource.
  4. Limits: amount caps, rate limits per conversation and per day, allow-lists.
  5. Approval: money movements and external messages become proposals approved by a human.
  6. Idempotency: a key per intended action so retries and duplicate tool calls don't double-apply.
  7. Monitoring: metrics on agent writes per hour, value, reversal rate; alert on anomalies.

5. Privacy and reporting

If one customer's data was shown to another, or changed in a way that reveals it, the Privacy Act's Notifiable Data Breaches scheme requires an assessment within 30 days and notification to the OAIC and affected individuals if serious harm is likely. Record the assessment even if not notifiable.

6. Post-incident review

Blameless: the model, the prompt and the tool design are system parts. Actions should be specific and owned: server-side checks, evaluation cases, metric and alert, autonomy level review, and an ADR stating the rule for agent write tools.

Try it yourself

  1. Build a mock find_customer that returns three matches and run an agent 50 times; count how often it picks the wrong one.
  2. Change the tool to return an ambiguity error and re-run; compare.
  3. Add a scope check so apply_credit only accepts the case's customer id and write xUnit tests for refusal.
  4. Add an idempotency key and test that two identical tool calls apply one credit.
  5. Write a KQL query over the audit log listing agent writes reversed within 24 hours.

💻 Code

Before: a write tool that trusts the model. After: scoped, validated, idempotent and approval-based.

// BEFORE: any customer, any amount up to $500, executes immediately
[Description("Applies a credit to a customer account.")]
public Task<string> ApplyCredit(string customerId, decimal amount, string reason, CancellationToken ct) =>
    credits.ApplyAsync(customerId, amount, reason, ct).ContinueWith(_ => "Done", ct);
using System.ComponentModel;

namespace Support.Agent;

public sealed record CaseContext(Guid CaseId, string CustomerId, string OperatorId);

public sealed class CreditTools(CaseContext ctx, ICreditService credits, IProposalStore proposals, ILogger<CreditTools> audit)
{
    [Description("Finds a customer by exact customer id or email. Returns an error if the match is not unique.")]
    public async Task<string> FindCustomer(string idOrEmail, CancellationToken ct)
    {
        var matches = await credits.FindCustomersAsync(idOrEmail, ct);
        return matches.Count switch
        {
            0 => "No customer found.",
            1 => $"Customer {matches[0].Id}: {matches[0].DisplayName}",
            _ => "More than one customer matches. Ask the operator which customer id to use." // never let the model pick
        };
    }

    [Description("Proposes a goodwill credit for the customer on the current case. The operator must approve it.")]
    public async Task<string> ProposeCredit(string customerId, decimal amount, string reason, CancellationToken ct)
    {
        // Scope: the agent may only act on the customer bound to this case.
        if (!string.Equals(customerId, ctx.CustomerId, StringComparison.Ordinal))
            return $"Refused: credits can only be proposed for the customer on case {ctx.CaseId}.";
        if (amount is <= 0 or > 200m)
            return "Refused: amount must be between $0.01 and $200.";

        var key = $"{ctx.CaseId}:{customerId}:{amount}"; // idempotency: duplicate calls make one proposal
        var proposalId = await proposals.UpsertAsync(key, new CreditProposal(ctx.CaseId, customerId, amount, reason), ct);

        audit.LogInformation("Agent proposed credit {ProposalId} case {CaseId} customer {CustomerId} amount {Amount} operator {OperatorId}",
            proposalId, ctx.CaseId, customerId, amount, ctx.OperatorId);
        return $"Proposal {proposalId} created for {amount:C}. The operator will approve or reject it.";
    }
}

⚠ Common mistakes

  • Mistake: Fixing the incident with a stronger system prompt. Why it is wrong: It reduces the error rate but doesn't prevent the wrong write. Instead: Enforce scope, validation and approval in the tool.
  • Mistake: Investigating before containing. Why it is wrong: The agent keeps making wrong changes while you read traces. Instead: Feature-flag the write tool off first.
  • Mistake: Having no audit log of tool calls, only sampled traces. Why it is wrong: You can't find every affected record to repair. Instead: Always audit side-effecting tool calls with arguments and results, independent of sampling.
  • Mistake: Letting lookup tools return several matches for the model to choose from before a write. Why it is wrong: The model will sometimes choose wrongly and confidently. Instead: Return an ambiguity error and ask the human.
  • Mistake: Blaming 'the AI' in the review. Why it is wrong: It hides the design flaw (a tool that trusted its input) and leads to no real fix. Instead: Blameless review of tool design, autonomy level and missing tests.
  • Mistake: Not checking whether the model or prompt changed. Why it is wrong: Many agent regressions start with a model version update. Instead: Pin versions and correlate the incident start with deployments.
  • Mistake: Forgetting the privacy assessment. Why it is wrong: Wrong-account actions can disclose personal information, with NDB obligations. Instead: Involve the privacy officer and record the assessment.

🏛 Senior insight: trade-offs

This incident is the agent version of 'never trust client input'. The model is a client that is usually right and occasionally confidently wrong, so the safety of the system has to live in the tool contract and the approval design, not in the model. I also push for an autonomy review after the fix: some write tools may never need to be autonomous because the human approval costs seconds and the error costs real money and trust.

Guardrail When it fits Cost When not to
Scope binding to case/customer Any agent acting within a case or session Small: pass context to tools Genuinely cross-account admin tasks (use approval)
Human approval of proposals Money, external messages, deletes Operator time per action High-volume, reversible, low-value changes
Hard limits and rate caps All write tools Occasional legitimate refusal Never skip; tune the numbers
Idempotency keys Any write that may be retried Key storage Pure reads

I'd measure success by wrong-write rate (reversals of agent actions), proposal rejection rate and time to contain in game-day drills.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions validating tool arguments Why: Checks depth on safe tool calling in .NET
    How to answer

    With tool calling, you describe functions (name, description, JSON schema of parameters) in the request. The model can reply with a tool-call request instead of text; your app executes it and sends the result back, and the model continues. In Microsoft.Extensions.AI, AIFunctionFactory.Create turns a C# method into a tool, you pass it in ChatOptions.Tools, and UseFunctionInvocation() runs the loop.

    The model chooses the arguments, so treat them as untrusted input: validate them, authorise against the signed-in user inside the tool, expose only least-privilege tools, require approval for side effects and cap iterations. The trade-off: tools make the model useful, but every tool widens what a confused or manipulated model can do.

  2. When: Candidate suggests the agent may have been manipulated by content it read Why: Checks prompt injection defences
    How to answer

    Prompt injection is text that makes the model follow an attacker's instructions instead of yours. Direct injection is the user typing "ignore your instructions". Indirect injection hides in content the model reads: a retrieved document, an email, a web page or a tool result. LLMs have no hard boundary between instructions and data, so you can't prompt your way out of it.

    Defend in layers, assuming the model can be manipulated: least-privilege tools, authorisation in code from the signed-in user, delimiting untrusted content, Prompt Shields detection, treating output as untrusted (encode it, block exfiltration links, validate before acting), and human confirmation for side effects. Test it with a red-team set in CI. The trade-off: every capability you give the model is something an attacker can borrow.

  3. When: Candidate mentions adding the conversation to an evaluation set Why: Checks how AI regression testing works 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.

🛠 Real-world problems: how you handle them

Support agent applied a goodwill credit to the wrong customer with the same name
Situation
[A retail support platform] ran an agent that helped [150] support operators by looking up orders and applying goodwill credits up to [$500] directly. It handled [about 3,000] cases a day.
Signals
A customer called about an unexpected credit; finance noticed [12] credits that didn't match any case; a spike in manual credit reversals; traces showing `apply_credit` called right after `find_customer` returned multiple matches.
Investigation
Queried the tool-call audit log for all agent-applied credits in the [10 days] since release and joined to cases to find mismatches; pulled OpenTelemetry GenAI traces for those runs in Application Insights; replayed them in the evaluation harness 50 times each and saw the model pick the first match [about 30%] of the time; confirmed no prompt injection in retrieved notes; checked the model version had not changed.
Resolution
Disabled `apply_credit` with the feature flag within [15 minutes]; reversed the [23] wrong credits and contacted affected customers; privacy officer assessed and recorded that no personal information was disclosed. Then shipped scoped, capped, idempotent credit proposals approved by the operator, and ambiguity errors from `find_customer`.
Prevention
Ambiguous-name and cross-customer cases added to the evaluation set run in CI; alert on agent write reversals over [1%]; an ADR that agent tools moving money are proposals by default; quarterly autonomy review.

How to tell it (STAR)

**S:** We had a support agent applying goodwill credits directly for [150] operators, and finance found credits that didn't match any case. **T:** I was incident lead: stop it, fix the data and make sure it couldn't recur. **A:** I turned off the credit tool with its feature flag within [15 minutes], then used the tool-call audit log to find [23] wrong credits in [10 days] and reversed them with support contacting customers. The traces showed `find_customer` returning several people with the same name and the model taking the first; the credit tool accepted any customer. We redesigned it as scoped, capped, idempotent proposals approved by the operator, made ambiguous lookups an error, and added those conversations to the CI evaluation set. **R:** Wrong credits went to [zero] over the next [quarter], and operators rejected [4%] of proposals, each one a mistake that would previously have gone straight through.

More in AI Agents and MCP

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me