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.
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.
"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."
| 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 |
| 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 |
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.
Checks that the candidate can prove an AI feature's quality with data and protect it against regressions.
Green flags
Red flags
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.
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
RelevanceEvaluator, CoherenceEvaluator, FluencyEvaluator, GroundednessEvaluator, CompletenessEvaluator, EquivalenceEvaluator, RetrievalEvaluator. Scores are typically 1–5 with reasons.ReportingConfiguration with disk or Azure storage; responses cached so unchanged cases don't call the model again; dotnet aieval report produces an HTML report.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.
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.
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.
dotnet aieval report.GroundednessEvaluator.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
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.
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:
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.
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.
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.
Last updated 23 Nov 2026.