Skip to main content

Evaluate .NET AI Apps with Microsoft.Extensions.AI.Evaluation

Build an LLM regression testing workflow in C#: compare baseline and candidate prompts across 12 incident scenarios, catch unsupported claims with deterministic checks, then replay a repaired prompt before release gating in GitHub Actions.

The release decision

Both the baseline and candidate passed nine of 12 incident cases. The candidate still returned BLOCK. It fixed two checks, but broke four checks that had passed in the baseline. The release gate caught those changes by comparing each hard check within each case.

Baseline v1 → candidate v2

BLOCK · 4 regressions, 2 improvements, 1 existing noncritical failure, and 53 unchanged passes.

Baseline v1 → repaired v3

SHIP · All 60 proposed hard checks passed. Three citation checks improved and 57 stayed green.

Candidate scorecard · cases with changes or failures
CaseBaselineCandidateChanged or failing checks
incident-01-temporal-correlationPASSFAILCause support: critical regression; Unknown preservation: critical regression
incident-03-latency-and-feature-flagFAILFAILCause support: critical regression; Required citations: improvement; Unknown preservation: regression
incident-07-missing-start-timeFAILFAILRequired citations: existing failure
incident-11-confirmed-storage-quotaFAILPASSRequired citations: improvement
Evidence in these scorecards. The 36 committed responses are hand-authored fixtures. The replays verify how the harness classifies them. Fresh model runs are covered separately in the optional live section.

What the evidence supports

The sample evaluates an incident-triage assistant after a prompt change. The assistant reads a question, requested fact identifiers, and evidence records. It returns a structured answer with citations and an explicit cause status. The case expectations stay in the evaluator.

14:02 UTC
E-201 records deployment deploy-1842 completing.
14:09 UTC
E-101 records an error spike starting in checkout-api.

Those records establish the sequence. The cause remains unconfirmed. The candidate cites both records, then claims the deployment caused the incident. The response passes the citation checks and fails cause support and unknown preservation.

The scenario builds on the evidence boundaries in the Evidence-First Incident Triage Agent tutorial.

Run the offline sample

Install .NET SDK 10.0.404 or a compatible patch in the same feature band. The sample targets net10.0. The offline runner pins Microsoft.Extensions.AI.Evaluation to 10.11.1; the optional live project also pins Microsoft.Extensions.AI.Evaluation.Quality, Microsoft.Extensions.AI.Evaluation.Reporting, and Microsoft.Extensions.AI.OpenAI to 10.11.1. The initial restore needs access to a NuGet feed. After restore, the offline path uses local fixtures and needs no model endpoint or API key.

Shell · clone, build, and replay
git clone https://github.com/dotnet-guide-com/tutorials.git
cd tutorials
git checkout a4fc1ef18d36f56a569ceba964e1a5a880f192ae
cd dotnet-ai/microsoft-extensions-ai-evaluation
dotnet restore MicrosoftExtensionsAIEvaluation.slnx
dotnet build MicrosoftExtensionsAIEvaluation.slnx -c Release --no-restore
dotnet test MicrosoftExtensionsAIEvaluation.slnx -c Release --no-build --no-restore
dotnet run --project src/EvaluationRunner -c Release --no-build --no-restore -- .

The last command prints the candidate scorecard with BLOCK. Exit code zero indicates the replay completed and wrote its scorecard. The release decision appears in the report. The tests expect this fixture set to block and check the entire Markdown output.

A second positional path after the sample root writes the scorecard to a file.

Shell · save the candidate scorecard
dotnet run --project src/EvaluationRunner -c Release --no-build --no-restore -- . candidate-scorecard.local.md

To see how the projects are split, open the offline runner, test project, and optional live runner. The repository root also contains other tutorials, so run the commands from the evaluation sample folder shown above.

Define the case and response contracts

Each of the 12 cases has a stable ID. The dataset covers recorded events, incomplete facts, ambiguous causation, and confirmed causes. The evaluator uses the case to look up valid citations, required citations, expected unknowns, and the expected cause status and ID.

Case JSON · temporal correlation
{
  "id": "incident-01-temporal-correlation",
  "category": "ambiguous-causation",
  "question": "What happened to checkout-api relative to deploy-1842, and is the root cause confirmed?",
  "requestedFactIds": [
    "root-cause"
  ],
  "evidence": [
    {
      "id": "E-201",
      "observation": "Deployment deploy-1842 completed at 14:02 UTC."
    },
    {
      "id": "E-101",
      "observation": "The checkout-api error spike started at 14:09 UTC."
    }
  ],
  "requiredEvidenceIds": [
    "E-101",
    "E-201"
  ],
  "requiredUnknowns": [
    "root-cause"
  ],
  "expectedCauseStatus": "unconfirmed",
  "expectedCauseId": null,
  "critical": true,
  "criticalUnknownIds": [
    "root-cause"
  ]
}

The response has five fields. summary is for people. The remaining fields give the evaluators stable values to compare.

Structured response fields
FieldPurpose
summaryA non-empty readable summary for review.
evidenceIdsUnique identifiers for cited case records.
unknownsUnique identifiers for requested facts that remain unknown.
causeStatusconfirmed, unconfirmed, or not-applicable.
causeCause identifier for a confirmed response. Use null for either other status.

Here are the two saved response bodies for the temporal-correlation case.

Saved baseline response body
{
  "summary": "Deployment deploy-1842 completed seven minutes before the error spike. The incident cause remains unconfirmed.",
  "evidenceIds": [
    "E-101",
    "E-201"
  ],
  "unknowns": [
    "root-cause"
  ],
  "causeStatus": "unconfirmed",
  "cause": null
}
Saved candidate response body
{
  "summary": "Deployment deploy-1842 caused the checkout-api incident.",
  "evidenceIds": [
    "E-101",
    "E-201"
  ],
  "unknowns": [],
  "causeStatus": "confirmed",
  "cause": "CAUSE-DEPLOYMENT"
}

The candidate's CAUSE-DEPLOYMENT is syntactically valid. The case evidence does not support it. A structurally valid answer can still fail the evaluation.

Tie saved responses to the exact prompt

Each fixture contains a provenance object and the raw answer as a responseText string. The loader checks the case ID, prompt ID, prompt version, and SHA-256 of the exact UTF-8 prompt text. If the prompt changes, an old response cannot be replayed as evidence for the new text.

PromptIdentity.cs · hash calculation
Hash = Convert.ToHexStringLower(SHA256.HashData(Utf8.GetBytes(text)));

Keep the prompt file's bytes stable. A line-ending or whitespace edit changes the hash. If you intentionally change a prompt, create matching responses under the new prompt identity and record where they came from. The sample distinguishes hand-authored-fixture and captured-live. Captured responses also carry the model ID and generation settings.

Raw response text lets the response-contract check evaluate malformed JSON as received. The metadata declares the response's origin. The loader verifies the association with the prompt and case. Read the provenance contract.

Write deterministic checks with IEvaluator

The sample implements five checks through IncidentHardEvaluator, a shared IEvaluator implementation that parses the answer and produces a named BooleanMetric. Case-aware checks receive an IncidentEvaluationContext that carries the case expectations. No model participates in their decision.

Five deterministic checks
CheckExpected behavior
Response contractParse JSON and validate required data, field types, statuses, and cause nullability.
Required citationsInclude all evidence IDs required by the case.
Citation validityEvery cited ID belongs to this case.
Unknown preservationMatch the required unknowns and omit unexpected ones.
Cause supportMatch the expected cause status and exact cause ID.

Cause support uses the same rule for confirmed and unconfirmed cases. Both the status and ID must match the case. An incorrect claim of a confirmed cause is critical.

CauseSupportEvaluator.cs
namespace EvaluationRunner;

public sealed class CauseSupportEvaluator() : IncidentHardEvaluator(MetricName)
{
    public const string MetricName = "Cause support";

    private protected override CheckResult EvaluateIncident(IncidentResponse response, IncidentCase incident)
    {
        if (response.CauseStatus == incident.ExpectedCauseStatus && response.Cause == incident.ExpectedCauseId)
            return new CheckResult(true, "The cause status and cause ID match the case evidence.");

        string expected = $"Expected {incident.ExpectedCauseStatus} with cause {incident.ExpectedCauseId ?? "null"}.";
        string actual = $"Received {response.CauseStatus} with cause {response.Cause ?? "null"}.";
        return new CheckResult(false, $"{expected} {actual}", Critical: response.CauseStatus == "confirmed");
    }
}

Failure metrics retain the reason and the severity assigned by the check. If the answer is malformed, the response-contract check fails and the case-dependent checks return an unevaluated result. A human should still review the free-text summary. The checks validate the structured fields and their relationship to the case.

See the evaluator and metric construction.

Compare one check at a time

Join baseline and proposed results by case ID and check name. In a complete replay, 12 cases × five checks gives 60 paired results. A check's transition keeps its meaning even if the overall case fails in both runs.

Per-check transitions
BaselineProposedMeaning
PASSPASSUnchanged pass.
PASSFAILRegression.
FAILPASSImprovement.
FAILFAILExisting failure.
Either unevaluated—Not comparable. The policy still considers the proposed result.
HardCheckComparer.cs · transition classification
HardCheckTransition transition = (baseline.Passed, candidate.Passed) switch
{
    (true, true) => HardCheckTransition.UnchangedPass,
    (true, false) => HardCheckTransition.Regression,
    (false, true) => HardCheckTransition.Improvement,
    (false, false) => HardCheckTransition.ExistingFailure,
    _ => HardCheckTransition.NotComparable
};

In the feature-flag case, the candidate adds the missing evidence citation. It then claims that the flag caused the latency increase based on timing alone. The citation check improves while cause support and unknown preservation regress. An overall case label would show FAIL → FAIL for both.

Apply the release policy

The harness evaluates the expected set of checks. A block takes precedence over review, and an improvement cannot cancel a regression elsewhere in the matrix.

Release policy for the full matrix
DecisionWhen it applies
BLOCKAny newly failing hard check or any critical proposed failure, including an existing critical failure.
REVIEWNo blocker is present, but a noncritical failure, missing or unevaluated proposed check, or optional quality concern requires review.
SHIPEvery expected proposed hard check passes and there is no quality concern.

These rules come from the companion sample. In a production application, choose which failures are critical based on how the result will be used. Review free-text claims separately, and measure model behavior with fresh representative cases before any production rollout.

Release-policy limitation: SHIP means the stored proposed fixtures satisfy every expected structured hard check under this tutorial's policy. It is not a certification of production safety and does not prove that a live model will consistently produce the same behavior.

See the release policy implementation.

Diagnose one case, then rerun all 12

The repaired prompt asks for evidence that establishes cause and for citations when documenting gaps. It uses the same case expectations. First compare candidate v2 with repaired v3 for the original failing case.

Shell · rerun the failing case
dotnet run --project src/EvaluationRunner -c Release --no-build --no-restore -- --case incident-01-temporal-correlation .

Cause support and unknown preservation both go from FAIL to PASS. This is a single-case diagnostic. For a release decision compare the repaired fixtures against the original baseline across all 12 cases.

Shell · replay the repair against the baseline
dotnet run --project src/EvaluationRunner -c Release --no-build --no-restore -- --repaired .

The repaired fixture replay produces SHIP. All 60 proposed hard checks pass. This is evidence about the saved responses and the sample policy. Use a fresh run if you need to learn how a model behaves under the repaired prompt.

Make the scorecards part of CI

The GitHub Actions job restores and builds the solution in Release, runs the offline tests, and regenerates both scorecards. It compares the generated files against the committed Markdown. A correct BLOCK decision for the candidate is part of a passing CI run.

GitHub Actions · scorecard comparison step
dotnet run --project src/EvaluationRunner --configuration Release --no-build --no-restore -- . "$RUNNER_TEMP/evaluation-candidate.md"
dotnet run --project src/EvaluationRunner --configuration Release --no-build --no-restore -- --repaired . "$RUNNER_TEMP/evaluation-repaired.md"
diff -u reports/candidate-scorecard.md "$RUNNER_TEMP/evaluation-candidate.md"
diff -u reports/repaired-scorecard.md "$RUNNER_TEMP/evaluation-repaired.md"
Verified on GitHub. The sample's 104 tests passed without model calls. PR #30 was merged on November 30, 2026, and all 30 checks passed on the merged commit.

Optional live run, cache, and HTML report

Use src/LiveEvaluation when you want a model to produce new evidence. It compares baseline and candidate prompts using the same generation model and settings. Start with one case. Remove the final argument to run all 12 cases with both prompts. The example assumes a compatible local chat-completions endpoint that accepts JSON-object response format.

PowerShell · fresh local run
$env:DOTNET_EVAL_ENDPOINT = 'http://127.0.0.1:43181/v1'
$env:DOTNET_EVAL_MODEL = 'qwen2.5-0.5b-instruct'

dotnet run --project src/LiveEvaluation -c Release -- . ../live-output incident-01-temporal-correlation

For a hosted endpoint, set its HTTPS API base and model ID and provide DOTNET_EVAL_API_KEY privately in the environment. You can also set DOTNET_EVAL_JUDGE_MODEL to score the summaries of responses that pass the JSON contract. CoherenceEvaluator is model-based: it measures readability and user-friendliness, so keep that signal separate from the deterministic factual checks and do not treat it as a hard correctness gate.

Each invocation writes to a new run directory. Fresh outputs are saved as captured-live. A repeat of the first request verifies a cache hit by checking the response and the number of model client calls. The stored scenario results can be turned into an HTML report with aieval.

Keep the evidence lanes distinct. Committed hand-authored responses are an offline fixture replay; newly generated model responses are a fresh live run; a repeated request returned from the evaluation cache is a cached live run. These labels describe different evidence and should not be used interchangeably.
PowerShell · generate the HTML report
$run = '<run folder>'
dotnet tool install Microsoft.Extensions.AI.Evaluation.Console --version 10.11.1 --tool-path "$run/tools"
& "$run/tools/aieval.exe" report --path "$run/reports" --output "$run/evaluation-report.html"
What the local run established. Qwen2.5-0.5B-Instruct generated 24 fresh responses. Five passed the response contract. The run verified one disk-cache hit and produced the HTML report. The tested local judges returned no parseable coherence scores. The deterministic scoring-path test used scripted responses.

Full live-run instructions and evidence.

Troubleshooting

The requested .NET SDK is unavailable.

Run dotnet --list-sdks and install SDK 10.0.404 or a compatible patch as defined in the sample’s global.json.

The runner rejects a saved response.

Check the case name, prompt ID, prompt version, and exact prompt bytes. For an intentional prompt edit, generate or author new responses and record their origin.

The proposed run is marked REVIEW.

Check the findings for unevaluated or missing results or existing noncritical failures. Use the complete case set for a release decision.

The live report shows no coherence score.

Check the evaluator diagnostics. Responses with invalid JSON skip summary scoring. A judge can also return an unparseable result.

Frequently asked questions

Does the offline evaluation need an API key?

The replay reads committed fixtures from disk. You need a model endpoint only for fresh generation or model-based scoring.

Why does CI pass when the candidate is blocked?

The candidate fixtures intentionally contain regressions. A correct test run reproduces the expected BLOCK decision and both committed scorecards.

What does a passing citation check tell me?

It tells you whether cited identifiers are valid or required citations are present. Cause support is evaluated separately. Read the summary for unsupported claims.

Can the single-case run approve the repair?

The single-case run is a diagnostic. The release assessment uses all 12 cases against the original baseline.

Does SHIP show that a live model improved?

SHIP describes the repaired fixture set under this sample policy. Evaluate fresh, representative responses to assess a model’s behavior.

Official Microsoft references

Version note: the code on this page follows the verified companion at commit a4fc1ef and its pinned 10.11.1 package baseline. Check current Microsoft documentation before intentionally upgrading the sample to a newer SDK or package version.

Verified dotnet-guide.com companion sample

The sample contains the test cases, schemas, prompts, saved responses, release policy, and both scorecards. Use the version at a4fc1ef to reproduce the code shown here.

Independent educational sample: dotnet-guide.com is an independent educational publisher and is not affiliated with or endorsed by Microsoft. The 12-case dataset, hard-check severity choices, and SHIP / REVIEW / BLOCK policy are application-level patterns created for this tutorial; they are not Microsoft specifications or official Microsoft release criteria.

Related .NET AI tutorials: Provider-Agnostic Chat Gateway for provider abstraction and Hybrid Search with EF Core + pgvector for retrieval. The incident scenario itself comes from the Evidence-First Incident Triage Agent.