STAF.LLMEval
3.3.1
dotnet add package STAF.LLMEval --version 3.3.1
NuGet\Install-Package STAF.LLMEval -Version 3.3.1
<PackageReference Include="STAF.LLMEval" Version="3.3.1" />
<PackageVersion Include="STAF.LLMEval" Version="3.3.1" />
<PackageReference Include="STAF.LLMEval" />
paket add STAF.LLMEval --version 3.3.1
#r "nuget: STAF.LLMEval, 3.3.1"
#:package STAF.LLMEval@3.3.1
#addin nuget:?package=STAF.LLMEval&version=3.3.1
#tool nuget:?package=STAF.LLMEval&version=3.3.1
STAF.LLMEval
Testing non-deterministic LLM output with brittle string-equality asserts does not scale. STAF.LLMEval gives you pluggable metrics, LLM-as-judge, and RAG groundedness checks that run in CI.
Package: STAF.LLMEval · Version: 3.3.1 · Targets: net8.0, net9.0, net10.0 · License: MIT
This package contains the evaluation assemblies (LLMEval.dll, LLMEval.Core.dll, LLMEval.Abstractions.dll). Install it alone.
Score outputs with pluggable metrics (exact, keyword, TF-IDF or embeddings 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, opt-in run-history HTML trends, and HTML/JSON/Markdown/CSV reports. Works with ChatGPT, GPT, Gemini, Ollama, Azure OpenAI, Claude, Groq, and Mistral.
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; unchanged
await Eval.Direct().SemanticEmbedding(actual, expected).WithProvider(EmbeddingProviderType.OpenAI).WithApiKey(apiKey).WithModel("text-embedding-3-small").WithThreshold(0.85).EvaluateAsync();
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) |
EmbeddingModel / EmbeddingDeployment |
Embeddings model or Azure embeddings deployment (embedding-semantic) |
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, optionalSchemaProviderType:Ollama,OpenAI,Gemini,AzureOpenAI,Claude,Groq,MistralEndpoint,Configuration,PassThreshold,ModelNameMatchingType:exact,keyword,semantic(TF-IDF),semantic-embedding,embedding-semantic,json,schema,relevance,grounded-heuristic, or any registered custom nameEvaluationType:DirectEvaluation,LLMAsJudge,GroundedAnswerCheckIsReferenceDoc— treatGoldenOutputas a reference document for LLM-as-judgeReferenceDocuments— optional multi-doc list for grounding (overridesGoldenOutputwhen set)
EvaluationResult
Score,IsPassed,Details,Confidence,MetricName- Grounding:
UnsupportedStatements,PartiallySupportedStatements,RiskLevel,GroundednessScore,HallucinationRate Usage— best-effortTokenUsagewhen 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.html uses the STAF HtmlResult skin (same visual language as STAF.Playwright)
// Opt-in: JSONL history + pass-rate sparkline on report.html (off by default)
var suiteWithHistory = new EvaluationSuite(evalService, new LLMEvalOptions { EnableRunHistory = true });
await suiteWithHistory.WriteReportsAsync(report, outDir);
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.
Zero-key sample: repo samples/QuickStart. Live judge sample: samples/OpenAIJudge (set OPENAI_API_KEY).
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 |
| Claude | Optional (https://api.anthropic.com/v1/messages) |
ApiKey, Model; optional ApiVersion, MaxTokens |
| Groq | Optional (https://api.groq.com/openai/v1/chat/completions) |
OpenAI-compatible; ApiKey, Model |
| Mistral | Optional (https://api.mistral.ai/v1/chat/completions) |
OpenAI-compatible; ApiKey, Model |
Optional: STAF.LLMEval.SemanticKernel — AddLLMEvalSemanticKernel() uses Kernel chat completion for judge/grounding.
ASP.NET / host config: services.AddLLMEval(configuration) binds the LLMEval section.
Release notes — 3.3.1
STAF.LLMEvalcontains the Core and Abstractions assemblies.dotnet add package STAF.LLMEvalis the only install- Optional Semantic Kernel package depends on
STAF.LLMEval3.3.1
Release notes — 3.3.0
- README leads with the evaluation problem, then install
- Opt-in embeddings:
Eval.Direct().SemanticEmbedding(...)/MatchingType = semantic-embedding(embedding-semanticstill works). TF-IDFsemanticis unchanged - A missing embedding provider throws
LLMEvalConfigurationException(no TF-IDF fallback, no score of 0) - DI:
services.AddSingleton<IEmbeddingProvider, T>()is picked up byAddLLMEval - NuGet package icon
Release notes — 3.2.1
- Dependency refresh: Microsoft.Extensions 10.0.12, Semantic Kernel 1.80.1, SourceLink 10.0.401
- Docs: embeddings, opt-in run history, QuickStart / OpenAIJudge samples
- No API breaks vs 3.2.0
Release notes — 3.2.0
- Embeddings:
Eval.Direct().EmbeddingSemantic(...)/MatchingType = embedding-semantic(OpenAI/Azure orIEmbeddingProvider). TF-IDFsemanticunchanged - Run history (opt-in):
LLMEvalOptions.EnableRunHistory→ JSONL + HTML pass-rate sparkline - Samples:
samples/QuickStart(no keys),samples/OpenAIJudge(OPENAI_API_KEY) - No API breaks vs 3.1.0
Release notes — 3.1.0
- Community: CONTRIBUTING.md, Discussions guidance, best practices / performance docs, blog outline
- Benchmarks:
benchmarks/LLMEval.Benchmarks+ CI smoke - NuGet metadata/tags refreshed — no API breaks vs 3.0.0
Release notes — 3.0.0
- Multi-package:
STAF.LLMEvalmeta →Core+Abstractions(type forwards); still one-line install - Providers: Anthropic Claude, Groq, Mistral (+ OpenAI / Azure / Gemini / Ollama)
- Optional:
STAF.LLMEval.SemanticKernelfor Semantic Kernel chat completion - ASP.NET / Aspire-friendly:
services.AddLLMEval(configuration)binds sectionLLMEval - Migration: docs/MIGRATION-v3.md · packages: docs/PACKAGES.md
Release notes — 2.2.0
- Richer asserts: metric / grounding / usage in failure messages; optional
because:;ShouldMeetPassRatefor suite CI gates EvalTraits+ suite case tags /FilterByTagsfor CI filteringLLMEVAL_REPORT_DIR/ReportPathsfor 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, embedding-semantic, 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
Notes
- Prefer
Temperature=0for deterministic judge / grounding runs in CI. MatchingType = semanticis TF-IDF (no API key).semantic-embeddingis the embeddings opt-in and requires a provider (embedding-semanticis the same metric).GloveModel/SemanticSimilarityEvaluatorare obsolete and not used byAdvancedEvaluationService.- Register custom DirectEvaluation metrics with
MetricRegistrywithout forking core. - Repository: https://github.com/sooraj171/LLMEval
- Changelog / migration: see repo
CHANGELOG.mdanddocs/MIGRATION-v3.md(classicEvaluateAsyncAPI retained).
| Product | Versions 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. |
-
net10.0
- Microsoft.Extensions.Configuration.Abstractions (>= 10.0.12)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 10.0.12)
- Microsoft.Extensions.Http (>= 10.0.12)
- Microsoft.Extensions.Options (>= 10.0.12)
- Microsoft.Extensions.Options.ConfigurationExtensions (>= 10.0.12)
-
net8.0
- Microsoft.Extensions.Configuration.Abstractions (>= 10.0.12)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 10.0.12)
- Microsoft.Extensions.Http (>= 10.0.12)
- Microsoft.Extensions.Options (>= 10.0.12)
- Microsoft.Extensions.Options.ConfigurationExtensions (>= 10.0.12)
-
net9.0
- Microsoft.Extensions.Configuration.Abstractions (>= 10.0.12)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 10.0.12)
- Microsoft.Extensions.Http (>= 10.0.12)
- Microsoft.Extensions.Options (>= 10.0.12)
- Microsoft.Extensions.Options.ConfigurationExtensions (>= 10.0.12)
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 3.3.1 — One package contains the evaluation assemblies
- LLMEval.Core and LLMEval.Abstractions ship inside this nupkg
- Install with: dotnet add package STAF.LLMEval
- 3.3.0 content: SemanticEmbedding opt-in, configuration failures throw, NuGet icon
See https://github.com/sooraj171/LLMEval/blob/main/CHANGELOG.md