STAF.LLMEval 2.2.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package STAF.LLMEval --version 2.2.0
                    
NuGet\Install-Package STAF.LLMEval -Version 2.2.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="STAF.LLMEval" Version="2.2.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="STAF.LLMEval" Version="2.2.0" />
                    
Directory.Packages.props
<PackageReference Include="STAF.LLMEval" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add STAF.LLMEval --version 2.2.0
                    
#r "nuget: STAF.LLMEval, 2.2.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package STAF.LLMEval@2.2.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=STAF.LLMEval&version=2.2.0
                    
Install as a Cake Addin
#tool nuget:?package=STAF.LLMEval&version=2.2.0
                    
Install as a Cake Tool

STAF.LLMEval

STAF.LLMEval is a .NET LLM evaluation and AI testing library for validating generative AI responses (ChatGPT, GPT, Gemini, Ollama, Azure OpenAI) in unit tests and CI pipelines.

Score outputs with pluggable metrics (exact, keyword, TF-IDF semantic similarity, JSON/schema, relevance, heuristic grounding), LLM-as-judge, and RAG grounding / hallucination detection. Includes a fluent Eval API, test assertions, Options/DI, JSON/JSONL/CSV evaluation suites, golden baseline comparison, and HTML/JSON/Markdown/CSV reports.

Package: STAF.LLMEval · Version: 2.2.0 · Targets: net8.0, net9.0, net10.0 · License: MIT

Release notes — 2.2.0

  • Richer asserts: metric / grounding / usage in failure messages; optional because:; ShouldMeetPassRate for suite CI gates
  • EvalTraits + suite case tags / FilterByTags for CI filtering
  • LLMEVAL_REPORT_DIR / ReportPaths for artifact folders
  • CI templates: GitHub Actions + Azure DevOps (samples/ci) with pass-rate fail + report upload
  • Framework-specific NuGet packages not required — asserts stay in the main package

Release notes — 2.1.0

  • Plugin metrics: IEvaluationMetric / MetricRegistry (exact, keyword, semantic TF-IDF, json, schema, relevance, grounded-heuristic + custom)
  • Datasets: CSV (+ JSON/JSONL); golden baseline comparison for CI
  • Reports: Markdown + CSV in addition to HTML/JSON
  • Usage: best-effort TokenUsage / cost when providers return usage
  • Grounding: GroundednessScore, HallucinationRate
  • Backward compatible with EvaluationRequest / EvaluateAsync

Full changelog: https://github.com/sooraj171/LLMEval/blob/main/CHANGELOG.md

Installation

dotnet add package STAF.LLMEval

Quick start (no API key)

using LLMEval;

var result = await Eval.Direct()
    .Exact(actual: "Paris", expected: "Paris")
    .WithThreshold(1.0)
    .EvaluateAsync();

result.ShouldPass();
result.ShouldScoreAbove(0.9);

Other Direct matchers:

await Eval.Direct().Keyword(actual, expected).WithThreshold(0.5).EvaluateAsync();
await Eval.Direct().Semantic(actual, expected).WithThreshold(0.3).EvaluateAsync(); // TF-IDF (not embeddings)
await Eval.Direct().Json("""{"ok":true}""").EvaluateAsync();
await Eval.Direct().Schema(actualJson, jsonSchema).EvaluateAsync();
await Eval.Direct().Relevance(question, actual).WithThreshold(0.2).EvaluateAsync();
await Eval.Direct().GroundedHeuristic(actual, referenceDoc).WithThreshold(0.5).EvaluateAsync();

Assertions

result.ShouldPass(because: "exact capital");
result.ShouldScoreAbove(0.8);
result.ShouldBeGrounded(); // fails if RiskLevel is High or unsupported statements exist
report.ShouldMeetPassRate(0.9, because: "CI gate");

Failures throw LLMEvalAssertionException with score, metric, grounding, usage, and optional because context. SuiteResult is set when a suite pass-rate assert fails.

Filtering eval tests (traits)

[Fact]
[Trait(EvalTraits.Category, EvalTraits.LLMEval)]
[Trait(EvalTraits.Kind, EvalTraits.Direct)]
[Trait(EvalTraits.Tag, EvalTraits.Smoke)]
public async Task ExactMatch_ShouldPass() { ... }
dotnet test --filter "Category=LLMEval"
dotnet test --filter "Category=LLMEval&Tag=Smoke"

Same string constants work with MSTest [TestCategory(EvalTraits.LLMEval)] and NUnit [Category(EvalTraits.LLMEval)].

Fluent judge & grounding

using LLMEval;

// LLM-as-judge
var judgeResult = await Eval.Judge()
    .WithQuestion("What is the capital of France?")
    .WithResponse("Paris")
    .WithExpected("Paris")
    .WithProvider(ProviderType.OpenAI)
    .WithApiKey(Environment.GetEnvironmentVariable("OPENAI_API_KEY")!)
    .WithModel("gpt-4o-mini")
    .WithTemperature(0)
    .WithThreshold(0.8)
    .EvaluateAsync();

judgeResult.ShouldPass();

// Grounding / hallucination check
var grounding = await Eval.Grounding()
    .WithQuestion("Summarize the document.")
    .WithResponse("The report states X. It also says Y.")
    .WithExpected("Full reference document text...")
    .WithReferenceDocuments("Doc A...", "Doc B...") // optional; overrides expected as reference
    .WithProvider(ProviderType.Ollama)
    .WithEndpoint("http://localhost:11434")
    .WithModel("llama3.2")
    .WithThreshold(0.8)
    .EvaluateAsync();

grounding.ShouldBeGrounded();
// Also: grounding.GroundednessScore, grounding.HallucinationRate, grounding.Usage

Inject an existing service with .Using(evaluationService) or apply shared settings with .WithOptions(options).

Configuration (Options + DI)

using Microsoft.Extensions.DependencyInjection;
using LLMEval;

services.AddLLMEvalMetric<MyCustomMetric>(); // optional
services.AddLLMEval(o =>
{
    o.DefaultProvider = ProviderType.OpenAI;
    o.ApiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
    o.Model = "gpt-4o-mini";
    o.Temperature = "0";
    o.DefaultPassThreshold = 0.8;
    o.MaxDegreeOfParallelism = 4; // suite case parallelism
}, configureMetrics: registry =>
{
    // registry.Register(new MyCustomMetric());
});

var eval = serviceProvider.GetRequiredService<IEvaluationService>();

Store secrets in environment variables or user secrets — never commit API keys.

Provider configuration keys

Still supported on EvaluationRequest.Configuration:

Key Purpose
ApiKey Cloud provider API key
Model Model name or Azure deployment name
Temperature Sampling temperature (prefer "0" in CI)
ApiVersion Azure OpenAI API version (optional)
InputCostPer1M / OutputCostPer1M Optional USD per 1M tokens for EstimatedCostUsd

EvaluationRequest.ModelName is copied into Configuration["Model"] when Model is not set.

Core types

EvaluationRequest

  • Question, AiResponse, GoldenOutput, optional Schema
  • ProviderType: Ollama, OpenAI, Gemini, AzureOpenAI
  • Endpoint, Configuration, PassThreshold, ModelName
  • MatchingType: exact, keyword, semantic (TF-IDF), json, schema, relevance, grounded-heuristic, or any registered custom name
  • EvaluationType: DirectEvaluation, LLMAsJudge, GroundedAnswerCheck
  • IsReferenceDoc — treat GoldenOutput as a reference document for LLM-as-judge
  • ReferenceDocuments — optional multi-doc list for grounding (overrides GoldenOutput when set)

EvaluationResult

  • Score, IsPassed, Details, Confidence, MetricName
  • Grounding: UnsupportedStatements, PartiallySupportedStatements, RiskLevel, GroundednessScore, HallucinationRate
  • Usage — best-effort TokenUsage when the provider response includes usage metadata

Classic usage (fully supported)

using LLMEval;

IAiProviderFactory providerFactory = new AiProviderFactory();
IEvaluationService evalService = new AdvancedEvaluationService(providerFactory);

var request = new EvaluationRequest
{
    Question = "What is the capital of France?",
    AiResponse = "Paris, France",
    GoldenOutput = "Paris",
    ProviderType = ProviderType.OpenAI,
    Endpoint = "https://api.openai.com/v1/chat/completions",
    Configuration = new Dictionary<string, string>
    {
        ["ApiKey"] = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!,
        ["Model"] = "gpt-4o-mini",
        ["Temperature"] = "0"
    },
    PassThreshold = 0.8,
    EvaluationType = EvaluationType.LLMAsJudge,
    IsReferenceDoc = false
};

EvaluationResult result = await evalService.EvaluateAsync(request);
result.ShouldPass();

Azure OpenAI

var request = new EvaluationRequest
{
    Question = "What is the capital of France?",
    AiResponse = "Paris",
    GoldenOutput = "Paris",
    ProviderType = ProviderType.AzureOpenAI,
    Endpoint = "https://YOUR_RESOURCE.openai.azure.com",
    Configuration = new Dictionary<string, string>
    {
        ["ApiKey"] = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!,
        ["Model"] = "your-deployment-name",
        ["Temperature"] = "0"
        // optional: ["ApiVersion"] = "2024-02-15-preview"
    },
    PassThreshold = 0.8,
    EvaluationType = EvaluationType.LLMAsJudge
};

GroundedAnswerCheck

var request = new EvaluationRequest
{
    Question = "Summarize the document.",
    AiResponse = "The report states X. It also says Y and Z.",
    GoldenOutput = "Full reference document text...",
    // or: ReferenceDocuments = new[] { "Doc1...", "Doc2..." },
    ProviderType = ProviderType.Ollama,
    Endpoint = "http://localhost:11434",
    Configuration = new Dictionary<string, string>
    {
        ["Model"] = "llama3.2",
        ["Temperature"] = "0"
    },
    PassThreshold = 0.8,
    EvaluationType = EvaluationType.GroundedAnswerCheck
};

var result = await evalService.EvaluateAsync(request);
result.ShouldBeGrounded();

Suite + reports (JSON/HTML/Markdown/CSV)

var cases = await EvaluationSuite.LoadAsync("cases.json"); // also .jsonl / .csv
var smoke = cases.FilterByTags("smoke"); // optional tags on cases
var suite = new EvaluationSuite(evalService);
var report = await suite.RunAsync(smoke);
var outDir = ReportPaths.ResolveReportDirectory("./artifacts"); // honors LLMEVAL_REPORT_DIR
await suite.WriteReportsAsync(report, outDir); // report.json + .html + .md + .csv

report.ShouldMeetPassRate(0.9, because: "CI pass-rate threshold");

var diff = await BaselineComparer.CompareToBaselineFileAsync(report, "baseline-report.json");
if (diff.HasRegressions)
    throw new Exception(diff.ToSummary());

Dataset fields: id, question, actual, expected, evaluationType, matchingType, threshold, optional provider, endpoint, model, schema, isReferenceDoc, referenceDocuments, tags.

Formats: JSON array, JSONL, CSV (header row; tags as smoke;ci), or { "cases": [ ... ] }.

CI templates: see repo samples/ci (GitHub Actions + Azure DevOps) for pass-rate failure + report artifact publish.

Providers

Provider Endpoint Notes
OpenAI Optional (defaults to chat completions URL) ApiKey, Model
Azure OpenAI Resource root or full chat/completions URL Model = deployment name; optional ApiVersion
Gemini Required ApiKey on URL/query as implemented by provider
Ollama e.g. http://localhost:11434 Local; Model required

Notes

  • Prefer Temperature=0 for deterministic judge / grounding runs in CI.
  • Default semantic matching uses TF-IDF (not embeddings). GloveModel / SemanticSimilarityEvaluator are obsolete and not used by AdvancedEvaluationService.
  • Register custom DirectEvaluation metrics with MetricRegistry without forking core.
  • Repository: https://github.com/sooraj171/LLMEval
  • Changelog / migration: see repo CHANGELOG.md (v2.x keeps the classic EvaluateAsync API).
Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
3.3.1 332 10/1/2026
3.2.1 141 9/29/2026
3.1.0 179 8/26/2026
3.0.0 163 8/10/2026
2.2.0 140 8/7/2026
2.0.1 131 8/6/2026
2.0.0 139 8/6/2026
1.5.0 152 6/6/2026
1.4.0 148 5/6/2026
1.3.0 157 2/7/2026
1.1.0 279 6/25/2025
1.0.2 290 5/28/2025
1.0.1 342 5/15/2025
1.0.0 347 5/14/2025

STAF.LLMEval 2.2.0 — Test Framework & CI Reporting

- Richer assertion messages (metric, grounding, usage, optional because) + ShouldMeetPassRate for suite CI gates
- EvalTraits constants for xUnit/MSTest/NUnit filtering (Category / Kind / Tag)
- Suite case tags + FilterByTags; CSV tags column
- ReportPaths.LLMEVAL_REPORT_DIR for CI artifact directories
- Official GitHub Actions + Azure DevOps sample pipelines with pass-rate fail + report artifacts
- No separate MSTest/xUnit/NUnit packages — main-package asserts remain framework-agnostic

See https://github.com/sooraj171/LLMEval/blob/main/CHANGELOG.md