llm-drift-bench
Catch silent regressions before you swap, update, or quantize your LLM.
Lightweight, deterministic CLI and Python library for offline LLM drift detection, JSON Schema conformity, multi-candidate ranking, statistical significance testing, and agent tool-trace auditing.
Quickstart · Capabilities · Workflows · CLI Reference · Python API · CI/CD · Examples · Architecture
See it in 18 seconds
Watch MP4 · Static Preview · Sample HTML Report · Demo Fixtures
Edited from real CLI JSON outputs on handwritten fixtures in examples/ (not real model captures or runtime benchmarks). Silent — no audio required.
Why llm-drift-bench?
A quantized checkpoint (e.g. FP16 -> INT4/Q4_K_M), model version bump, or prompt edit can keep returning syntactically valid JSON while quietly dropping a required field, shifting an invoice total, flipping a classification label, or regressing P95 latency.
llm-drift-bench compares captured baseline and candidate responses by prompt_id completely offline — no LLM judge API calls, no embedding downloads, and no GPU required. Core models are pure stdlib dataclasses with PEP 562 lazy loading (~8 ms package import; canonical runs never eagerly import Pydantic or Rich).
flowchart LR
A["Capture or export<br/>baseline & candidate JSONL"] --> B["Bootstrap<br/>infer-schema & calibrate"]
B --> C["Evaluate<br/>run --config drift.toml"]
C --> D{"Gates pass?"}
D -->|Pass / Fail| E["Inspect & Decide<br/>diagnose · compare-reports · stats"]
E --> F["Ship & Track<br/>PR comment · HTML diffs · JUnit · history"]
Capabilities
| Capability | Status (0.3.0) |
Highlights |
|---|---|---|
| JSON & Schema Conformity | Available | Strict extraction (direct, fenced, prose), duplicate-key & NaN/Inf rejection, safe bounded regex subset |
| Composite Drift & Policies | Available | Token Jaccard, n-gram Dice, exact Levenshtein, JSON structure/field/numeric drift, drift.toml weights & per-field/wildcard [*] rules (ignore, unordered_array, tolerance_abs/tolerance_rel) |
| Semantic Field Diffs | Available | diff CLI inspects exact JSON field additions/removals/type shifts/numeric deltas or unified text diffs while respecting drift.toml rules |
| Zero-Setup Onboarding | Available | infer-schema generates strict JSON Schemas; calibrate auto-tunes drift.toml & collapses volatile arrays to [*]; doctor runs pre-flight checks |
| Endpoint Capture Collector | Available | Zero-dependency OpenAI-compatible collector (Ollama, vLLM, llama.cpp, OpenAI) with --concurrency, --runs, --json-mode, --resume, --header, bounded retries |
| Multi-Candidate Ranking | Available | compare-many & compare-reports with --sort-by, --against, --hotspots, --inspect-prompt, Rich tables & SVG Pareto frontier HTML |
| Statistical Rigor | Available | stats with deterministic bootstrap CIs, flaky-prompt detection, paired permutation tests (with Cohen's d), and exact two-sided McNemar conformity tests |
| Drift History & Trends | Available | Append-only JSONL ledger (history record|show|check) with moving-window regression alerts, --candidate/--tag filters, sparklines & SVG trend HTML |
| Agent Tool-Trace Audits | Available | check-tools --adapter normalized|openai|anthropic|otel (OpenAI Responses + OTLP resourceSpans), --max-failed-calls retry budgets, & secret-leak checks |
| Pluggable Scorers | Available | score CLI + pure-stdlib char_ngram_cosine, json_key_jaccard, markdown_structure, python_ast, tfidf_cosine + llm_drift_bench.scorers entry points |
| CI-Native Exports | Available | Table, Rich, JSON, CSV, SARIF 2.1.0, Markdown, GitHub PR comments (--previous deltas), offline HTML (--include-diffs), JUnit XML, --github-summary |
Quickstart
Requires Python 3.10+. Install the latest published release from PyPI or install this checkout in editable mode:
# Option A: Install from PyPI
pip install llm-drift-bench
# Option B: Install from source
git clone https://github.com/anant-goel/llm-drift-bench.git
cd llm-drift-bench
python -m venv .venv
.venv/bin/python -m pip install -e . # Windows PowerShell: .\.venv\Scripts\python.exe -m pip install -e .
Run the bundled offline demo (exit 0 on pass, exit 1 on drift):
# 1. Passing comparison (exit 0)
python -m llm_drift_bench run \
-b examples/baseline.jsonl \
-c examples/candidate-pass.jsonl \
-s examples/extraction-suite.json
# 2. Catch a regression and save the report (exit 1)
python -m llm_drift_bench run \
-b examples/baseline.jsonl \
-c examples/candidate-drift.jsonl \
-s examples/extraction-suite.json \
-o drift-report.json
# 3. Explain exactly why it failed & inspect exact field-level diffs (exit 0)
python -m llm_drift_bench diagnose -i drift-report.json
python -m llm_drift_bench diff -b examples/baseline.jsonl -c examples/candidate-drift.jsonl --only-changed
Preview actual terminal output (failing run + diagnose)
==============================================================================
LLM DRIFT BENCHMARK REPORT [FAILED]
==============================================================================
Baseline Model : demo-reference
Candidate Model : demo-candidate-drift
Total Samples : 2 (Drifted: 2 / 100.0%)
------------------------------------------------------------------------------
Metric | Baseline | Candidate / Value
------------------------------------------------------------------------------
JSON Conformity Rate | 100.0% | 50.0%
Mean Composite Drift | 0.0000 (ref) | 0.6694
Max Composite Drift | 0.0000 (ref) | 0.9597
Mean Token Jaccard Similarity | 1.0000 (ref) | 0.5238
Mean Levenshtein Similarity | 1.0000 (ref) | 0.5142
Mean JSON Structural Similarity | 1.0000 (ref) | 0.5000
Mean JSON Numeric Relative Drift | 0.0000 (ref) | 0.4444
P50 Latency (ms) | n/a | n/a
P95 Latency (ms) | n/a | n/a
Latency regression check: n/a (incomplete measurements).
------------------------------------------------------------------------------
Prompt ID | Category | JSON OK | Struct Sim | Drift | State
------------------------------------------------------------------------------
invoice-01 | extraction | YES | 1.0000 | 0.3791 | DRIFT
ticket-01 | classification | NO | 0.0000 | 0.9597 | DRIFT
==============================================================================
Threshold Violations:
- 2 of 2 samples failed individual drift checks.
- Mean composite drift (0.6694) exceeded threshold (0.2500).
- Candidate JSON conformity rate (50.00%) fell below minimum (95.00%).
- Mean numeric relative drift (0.4444) exceeded threshold (0.1500).
==============================================================================
Benchmark FAILED
[schema] ticket-01: $.priority: required
Try: Restore the required field in the extraction prompt or output mapping.
[numeric_change] invoice-01: Shared numeric fields have relative drift 0.4444.
Try: Compare units, decimal placement and rounding against the source record.
Core Workflows
1. Zero-Setup Onboarding (infer-schema & calibrate)
Skip writing JSON Schemas and guessing thresholds by hand:
# Auto-infer a strict prompts.json schema suite from captured baseline JSON outputs
python -m llm_drift_bench infer-schema -i examples/baseline.jsonl -o inferred-prompts.json --strict-additional
# Validate captures immediately against the inferred schema
python -m llm_drift_bench validate -i examples/baseline.jsonl -p inferred-prompts.json --strict
# Auto-calibrate drift.toml (thresholds + ignore rules for volatile fields like $.timestamp)
python -m llm_drift_bench calibrate --baseline-a baseline-run1.jsonl --baseline-b baseline-run2.jsonl -o drift.toml
2. Task-Specific drift.toml Policies
Customize metric weights, ignore volatile fields, compare order-insensitive arrays, set absolute/relative numeric tolerances, or handle >16,384-char responses (see examples/drift.toml):
long_text_mode = "skip_levenshtein" # or "error" (default)
[thresholds]
max_composite_drift = 0.20
min_json_conformity_rate = 0.98
max_numeric_relative_drift = 0.05
max_latency_regression_pct = 35.0
[fields."$.items[*].timestamp"]
ignore = true
[fields."$.tags"]
unordered_array = true
[fields."$.confidence"]
tolerance_abs = 0.03
python -m llm_drift_bench run \
-b examples/baseline.jsonl -c examples/candidate-pass.jsonl \
-s examples/extraction-suite.json --config examples/drift.toml
# Inspect only semantic changes not suppressed by drift.toml
python -m llm_drift_bench diff \
-b examples/baseline.jsonl -c examples/candidate-drift.jsonl \
--config examples/drift.toml --only-changed
3. Capture Reproducible Outputs (capture)
Collect deterministic JSONL captures directly from any OpenAI-compatible endpoint (Ollama, vLLM, llama.cpp server, OpenAI) with bounded concurrency, multi-run repeats, JSON mode, crash-resilient --resume checkpointing, custom gateway --header flags, explicit timeouts, bounded retries, and env-var secret handling:
python -m llm_drift_bench capture \
-s examples/extraction-suite.json \
--endpoint http://localhost:11434/v1 \
--model llama3:8b-q4_K_M \
--seed 42 --concurrency 4 --runs 3 --json-mode --resume \
--header "X-Title: DriftBench" \
-o candidate.jsonl
4. Multi-Candidate Ranking & Visual Reports
Compare multiple quantizations or prompts side-by-side, inspect hotspots, gate on newly regressed prompts, and export zero-JS offline HTML dashboards or compact GitHub PR comments:
# Evaluate multiple captures against one baseline and flag regressions vs a reference candidate
python -m llm_drift_bench compare-many \
-b examples/baseline.jsonl -s examples/extraction-suite.json \
-c q8 examples/candidate-pass.jsonl \
-c q4 examples/candidate-drift.jsonl \
--against q8 --hotspots 5 --format rich --html-output comparison.html
# Rank saved reports with an inline SVG Pareto frontier dashboard
python -m llm_drift_bench compare-reports examples/expected-pass.json examples/expected-drift.json \
--sort-by passed --by-category --rule-summary --numeric-changes 5 --html-output pareto.html
# Export a compact GitHub PR comment with deltas vs a previous run
python -m llm_drift_bench report -i examples/expected-drift.json \
--format pr-comment --previous examples/expected-pass.json
# Export a standalone offline HTML report with collapsible side-by-side JSON field diffs
python -m llm_drift_bench run \
-b examples/baseline.jsonl -c examples/candidate-drift.jsonl \
-s examples/extraction-suite.json --format html --include-diffs --no-fail-on-drift > report.html
5. Statistical Significance & Drift History (stats & history)
Distinguish real regressions from sampling variance and track model quality across releases:
# Bootstrap CIs, flaky prompt detection, paired permutation & exact McNemar conformity tests
python -m llm_drift_bench stats run1.json run2.json run3.json \
--compare-against baseline-ref.json --confidence 0.95
# Append runs to an audit ledger, render trends, and gate on gradual degradation
python -m llm_drift_bench history record --ledger drift-history.jsonl -i examples/expected-pass.json --tag q8 --git-sha abc1234
python -m llm_drift_bench history show --ledger drift-history.jsonl --candidate demo-candidate-pass --format text
python -m llm_drift_bench history show --ledger drift-history.jsonl --format html -o trends.html
python -m llm_drift_bench history check --ledger drift-history.jsonl --window 3 --max-drift-increase 0.05
6. Offline Agent Tool-Trace Audits (check-tools)
Verify that an agent read required content before editing — directly on normalized traces, OpenAI Chat/Responses transcripts, Anthropic/Claude tool_use/tool_result logs, or OpenTelemetry GenAI spans — and optionally attach the saved evidence to reports with --tool-check (never alters the drift verdict):
python -m llm_drift_bench check-tools \
-i transcript.json --adapter openai \
--resource src/app.py@v1 --start 0 --end 500 --trace-complete \
-o tool-check.json
Exit codes for check-tools: 0 PASS, 1 FAIL, 3 UNKNOWN (incomplete/insufficient evidence — never treated as PASS), 2 input error. See docs/tool-events.md for the full schema and Python workflow checks (check_max_tool_retries, check_no_secret_in_tool_args).
CLI Reference
Run python -m llm_drift_bench <command> --help for full options on any command.
| Command | Purpose |
|---|---|
run |
Compare baseline and candidate captures (--config, --category, --long-text-mode, --include-diffs, --format, --junit-output, --sarif-output, --github-summary) |
diff |
Show policy-aware JSON field-level or unified text diffs between two captures (--only-changed, --prompt-id, --format json) |
score |
Run pluggable scorers (char_ngram_cosine, json_key_jaccard, markdown_structure, python_ast, tfidf_cosine, or entry-point plugins; --list-scorers) |
validate |
Validate captures for JSON syntax and JSON Schema conformity (--category, --strict) |
report |
Render a saved report as markdown, console/table, json, csv, sarif, html, junit, or pr-comment (--previous, --tool-check) |
diagnose |
Explain why a saved comparison failed (--scope, --kind, --prompt-id, optional local OpenVINO --ai-model) |
compare-many |
Evaluate 2+ labeled candidate captures against one baseline (--sort-by, --against, --hotspots, --format rich, --html-output) |
compare-reports |
Rank saved candidate reports and export SVG Pareto frontier dashboards |
check-tools |
Offline read-before-edit & --max-failed-calls checks on normalized, OpenAI, Anthropic, or OTel traces (--adapter) |
stats |
Multi-run bootstrap CIs, flaky-prompt detection, paired permutation (with Cohen's d), and exact two-sided McNemar tests |
history |
Record reports (record), inspect sparklines/SVG trends (show), and gate on moving-window regressions (check) |
capture |
Capture reproducible JSONL outputs from OpenAI-compatible endpoints (--concurrency, --runs, --json-mode, --resume, --header) |
infer-schema |
Auto-infer a supported-subset JSON Schema prompt suite from baseline captures |
calibrate |
Auto-calibrate drift.toml thresholds and detect/collapse volatile JSON fields from baseline noise runs |
init-sample |
Scaffold starter prompt, baseline, and candidate datasets (--with-policy adds drift.toml) |
doctor |
Pre-flight check for environment, drift.toml policies, suite schemas/regex safety, and capture ID alignment |
ai-devices |
List devices visible to the optional local OpenVINO runtime |
Standard exit codes: 0 passed / succeeded · 1 drift or threshold failure (suppressible via --no-fail-on-drift, report still records failure) · 2 usage or input error · 3 (check-tools only) UNKNOWN.
Python API & Pluggable Scorers
Automated Regression Test Gate (pytest / unittest)
assert_no_drift(report) enforces the canonical engine verdict and prints suite failure reasons plus up to 5 failing prompt IDs without leaking raw captured responses:
from pathlib import Path
from llm_drift_bench import (
DriftBenchmarkEngine,
assert_no_drift,
load_model_samples,
load_policy,
load_prompt_cases,
)
def test_quantized_candidate_does_not_regress() -> None:
fixtures = Path("examples")
engine = DriftBenchmarkEngine(policy=load_policy(fixtures / "drift.toml"))
report = engine.evaluate(
baseline_samples=load_model_samples(fixtures / "baseline.jsonl"),
candidate_samples=load_model_samples(fixtures / "candidate-pass.jsonl"),
prompt_cases=load_prompt_cases(fixtures / "extraction-suite.json"),
)
assert_no_drift(report)
Pluggable Scorers (scorers.py)
Use built-in zero-dependency scorers or register your own (third-party packages are also auto-discovered via the llm_drift_bench.scorers entry-point group):
from llm_drift_bench import (
char_ngram_cosine_similarity,
get_scorer,
list_scorers,
python_ast_similarity,
register_scorer,
tfidf_cosine_similarity,
)
print(list_scorers()) # ['char_ngram_cosine', 'json_key_jaccard', 'markdown_structure', 'python_ast', 'tfidf_cosine']
# Identifier-invariant structural similarity for generated Python code
assert python_ast_similarity("def add(x, y): return x + y", "def sum2(a, b): return a + b") == 1.0
# Pure-stdlib character n-gram & TF-IDF cosine scorers
res = get_scorer("tfidf_cosine").score("invoice total 100 usd", "invoice total 100 dollars")
print(res.similarity, res.available)
CI/CD Integration
Drop llm-drift-bench directly into GitHub Actions with JUnit test reporting, native Job Summaries, and PR comment output:
- name: Run LLM drift regression gate
run: |
llm-drift-bench run \
-b benchmarks/baseline.jsonl \
-c benchmarks/candidate.jsonl \
-s benchmarks/prompts.json \
--config drift.toml \
-o drift-report.json \
--junit-output junit.xml \
--sarif-output drift.sarif \
--github-summary
- name: Render PR comment (even on failure)
if: always()
run: |
llm-drift-bench report -i drift-report.json --format pr-comment -o pr-comment.md
Reference Details
Input capture & prompt suite formats
Capture files (.jsonl or .json) — Each record requires a unique, non-empty prompt_id and a string output. Structured values must be JSON-serialized strings (json.dumps), never raw objects or null. Optional latency_ms and tokens_generated are preserved as null when missing (never estimated).
{"prompt_id": "invoice-01", "model_name": "llama-3-8b-fp16", "latency_ms": 142.5, "output": "{\"total\": 100.0}"}
Prompt suite (.json or .jsonl) — Associates each prompt_id with a prompt, optional category, and optional schema:
[
{
"prompt_id": "invoice-01",
"category": "extraction",
"prompt": "Extract the invoice total.",
"schema": {
"type": "object",
"required": ["total"],
"properties": { "total": { "type": "number", "minimum": 0 } }
}
}
]
Baseline, candidate, and any supplied suite must share identical prompt ID sets (no silent drops or duplicate IDs). Unsupported JSON Schema keywords fail explicitly — see docs/current-limitations.md.
Default drift thresholds & failure semantics
Flag / drift.toml Key |
Default | Meaning |
|---|---|---|
--max-drift / max_composite_drift |
0.25 |
Max composite drift per prompt and suite mean |
--min-conformity / min_json_conformity_rate |
0.95 |
Min candidate JSON Schema conformity rate |
--max-numeric-drift / max_numeric_relative_drift |
0.15 |
Max relative drift on shared numeric JSON fields |
--max-latency-regression / max_latency_regression_pct |
50.0% |
Max P95 latency increase (skipped if timings incomplete) |
A failed individual sample fails the suite even when aggregate means stay under threshold.
Optional extras (local OpenVINO AI advisor & Opik adapter)
- Local OpenVINO advisor (
pip install "llm-drift-bench[ai]"): Prioritize diagnostic next steps offline using a local exported OpenVINO GenAI model directory without sending raw captured outputs or prompt IDs to the model:llm-drift-bench ai-devices llm-drift-bench diagnose -i drift-report.json --ai-model /path/to/openvino-model --device CPU
- Opik integration (
pip install "llm-drift-bench[opik]"): ExportEvidenceScoreverdicts viascore.to_opik()while keeping unavailable evidence explicit.
Documentation & Community
- Examples & Hands-On Playground — Reproducible offline fixtures,
drift.toml, and Python batch examples - Architecture — Module map, lazy-loading design, scoring formulas, and schema subset
- Workflow Recipes — Quantization, JSON extraction, RAG, and agent evaluation boundaries
- Tool-Event Checks — Normalized trace format, vendor adapters, and PASS/FAIL/UNKNOWN semantics
- Current Limitations — Schema subset, regex safety policy, and size caps
- Roadmap · Migration Guide (0.2) · Publishing · Changelog
- Contributing · MIT License
Metadata
Release files for llm-drift-bench 0.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| llm_drift_bench-0.3.0.tar.gz | 1.6 MB | With provenance | Details for llm_drift_bench-0.3.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| llm_drift_bench-0.3.0-py3-none-any.whl | Python 3 | none | any | Details for llm_drift_bench-0.3.0-py3-none-any.whl |
Total release size: 1.8 MB
Release files / llm_drift_bench-0.3.0.tar.gz
| Download URL | llm_drift_bench-0.3.0.tar.gz |
|---|---|
| Size | 1.6 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d5b1a2bb1b8f2d17fe247cb4f7f4c4c2724602f4f82f119b65e5f211df5f394f
|
|
BLAKE2b-256 checksum How to use checksums |
011e618efadcf91f681eb559b149c86636f8f93476f5b55d3fe3945dc3df82f4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.
Transparency logRelease files / llm_drift_bench-0.3.0-py3-none-any.whl
| Download URL | llm_drift_bench-0.3.0-py3-none-any.whl |
|---|---|
| Size | 128.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
722a7fc90cf4757c4243adeabdc414e806f1a905a27998c25e210a3cae774f8c
|
|
BLAKE2b-256 checksum How to use checksums |
bb1d63a3f6cb8c94657354b88339a1b22193fe4188ab68a90a53415183202773
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.
Transparency logSecurity for llm-drift-bench 0.3.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for llm_drift_bench-0.3.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.