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

📚 Interview question

How do you know an AI feature actually works, and keeps working? Explain how you build an evaluation set, which metrics you use (groundedness, relevance, retrieval quality, safety), LLM-as-judge and its limits, and how you regression-test prompt and model changes in CI.

Evaluating AI features in .NET: building a golden evaluation set, retrieval metrics versus answer metrics, groundedness, relevance and completeness with Microsoft.Extensions.AI.Evaluation, LLM-as-judge calibration and bias, deterministic checks, safety evaluation, CI regression gates for prompt and model changes, and production feedback loops.

Senior Theory Advanced ai ci-cd evaluation microsoft-extensions-ai rag testing

🎯 Key points

  • A golden set of 100–300 real, representative cases (including edge, out-of-scope and adversarial ones) with expected sources or reference answers, owned with domain experts and de-identified
  • Measure layers separately: retrieval (recall@k, MRR) before answers (groundedness, relevance, completeness)
  • Deterministic checks first: valid JSON, citations map to sources, refusal when expected, length, banned content
  • LLM-as-judge (Microsoft.Extensions.AI.Evaluation, current as of .NET 10: GroundednessEvaluator, RelevanceEvaluator, CompletenessEvaluator) scales grading but must be calibrated against human labels
  • Safety and fairness evaluation: harmful content, protected material, indirect attack, plus per-group checks where answers affect people; documented testing supports Australia's Voluntary AI Safety Standard (guardrail 4: test before and monitor after deployment)
  • Treat prompts, model versions and retrieval settings as code: every change runs the eval suite in CI with thresholds; cache responses to keep cost down
  • Handle drift: pin model versions, re-run before provider upgrades or retirements, and watch for shifts in user questions and source content
  • Close the loop in production: thumbs, follow-up rate, refusal rate, sampled human review, and new failures added to the set

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"The honest answer is that an AI feature works when the numbers on a representative evaluation set say so, and keeps working when every change is checked against that set. I start by building a golden set with the people who know the domain: a few hundred real questions taken from logs or support tickets, each with the expected source documents and a reference answer or grading notes. I deliberately include questions the system should refuse, ambiguous ones, and injection attempts.

Then I measure in layers. Retrieval first: recall@k and MRR, because if the right chunk isn't retrieved nothing downstream can fix it. Then deterministic checks that need no model: does the JSON parse, does every citation map to a retrieved source, did it refuse when it should. Only then LLM-as-judge for groundedness, relevance and completeness, using Microsoft.Extensions.AI.Evaluation with response caching so CI runs are cheap. For example, on [a policy assistant] we [calibrated the groundedness judge against 100 human-graded answers before trusting it], found it agreed [about 85%] of the time, and used it as a CI gate: a prompt change that looked better in demos dropped groundedness from [4.4 to 3.9] and was rejected.

The mistake I see is 'vibe testing': trying five questions after a change and shipping. The other mistake is trusting the judge blindly; LLM judges favour long, confident answers and share blind spots with the model being graded. So I keep humans in the loop on a sample, pin model versions, and feed real production failures back into the set every sprint. The evaluation set is the specification of an AI feature."


What to measure

Layer Metric How
Retrieval Recall@k, MRR Expected source ids in the golden set
Format and rules JSON valid, citations valid, refusal correct, length Plain code assertions
Answer quality Groundedness, relevance, completeness, equivalence to reference LLM-as-judge evaluators (1–5 scores)
Safety Harmful content, protected material, indirect attack success Safety evaluators, red-team set
Operations p95 latency, tokens and cost per case Usage from responses, timings
Production Thumbs up/down, follow-up rate, escalation rate Telemetry, sampled human review

LLM-as-judge: strengths and limits

Strength Limit Mitigation
Scales to hundreds of cases per run Biased towards long, fluent answers Rubrics with explicit criteria; compare to reference
Grades open-ended text Non-deterministic scores Temperature 0, average several runs for close calls
Cheap compared with experts Same blind spots as the graded model Use a different or stronger judge model; human sample
Fast feedback in CI Can drift when the judge model changes Pin the judge model; re-calibrate after upgrades

Production example

On [the policy assistant], the CI suite ran [250] cases in about [6 minutes] for [about A$4] per run with response caching (cached runs cost almost nothing). Over [six months] it blocked [four] regressions, including one from a provider model upgrade that lowered completeness on multi-part questions.

🔍 What the interviewer is checking

Checks that the candidate can prove an AI feature's quality with data and protect it against regressions.

Green flags

  • Builds a representative golden set with domain experts, including hard cases
  • Separates retrieval and answer metrics
  • Uses deterministic checks plus calibrated LLM-as-judge
  • Gates prompt and model changes in CI with thresholds
  • Has a production feedback loop and pins model versions

Red flags

  • "We tried it and it looked good"
  • Only accuracy on happy-path questions
  • Blind trust in judge scores
  • No plan for model upgrades or drift

📚 Learn in depth

1. Why classic tests aren't enough

LLM output is non-deterministic and open-ended; there are many correct answers and many subtly wrong ones. Unit tests still cover the deterministic parts (prompt building, citation parsing, tool argument validation). Quality needs statistical evaluation over a dataset with thresholds.

2. Building the golden set

production logs / tickets / expert interviews
          │
          ▼
  sample and de-identify ─► label with experts ─► golden set (versioned in git)
                                  │
         expected source ids, reference answer or grading notes, category, difficulty
  • Cover the real distribution (common questions) plus tails: out-of-scope, ambiguous, multi-part, recent changes, adversarial.
  • Version it alongside the code. Never train or tune prompts on the exact test cases you report (keep a held-out slice).
  • Use synthetic or de-identified data for anything personal.

3. Microsoft.Extensions.AI.Evaluation

  • Quality evaluators (LLM-based): RelevanceEvaluator, CoherenceEvaluator, FluencyEvaluator, GroundednessEvaluator, CompletenessEvaluator, EquivalenceEvaluator, RetrievalEvaluator. Scores are typically 1–5 with reasons.
  • Safety evaluators: backed by the Azure AI Foundry evaluation service (harm categories, protected material, indirect attack).
  • Reporting: ReportingConfiguration with disk or Azure storage; responses cached so unchanged cases don't call the model again; dotnet aieval report produces an HTML report.
  • Runs inside MSTest, xUnit or NUnit, so it fits existing CI.

4. CI gating

PR changes prompt / model / retrieval
      │
      ▼
  unit tests ─► eval suite (cached) ─► compare to baseline thresholds ─► pass / fail
                                             │
                          report artefact attached to the PR

Gate on aggregates (mean groundedness ≥ 4.2, recall@5 ≥ 0.85, attack success ≤ 2%) and on no new failures in critical categories.

5. Model lifecycle

Providers retire and upgrade model versions on a published schedule. Pin versions in deployments, and run the suite against the new version well before the retirement date.

6. Production evaluation

Online metrics (thumbs, follow-up rate, refusal rate, escalations) catch what the golden set missed. Sample conversations (with privacy controls) for human review weekly and add failures to the set.

Try it yourself

  1. Write 30 golden cases for a small RAG demo, with expected source ids.
  2. Run the test below; then change the system prompt and compare reports with dotnet aieval report.
  3. Grade 30 answers yourself and compute agreement with GroundednessEvaluator.
  4. Swap the chat model and compare quality, latency and cost per case.
  5. Add five injection cases and measure attack success rate.

💻 Code

An xUnit evaluation test using Microsoft.Extensions.AI.Evaluation with cached responses and a groundedness gate.

// Packages: Microsoft.Extensions.AI.Evaluation, .Quality, .Reporting; xunit
using Microsoft.Extensions.AI;
using Microsoft.Extensions.AI.Evaluation;
using Microsoft.Extensions.AI.Evaluation.Quality;
using Microsoft.Extensions.AI.Evaluation.Reporting;
using Microsoft.Extensions.AI.Evaluation.Reporting.Storage;
using Xunit;

namespace Policies.Evaluation;

public sealed record GoldenCase(string Id, string Question, string[] ExpectedSourceIds);

public sealed class PolicyAssistantEvaluation
{
    private static readonly ReportingConfiguration Reporting = DiskBasedReportingConfiguration.Create(
        storageRootPath: "eval-results",
        evaluators: [new GroundednessEvaluator(), new RelevanceEvaluator(), new CompletenessEvaluator()],
        chatConfiguration: new ChatConfiguration(TestClients.JudgeChatClient()), // pinned judge model
        enableResponseCaching: true,                                          // unchanged cases cost nothing
        executionName: Environment.GetEnvironmentVariable("GITHUB_RUN_ID") ?? "local");

    public static TheoryData<string> CaseIds => new(GoldenSet.All.Select(c => c.Id));

    [Theory]
    [MemberData(nameof(CaseIds))]
    public async Task Answers_are_grounded_and_cite_expected_sources(string caseId)
    {
        var golden = GoldenSet.All.Single(c => c.Id == caseId);
        await using var run = await Reporting.CreateScenarioRunAsync($"policy-assistant.{caseId}");

        var assistant = TestClients.CreateAssistant(run.ChatConfiguration!.ChatClient);
        var (answer, retrieved) = await assistant.AskWithContextAsync(golden.Question, CancellationToken.None);

        // Deterministic checks first: cheap and unambiguous.
        Assert.Contains(retrieved, r => golden.ExpectedSourceIds.Contains(r.Id));   // retrieval hit
        Assert.All(answer.Citations, c => Assert.InRange(c.Number, 1, retrieved.Count));

        // LLM-as-judge for open-ended quality.
        var grounding = string.Join("\n", retrieved.Select(r => r.Text));
        EvaluationResult result = await run.EvaluateAsync(
            [new ChatMessage(ChatRole.User, golden.Question)],
            new ChatResponse(new ChatMessage(ChatRole.Assistant, answer.Text)),
            additionalContext: [new GroundednessEvaluatorContext(grounding)]);

        var groundedness = result.Get<NumericMetric>(GroundednessEvaluator.GroundednessMetricName);
        Assert.True(groundedness.Value >= 4, $"Groundedness {groundedness.Value}: {groundedness.Reason}");
    }
}

Generate the HTML report in CI and attach it to the build:

dotnet tool install --global Microsoft.Extensions.AI.Evaluation.Console
dotnet test tests/Policies.Evaluation
dotnet aieval report --path eval-results --output eval-report.html

⚠ Common mistakes

  • Mistake: Vibe testing a handful of questions after each change. Why it is wrong: small samples miss regressions and confirm what you hoped. Instead: a versioned golden set of 100–300 cases run on every change.
  • Mistake: Only measuring final answers. Why it is wrong: you can't tell retrieval failures from generation failures. Instead: measure retrieval (recall@k) and answers separately.
  • Mistake: Trusting LLM-as-judge scores uncalibrated. Why it is wrong: judges favour long, confident text and drift with model changes. Instead: calibrate against human grades, pin the judge model and re-check after upgrades.
  • Mistake: Skipping deterministic checks. Why it is wrong: format and citation errors are cheap to detect exactly. Instead: assert JSON validity, citations, refusals in code before judging.
  • Mistake: A golden set of only happy-path questions. Why it is wrong: production failures cluster in out-of-scope, ambiguous and adversarial inputs. Instead: include those categories deliberately and report per category.
  • Mistake: Unpinned model versions. Why it is wrong: the provider can change behaviour under the same deployment name. Instead: pin versions and evaluate upgrades before switching.
  • Mistake: Tuning prompts on the same cases you report. Why it is wrong: overfitting makes scores look better than reality. Instead: keep a held-out slice.
  • Mistake: No production feedback loop. Why it is wrong: the set goes stale as users and content change. Instead: add real failures from feedback and reviews every sprint.

🏛 Senior insight: trade-offs

The evaluation set is the specification of an AI feature: it is how product, domain experts and engineers agree on what good looks like. Invest in it early; it makes every later decision (prompt, model, chunking, cost cut) a measured one instead of an argument.

Option When it fits Cost When not to
Deterministic assertions Format, citations, refusals, tool arguments Nearly free Open-ended quality
LLM-as-judge Groundedness, relevance, completeness at scale Tokens per run (cache it) As the only signal for high-stakes outputs
Human expert review Calibration, high-risk domains, new features Expensive, slow Every CI run
Online metrics Real-world drift, satisfaction Needs traffic and telemetry Before launch

Report per category, not just averages: a feature can improve overall while getting worse on the questions that matter most.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions measuring retrieval separately Why: Checks depth on the retrieval layer of evaluation
    How to answer

    Build a labelled set of 50–200 real questions, each with the chunk ids that should come back, written with domain experts from real (de-identified) usage. Then measure:

    • Hit rate / recall@k: is a correct chunk in the top k, and what share of the correct chunks did we get?
    • MRR: the average of 1 / rank of the first correct chunk.
    • nDCG@k: graded relevance, discounted by position.

    In .NET this is a small xUnit test project: load the set from JSON, call the same IEmbeddingGenerator and vector store search the app uses, compute the metrics with LINQ, and fail the build if recall@5 drops below the baseline. Run it on every change to chunking, the embedding model, hybrid weights or the reranker. Retrieval comes before answer quality: if the right chunk isn't retrieved, no prompt fixes the answer.

  2. When: Candidate mentions adversarial or red-team cases Why: Checks whether safety and injection testing are part of the evaluation
    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.

🛠 Real-world problems: how you handle them

A prompt 'improvement' that lowered groundedness
Situation
[A policy assistant] for [about 1,500 staff]. A product owner asked for friendlier, more complete answers, and a developer rewrote the system prompt; demos looked better and the change was about to ship.
Signals
CI evaluation run on the PR: mean groundedness fell from [4.4 to 3.9], completeness rose slightly, and [12] cases now included statements not supported by any source. Recall@5 was unchanged, so retrieval wasn't the cause.
Investigation
Opened the `dotnet aieval report` for the failing cases and compared answers before and after; the new prompt's 'be thorough and helpful' wording encouraged filling gaps from general knowledge. Checked the judge's verdicts against [20] manual grades to confirm the drop was real.
Resolution
Kept the friendlier tone but restored the 'only from sources; say what's missing' rule, and added an instruction to state which parts the sources don't cover. Groundedness returned to [4.4] with completeness [slightly up].
Prevention
Groundedness threshold of 4.2 as a required CI check; evaluation report linked in every PR touching prompts; prompts moved into versioned files with code owners; monthly calibration of the judge against human grades.

How to tell it (STAR)

**S:** A prompt rewrite on our [policy assistant] made demos look friendlier and more complete, and it was about to ship. **T:** I [maintained the evaluation suite] and the CI run flagged it, so I had to work out whether the drop was real. **A:** I compared the report's failing cases, checked [20] of them by hand to confirm the judge, and found the new wording encouraged answers from general knowledge. I kept the tone but restored the grounding rule and made the threshold a required check. **R:** Groundedness went back to [4.4], the friendlier style shipped, and the gate has since [blocked several regressions], including one from a model upgrade.

↩ Usually asked after

More in .NET and AI

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me