Skip to main content

ragnarok-ai logo

Local-first RAG evaluation framework for LLM applications

Evaluate, benchmark, and monitor your RAG pipelines — 100% locally, no API keys required.

PyPI CI Python 3.10+ License: AGPL-3.0 Ruff Type Checked: mypy Open In Colab Open in Spaces Hugging Face: ragnarok-ai

Problem • Solution • Quick Start • Installation • Roadmap


The Problem

Building RAG systems is easy. Knowing if they actually work is hard.

A pipeline can have a good retriever but a bad generator, great faithfulness but poor relevance, or a beautiful score that quietly degrades in production. And when the answer matters — medical, legal, internal data — you often can't send your documents to an external API just to evaluate them.

ragnarok-ai is designed from the ground up for local, private, reproducible RAG evaluation:

  • Runs 100% locally (Ollama, local models) — your data never leaves your machine
  • Pins the judge's sampling options (temperature 0, fixed seed, explicit 8192-token context window) and warns when Ollama probably truncated a prompt — the same inputs give the same judgment on the same machine and Ollama version
  • Checkpoints long batch evaluations — after a crash, resume: every query already evaluated is restored, only the rest is recomputed
  • Tells you why quality is low (root-cause diagnosis), not just that it is
  • Lets you calibrate the judge against your own labels — trust the scores, or know you can't
  • Gates your CI, monitors production, detects drift, A/B tests configurations
  • Integrates with your existing stack (LangChain, LangGraph, LlamaIndex...)

The Solution

ragnarok-ai is a lightweight, local-first framework to evaluate RAG pipelines.

RAGnarok-AI Overview

from ragnarok_ai import evaluate
from ragnarok_ai.core.types import Query, TestSet
from ragnarok_ai.reporters import HTMLReporter

# A test set: questions with the documents that should be retrieved
# (or generate one from your knowledge base: `ragnarok generate --docs ./docs/`)
testset = TestSet(
    queries=[
        Query(text="Who created Python?", ground_truth_docs=["doc_python"]),
        Query(text="When was Python first released?", ground_truth_docs=["doc_python"]),
    ]
)

# Evaluate your RAG pipeline: any object with `async def query(question) -> RAGResponse`
results = await evaluate(my_rag, testset)

print(results.summary())
# {'num_queries': 2, 'precision': ..., 'recall': ..., 'mrr': ..., 'ndcg': ...}

# Per-query details: answer, metrics, retrieved documents, latency, error
for qr in results.query_results:
    print(qr.query.text, qr.metric.recall, qr.retrieved_doc_ids)

# Interactive HTML report with per-query drill-down
HTMLReporter().report_to_file(
    [(qr.query.text, qr.metric, None) for qr in results.query_results],
    "report.html",
)

Generation quality (faithfulness, relevance, hallucination, completeness) is scored by a local LLM-as-Judge.


Key Features

Feature Description
100% Local Runs entirely on your machine with Ollama. No OpenAI, no API keys, no data leaving your network.
Production Monitoring Collect traces, export Prometheus metrics, track latency and success rates in production.
Production Intelligence Drift detection against a recorded baseline, live A/B testing, root-cause diagnosis of failures.
LLM-as-Judge Multi-criteria evaluation with Prometheus 2: faithfulness, relevance, hallucination, completeness — with calibration against your own labels (kappa, error rates, threshold tuning).
Cost Tracking Track token usage and costs. Local models = $0.00, see exactly what cloud APIs cost.
Jupyter Integration Rich HTML display in notebooks with metrics visualization.
Fast & Resilient Parallel evaluation, result caching, timeouts and retries. BatchEvaluator checkpoints every evaluated query — after a crash, resume restores their results and recomputes only the rest.
Framework Agnostic Works with LangChain, LangGraph, LlamaIndex, or your custom RAG.
Comprehensive Metrics Retrieval quality, faithfulness, relevance, hallucination detection, latency tracking.
Test Generation Auto-generate diverse test sets from your knowledge base — or mine them from real production traffic.
CI/CD Ready CLI-first design, JSON output, exit codes for pipeline integration.
Enterprise Ready Kubernetes Helm charts, air-gapped deployment, data sovereignty.
Lightweight Minimal dependencies. No torch/transformers in core.

Design Principles

ragnarok-ai is built around a small set of guarantees:

Principle What it means in practice
Local-first, always Every feature works with local models (Ollama). No API key is ever required. Air-gapped deployment is a first-class target.
Your data stays yours Nothing leaves your machine. Production traces hash queries by default; capturing text is opt-in and PII-scrubbed client-side.
Resumable by design Long local evaluations crash. BatchEvaluator checkpoints every evaluated query, so a resumed run restores their results and recomputes only the rest, whatever the batch size.
Trust is measured, not assumed Judge calibration quantifies agreement with your labels (kappa, error rates, threshold tuning) instead of asking you to believe a score. The recommended threshold is reported both in-sample and out-of-sample (cross-validation with a bootstrap interval, fixed seeds), next to the prevalence of your labels and the agreement a constant majority-class judge would get.
Engineering tool, not a notebook CLI-first, JSON output, exit codes, --fail-under CI gates, regression detection, Prometheus export, Helm chart.
Lightweight core No torch/transformers in the core. Statistics are hand-rolled over the standard library.

Performance

Benchmarked on Apple M2 16GB, Python 3.10 (RAGnarok-AI v1.4.0):

Retrieval Metrics: ~24,000 queries/sec

Queries Time Peak RAM
50 0.002s 0.02 MB
500 0.021s 0.03 MB
5000 0.217s 0.17 MB

LLM-as-Judge (Prometheus 2):

Criterion Avg Time
Faithfulness ~25s
Relevance ~22s
Hallucination ~28s

Retrieval is pure computation — instant. LLM-as-Judge is the bottleneck (~25s/eval), but runs 100% local.

Full benchmarks →


Quick Start

Try it now: Open in Google Colab

Prerequisites

  • Python 3.10+
  • Ollama running locally
  • uv (recommended) or pip

Install

pip install ragnarok-ai

With optional dependencies:

pip install ragnarok-ai[ollama,qdrant]

Run your first evaluation

# CLI demo
ragnarok evaluate --demo

# With options
ragnarok evaluate --demo --output results.json --fail-under 0.7

# Or in Python, against your own pipeline
python examples/custom_rag_adapter.py

Installation

Using pip

pip install ragnarok-ai

Optional dependencies

# LLM providers
pip install ragnarok-ai[ollama]      # Ollama support
pip install ragnarok-ai[openai]      # OpenAI support
pip install ragnarok-ai[anthropic]   # Anthropic support

# Vector stores
pip install ragnarok-ai[qdrant]      # Qdrant support
pip install ragnarok-ai[chroma]      # ChromaDB support
pip install ragnarok-ai[faiss]       # FAISS support

# RAG frameworks
pip install ragnarok-ai[langchain]   # LangChain/LangGraph support
pip install ragnarok-ai[llamaindex]  # LlamaIndex support
pip install ragnarok-ai[dspy]        # DSPy support

# Observability
pip install ragnarok-ai[telemetry]   # OpenTelemetry tracing

# Everything
pip install ragnarok-ai[all]

Development

git clone https://github.com/2501Pr0ject/RAGnarok-AI.git
cd RAGnarok-AI
pip install -e ".[dev]"
pre-commit install

Use Cases

Continuous RAG Testing in CI/CD

# .github/workflows/rag-tests.yml
- uses: 2501Pr0ject/ragnarok-evaluate-action@v1
  with:
    config: ragnarok.yaml
    threshold: 0.8
    # fail-on-threshold: false (default - advisory only)
    # comment-on-pr: true (default - posts PR comment)

The action posts a PR comment distinguishing deterministic retrieval metrics from advisory LLM-as-Judge scores.

Compare Embedding Models

from ragnarok_ai import compare

# create_rag(config) builds your pipeline from a config dict
comparison = await compare(
    rag_factory=create_rag,
    configs={
        "nomic-512": {"embedder": "nomic-embed-text", "chunk_size": 512},
        "mxbai-256": {"embedder": "mxbai-embed-large", "chunk_size": 256},
    },
    testset=testset,
)
print(comparison.summary())         # Side-by-side comparison
print(comparison.winner("ndcg"))    # Best config on a given metric

Monitor Production Quality

from ragnarok_ai import evaluate
from ragnarok_ai.benchmarks import BenchmarkHistory, JSONFileStore

# Track quality over time (JSON time-series storage)
history = BenchmarkHistory(JSONFileStore("./metrics/benchmarks.json"))

results = await evaluate(rag, testset)
record = await history.record(results, "production", testset)
await history.set_baseline(record.id)

# On later runs, compare against the baseline
regression = await history.compare_to_baseline("production", await evaluate(rag, testset), testset)
if regression is not None and regression.has_regressions:
    print("Quality regression detected")

Metrics

Retrieval Metrics

  • Precision@K — Relevant docs in top K results
  • Recall@K — Coverage of relevant docs
  • MRR — Mean Reciprocal Rank
  • NDCG — Normalized Discounted Cumulative Gain

Generation Metrics

  • Faithfulness — Is the answer grounded in retrieved context?
  • Relevance — Does the answer address the question?
  • Hallucination — Does the answer contain fabricated info?
  • Completeness — Are all aspects of the question covered?

LLM-as-Judge (v1.2+)

Use Prometheus 2 for comprehensive, local evaluation:

from ragnarok_ai import LLMJudge

# Initialize judge (uses Prometheus 2 by default)
judge = LLMJudge()

# Evaluate a single response
result = await judge.evaluate_all(
    context="Python was created by Guido van Rossum in 1991.",
    question="Who created Python?",
    answer="Guido van Rossum created Python.",
)

print(f"Overall: {result.overall_verdict} ({result.overall_score:.2f})")
# Overall: PASS (0.85)

print(f"Faithfulness: {result.faithfulness.verdict}")
print(f"Hallucination: {result.hallucination.verdict}")

Performance:

  • ~20-30s per evaluation on Apple M2 16GB
  • Prometheus 2 Q5_K_M: ~5GB RAM usage
  • keep_alive enabled by default (prevents model unloading between requests)

Reproducibility: the Ollama client built by LLMJudge sends temperature=0, seed=42 and num_ctx=8192 (LLMJudge.JUDGE_TEMPERATURE, JUDGE_SEED, JUDGE_NUM_CTX). Ollama truncates silently a prompt longer than its context window; the judge detects the signature of that truncation in the token counters and logs a warning (judge.truncation_warnings counts them). A client passed with llm= is used as given: OllamaLLM(temperature=..., seed=..., num_ctx=..., options={...}) sets the same options yourself; by default OllamaLLM sends none and keeps the server defaults. The judge reads token counters from any client whose generate_detailed() returns an LLMResponse (or any object with text, prompt_tokens, completion_tokens); judge.model_digest records the digest of the Ollama model in use.

Installation:

# Install Prometheus 2 (~5GB, runs on 16GB RAM)
ollama pull hf.co/RichardErkhov/prometheus-eval_-_prometheus-7b-v2.0-gguf:Q5_K_M

LLMJudge picks the prompt format from the model name: the prometheus-eval template and its [RESULT] N parser when the name contains "prometheus", Score: N prompts otherwise. Force it with prompt_format="prometheus" or "score-n" (CLI: --prompt-format) when the name does not tell, for example a Prometheus 2 model served under another name; judge.effective_prompt_format says which one is in use.

To compare a prompted judge with sentence-level classifiers on the same units, wrap it: SentenceLevel(LLMJudge()) segments the answer with the shared segmenter (ragnarok_ai.text.segment_sentences: pysbd sentences, citation markers merged, fragments and markers kept as skipped units), judges each sentence and aggregates (share of PASS sentences as the score and the worst sentence verdict by default; min and mean are available). An aggregated JudgeResult has raw_score=None. Every judge follows the same contract (ragnarok_ai.core.JudgeProtocol): judge.criteria, judge.config(criterion) describing the run (model, options, prompt template hash, verdict policy, input transforms) with a config_hash that tells whether two runs are comparable, and await judge.judge(criterion, question=..., context=..., answer=...). The four named methods of LLMJudge are wrappers of judge(); each JudgeResult carries its output, config and trace (token counters, probable truncation, latency).

If the requested model is not installed, LLMJudge raises JudgeModelNotFoundError with the ollama pull command: it never silently substitutes another model. An ollama cp alias whose name contains "prometheus" (e.g. prometheus2) is accepted for the default model.

Medical Mode

Reduce false positives in healthcare RAG evaluation with automatic medical abbreviation normalization.

from ragnarok_ai import LLMJudge

# Enable medical mode
judge = LLMJudge(medical_mode=True)

# "CHF" and "congestive heart failure" are now treated as equivalent
result = await judge.evaluate_faithfulness(
    context="Patient diagnosed with CHF.",
    question="What condition does the patient have?",
    answer="Patient has congestive heart failure.",
)
# Without medical_mode: may flag as unfaithful (text mismatch)
# With medical_mode: correctly identifies as faithful

Features:

  • 350+ medical abbreviations (CHF, MI, COPD, DVT...)
  • Context-aware disambiguation (MS = multiple sclerosis vs mitral stenosis)
  • Multiple formats: dotted (q.d.), slash (s/p), mixed-case (SpO2)
  • False positive filtering (OR, US, IT stay unchanged)

Also works with FaithfulnessEvaluator(llm, medical_mode=True).

Contributed by @harish1120

System Metrics

  • Latency — End-to-end response time
  • Token usage — Cost tracking for LLM calls

Cost Tracking (v1.3+)

Track exactly what your evaluations cost:

from ragnarok_ai import evaluate

results = await evaluate(rag, testset, track_cost=True)
print(results.cost)
# +--------------------+------------+----------+
# | Provider           |     Tokens |     Cost |
# +--------------------+------------+----------+
# | ollama (local)     |     45,230 |    $0.00 |
# | openai             |     12,500 |    $0.38 |
# +--------------------+------------+----------+

Local-first advantage: Ollama evaluations cost $0.00.

Jupyter Notebook (v1.3.1+)

Rich HTML display for evaluation results:

from ragnarok_ai.notebook import display, display_comparison

# Full dashboard with metrics, cost, latency
display(results)

# Compare multiple pipelines side-by-side
display_comparison([
    ("Baseline", baseline_results),
    ("Improved", improved_results),
])

Roadmap

Completed

v0.1 — Foundation
  • Project setup & architecture
  • Core retrieval metrics (precision, recall, MRR, NDCG)
  • Ollama adapter
  • Console reporter
  • JSON reporter
  • Basic CLI
  • CI/CD with GitHub Actions
v0.2 — Generation Metrics & Reporting
  • Qdrant adapter
  • Faithfulness evaluator
  • Relevance evaluator
  • Hallucination detection
  • HTML report with drill-down (failed questions, retrieved chunks)
  • Intelligent CI gating (stable metrics fail, LLM judgments warn)
v0.3 — Test Generation & Golden Sets
  • Synthetic question generation
  • Multi-hop question support
  • Adversarial question generation
  • Checkpointing system
  • Golden set support (human-validated, versioned question sets)
  • Baselines library (configs + expected results)
  • NovaTech example dataset for quickstart
v0.4 — Framework Adapters & Observability
  • LangChain integration
  • LangGraph integration
  • Custom RAG protocol support
  • OpenTelemetry export for tracing & debugging
v0.5 — Performance & Scale
  • Async parallelization (max_concurrency parameter)
  • Result caching (MemoryCache, DiskCache, CacheProtocol)
  • Batch processing (BatchEvaluator for 1000+ queries)
  • Progress callbacks (sync and async support)
  • Timeout and retry (timeout, max_retries, retry_delay)
  • Cache error handling (graceful degradation)
v0.6 — Cloud & Local Adapters
  • vLLM adapter (local high-performance inference)
  • OpenAI adapter (optional cloud fallback)
  • Anthropic adapter
  • ChromaDB adapter
  • FAISS adapter (pure local, no server)
v0.7 — Framework Adapters
  • LlamaIndex adapter (Retriever, QueryEngine, Index)
  • DSPy adapter (Retrieve, Module, RAG pattern)
  • Custom RAG support via RAGProtocol
  • Adapter contribution guide
v0.8 — Comparison & Benchmarking
  • Comparison mode (compare() for side-by-side evaluation)
  • Regression detection (alert on quality drop vs baseline)
  • Benchmark history tracking (time-series storage)
  • Diff reports (what changed between runs)
v0.9 — Agent Evaluation
  • AgentProtocol for agent pipelines
  • Tool-use correctness metrics (precision, recall, F1)
  • Multi-step reasoning evaluators (coherence, goal progress, efficiency)
  • ReAct/CoT pattern adapters
  • Trajectory analysis (loops, dead ends, failure detection)
  • Visualization (ASCII, Mermaid, HTML reports)
v1.0 — Production Ready
  • PyPI publish (pip install ragnarok-ai)
  • Stable public API
  • Complete README with examples
  • CHANGELOG.md (v0.1 → v1.0)
v1.1 — CLI Complete
  • ragnarok generate command (synthetic testset generation)
  • ragnarok benchmark command (history tracking, regression detection)
  • Standardized JSON envelope for --json output
  • E2E tests for CLI workflow
  • Trusted Publishing (PyPI OIDC)
v1.2 — LLM-as-Judge
  • LLMJudge class with Prometheus 2 integration
  • Multi-criteria evaluation (faithfulness, relevance, hallucination, completeness)
  • 100% local evaluation with Ollama (Q5_K_M quantization, ~5GB)
  • Rubric-based prompts with 1-5 scoring normalized to 0-1
  • Detailed explanations for each judgment
  • Batch evaluation support
  • Robust JSON parsing for LLM responses (handles incomplete JSON)
  • keep_alive support for Ollama (prevents model unloading between requests)
v1.2.5 — Plugin Architecture
  • Plugin system based on Python entry points
  • PluginRegistry singleton for adapter discovery
  • Dynamic discovery of external plugins via importlib.metadata
  • ragnarok plugins CLI command (list, info, filters)
  • Support for 4 namespaces: llm, vectorstore, framework, evaluator
  • LOCAL/CLOUD classification for all adapters
  • Plugin documentation (docs/PLUGINS.md)
  • E2E plugin test with mock package
v1.3.0 — Cost Tracking
  • Cost tracking module (ragnarok_ai.cost)
  • Pricing table for OpenAI, Anthropic, Groq, Mistral, Together AI
  • Token counting with tiktoken (fallback to estimation)
  • CostTracker class with context manager support
  • track_cost=True parameter in evaluate()
  • Formatted summary table and JSON export
  • Local providers (Ollama, vLLM) = $0.00
  • Automatic tracking in LLM adapters
v1.3.1 — Jupyter Integration
  • Jupyter notebook module (ragnarok_ai.notebook)
  • Rich HTML display for evaluation results
  • Metrics visualization with progress bars
  • Cost breakdown tables
  • Pipeline comparison display
  • Auto-detection of notebook environment
v1.4.0 — More Integrations
  • LLM Adapters: Groq, Mistral, Together AI
  • VectorStore Adapters: Pinecone, Weaviate, Milvus, pgvector
  • Framework Adapters: Haystack, Semantic Kernel
  • Medical Mode: Abbreviation normalizer with 350+ terms (contributed by @harish1120)
  • CLI: ragnarok judge command, --config ragnarok.yaml support
  • Docs: MkDocs documentation site, performance benchmarks
v1.4.1 — Dataset Versioning
  • Shared hashing utilities: Canonical JSON, SHA256, content-based keys
  • TestSet versioning: schema_version, dataset_version, created_at, author, source
  • Dataset diff: ragnarok dataset diff CLI command
  • Stable item keys: metadata.id or content hash fallback
  • Diff report: Added/removed/modified/unchanged detection
v1.5.0 — Enterprise Deployment
  • Kubernetes Helm Chart: Job and CronJob modes, ConfigMap, PVC support
  • Air-Gapped Deployment Guide: Complete documentation for offline environments
  • Docker improvements: Fixed Dockerfile for proper module installation
  • Data Sovereignty: Designed for data sovereignty: data never leaves your infrastructure, suited to GDPR- or HIPAA-constrained environments
v1.6.0 — Production Monitoring
  • MonitorClient: Instrument RAG pipelines with configurable sampling
  • Monitor Daemon: HTTP server with /ingest, /metrics, /health, /stats
  • Prometheus Export: Request counts, success rate, latency percentiles
  • SQLite Storage: 7-day trace retention, 90-day aggregate retention
  • CLI Commands: ragnarok monitor start|stop|status|stats
  • PII Safety: Query hashing (SHA256)
  • Custom Metadata: Tenant/route slicing support
v1.7.0 — Alerting
  • AlertManager: Multi-channel alert dispatch with concurrent sending
  • AlertRule: Threshold-based rules with cooldown support
  • WebhookAlertAdapter: Generic HTTP webhook notifications
  • SlackAlertAdapter: Slack notifications with Block Kit formatting
  • Alert Protocols: Alert, AlertResult, AlertSeverity (INFO, WARNING, CRITICAL)
  • Public Exports: AlertManager, AlertRule, AlertSeverity from package root
v1.8.0 — Medical Disambiguation
  • SLMDisambiguator: Resolve ambiguous medical abbreviations (MS, PE, CP...) with a small local model via closed-set classification
  • Tiered Escalation: Keyword scorer first, SLM only on zero context hits, priority fallback on abstention
  • Decision Caching: Per (abbreviation, context window) LRU cache
  • DisambiguationStrategy Protocol: Pluggable resolution backends
  • Evaluator Integration: disambiguation_llm parameter on LLMJudge and FaithfulnessEvaluator
  • Traceability: SLM-resolved expansions tagged [slm]
v1.9.0 — Production Intelligence
  • Drift Detection: PSI-based distribution drift + metric drift against a recorded, PII-free baseline, wired into alerting
  • Live A/B Testing: deterministic traffic splitting, z-test / Welch comparison, conservative winner rule
  • Root-Cause Diagnosis: classify evaluation failures (retrieval miss, ranking, hallucination...) with actionable recommendations
  • MonitorStore.get_traces: window queries over raw production traces
v1.10.0 — Trustworthy Evaluation
  • Production-Mined Testsets: build test sets from real traffic (frequent/failing/slow queries), with opt-in PII-scrubbed query capture
  • Judge Calibration: measure judge-vs-human agreement (Cohen's kappa, error rates by direction, recommended pass threshold)
v1.11.0 — Developer Experience
  • Real Test Set Evaluation: ragnarok evaluate --testset t.json --pipeline module:attr runs your own pipeline
  • Streaming Evaluation: results appear as each query completes, with running metric averages
  • Live Terminal Panel: progress, running metrics, latest queries; plain-line fallback in CI logs
  • Interactive Results TUI: ragnarok view results.json (textual, optional [tui] extra)
  • README Repositioning: identity led by ragnarok-ai's own guarantees

Planned

Next — Evaluation Study (feature freeze)

  • Public reproducible benchmark: human-labeled sample set, multiple local judges
  • Judge reliability study using the calibration module (human agreement per judge model)
  • Technical write-up of methodology and results

On-demand

  • Discord & email alert adapters

v2.0.0 — Visualization

  • Basic Web UI dashboard

Future (on-demand)

  • VS Code extension
  • Multi-modal evaluation
  • Enterprise (SSO, RBAC, Audit)

Architecture

RAGnarok-AI Architecture

View project structure
ragnarok-ai/
├── src/ragnarok_ai/
│   ├── core/           # Types, protocols, exceptions
│   ├── evaluators/     # Metric implementations
│   ├── generators/     # Test set generation
│   ├── adapters/       # LLM, vector store, framework adapters
│   ├── reporters/      # Output formatters (JSON, HTML, console)
│   └── cli/            # Command-line interface
├── tests/              # Test suite (pytest)
├── examples/           # Usage examples
├── benchmarks/         # Performance benchmarks
└── docs/               # Documentation

Development

# Setup
uv pip install -e ".[dev]"
pre-commit install

# Run checks
pytest                    # Tests
pytest --cov=ragnarok_ai  # With coverage
ruff check . --fix        # Lint
ruff format .             # Format
mypy src/                 # Type check

Advanced Usage

Comparing Judges

Judges available out of the box. Every one is a JudgeProtocol judge with a comparable JudgeConfig, so judge-bench, JudgeCalibrator and SentenceLevel take any of them.

Judge Class Runs with Output Default unit Licence Install
Prometheus 2 (7B, Q5_K_M) LLMJudge Ollama, local server 1-5 score, PASS at 4 answer Apache-2.0 (upstream weights) [ollama], then ollama pull
HHEM-2.1-Open (Vectara) HHEMJudge transformers + torch, in process, cpu / mps / cuda P(consistent), PASS at 0.5 (model card default, not calibrated) sentence Apache-2.0 (code and weights); foundation google/flan-t5-base Apache-2.0 [hhem]
MiniCheck-Flan-T5-Large (default), MiniCheck-RoBERTa-Large, MiniCheck-DeBERTa-v3-Large MiniCheckJudge transformers + torch + nltk, in process, cpu / mps / cuda max over document chunks of P(supported), PASS at 0.5 (official default, not calibrated) sentence MIT (all three checkpoints); official code Apache-2.0. Bespoke-MiniCheck-7B not offered (CC BY-NC 4.0) [minicheck]

Fidelity to the published code is measured on CPU in float32 for both classifiers. On mps or cuda small numeric differences are possible; the device is part of the configuration, so a CPU run and an MPS run are never comparable.

HHEMJudge loads two artifacts pinned to a commit, the HHEM weights and the flan-t5-base tokenizer, both recorded in model_digest; the repository's remote code is never executed. The Hugging Face cache is consulted before any download, and HHEMJudge.download(folder) then HHEMJudge(model_path=folder) work with no network at all. The context is the premise and the answer (or each sentence) the hypothesis; the question is not part of the model's input. Nothing is truncated by default (the foundation has no hard window; 512 tokens is its training length), and trace.prompt_tokens says what was sent; max_input_tokens=N cuts the context to fit and sets trace.context_truncated.

from ragnarok_ai.judges import HHEMJudge

judge = HHEMJudge(device="cpu")  # unit="sentence": fraction of consistent sentences, worst verdict
result = await judge.judge(
    "faithfulness",
    question="Who created Python?",
    context="Python was created by Guido van Rossum and first released in 1991.",
    answer="Python was created by Guido van Rossum. It was first released in 1989.",
)
result.score, result.verdict, [(u.text, u.verdict) for u in result.units if u.skipped is None]

MiniCheckJudge reproduces the official code (github.com/Liyan06/MiniCheck, commit b58b9fa, package 0.1.0) without depending on it: sentence split with nltk, chunks of 500 words (Flan-T5) or 400 tokens (RoBERTa, DeBERTa) that never cut a sentence, each chunk checked with the claim, maximum over chunks. The checkpoint revision is pinned and recorded in model_digest; the official code's truncation length (2048 tokens for Flan-T5 and DeBERTa, 512 for RoBERTa) is declared as training_length with training_length_kind saying it is a truncation length, not a training length, and the benchmark report shows it as such; trace.context_truncated says when a chunk hit it. MiniCheckJudge.download(folder) also stores nltk's punkt_tab, the one piece no revision pins; the configuration records nltk's version and the SHA-256 of the punkt_tab files actually loaded, so two runs that split sentences differently are never comparable, and model_path=folder needs no network at all. The pinned checkpoints ship a pytorch_model.bin: it is loaded with weights_only=True (the extra requires torch>=2.6), a model.safetensors is preferred when a folder holds one, and the Hub's automatic conversions on pull request refs are not used.

from ragnarok_ai.judges import MiniCheckJudge

judge = MiniCheckJudge(device="cpu")  # MiniCheck-Flan-T5-Large, unit="sentence"
result = await judge.judge(
    "faithfulness",
    question="Who created Python?",
    context="Python was created by Guido van Rossum and first released in 1991.",
    answer="Python was created by Guido van Rossum. It was first released in 1989.",
)
result.score, result.verdict

ragnarok judge-bench runs any judge on a labeled JSONL set and writes a report. The set is either the sentence-level output of the judge-training conversion (id, question, context, prev_sentence, sentence, label in SUPPORTED / CONTRADICTED / UNSUPPORTED, plus metadata) or an answer-level file (answer, label PASS / FAIL). No data ships with the package.

ragnarok judge-bench --judge llm --data test.jsonl --dev dev.jsonl --out results/prometheus/ \
  --sample 200 --stratify label --seed 7 --by task,generator
  • On a sentence-level set the judge receives each sentence as the answer; prev_sentence is kept in the file, never sent, and the report says how many records carry one.
  • Every call goes through judge_many; attempts.jsonl is written as the run goes and an interrupted run resumes from it by id. Its first line records the judge configuration hash, criterion, level, sample, seed, stratify and the SHA-256 of the data file: a run whose parameters differ is refused (exit code 2), never mixed. Same for dev_attempts.jsonl and --dev. Through the Python API (run_benchmark without data_sha256), the SHA-256 of the records' content takes the file's place, so the check applies there too.
  • --per-class N evaluates at most N records of every label (class quotas, exclusive with --sample). The raw metrics then follow the sample's class mix and the report says so; a prevalence-adjusted section gives the per-class recall, the specificity and the precision and accuracy reweighted by the full set's prevalence of the not-supported class.
  • For a probabilistic judge the pass threshold is chosen on --dev (F1 of the not-supported class) and applied unchanged to --data; without --dev, the judge's own verdict policy applies. Nothing is tuned on the evaluated set.
  • The report (report.json, report.md) states the prediction rule in words (PASS if score >= threshold, PARTIAL and FAIL counted as not supported, with the threshold's value and source) and gives precision, recall and F1 of the not-supported class, balanced accuracy, kappa, the majority-class baseline, per-class F1 and a confusion matrix when the judge predicts the set's classes, Brier and ECE for probabilistic judges, failures by kind, probable truncations, the share of inputs beyond the judge's training length when it declares one (512 tokens for HHEM), p50 / p90 latency, 95% bootstrap intervals grouped on the source (fixed seed), and breakdowns per metadata field. Metrics are computed on the scored records only; the report shows the coverage (evaluated, scored, failed) next to them.
  • Memory: peak_rss_mb_harness is the harness process only. An Ollama model runs in the Ollama server, so for --judge llm the report also gives the model's resident and VRAM size read on /api/ps right after the run, when the server answers.
  • --judge hhem and --judge minicheck[:<checkpoint>] benchmark HHEMJudge and MiniCheckJudge at answer level on --device (the set defines the unit; add --sentence-level on an answer-level set). The model then runs in the harness process, so peak_rss_mb_harness includes it.
  • --judge python:<module>:<Class> benchmarks any JudgeProtocol class of your own.

Importing Types

For advanced use cases (custom RAG implementations, type hints), import types directly from submodules:

# Core types
from ragnarok_ai.core.types import Document, Query, RAGResponse, TestSet

# Protocols (for implementing custom adapters)
from ragnarok_ai.core.protocols import RAGProtocol, LLMProtocol, VectorStoreProtocol

# Evaluators
from ragnarok_ai.evaluators import FaithfulnessEvaluator, RelevanceEvaluator

# Adapters
from ragnarok_ai.adapters.llm import OllamaLLM, OpenAILLM
from ragnarok_ai.adapters.vectorstore import ChromaVectorStore, QdrantVectorStore

Implementing a Custom RAG

from ragnarok_ai import evaluate
from ragnarok_ai.core.types import Document, RAGResponse

class MyCustomRAG:
    """Any object with this async method satisfies RAGProtocol."""

    def __init__(self, documents: list[Document]) -> None:
        self.documents = documents

    async def query(self, question: str) -> RAGResponse:
        # Your retrieval logic here (naive keyword match for illustration)
        words = set(question.lower().split())
        docs = [d for d in self.documents if words & set(d.content.lower().split())][:5]

        # Your generation logic here
        answer = docs[0].content if docs else "I don't know."

        return RAGResponse(answer=answer, retrieved_docs=docs)

results = await evaluate(MyCustomRAG(documents), testset)
print(results.summary())

Feedback

Your feedback helps improve RAGnarok-AI. Pick the right channel:

Type Link
Bug report Report a bug
Feedback / UX Share feedback
Feature request Request a feature
Questions / Ideas Discussions

Contributing

Contributions are welcome! Please read CONTRIBUTING.md for guidelines.

Priority areas for contributions:

  • Framework adapters (Haystack, Semantic Kernel)
  • Agent evaluation features
  • Streaming evaluation support
  • Multi-modal evaluation
  • Documentation & examples

License

RAGnarok-AI is dual-licensed:

License Use Case
AGPL-3.0 Open source projects, personal use, research
Commercial Proprietary software, SaaS, organizations with AGPL restrictions

Why dual licensing?

  • AGPL ensures improvements stay open-source
  • Commercial license enables enterprise adoption without copyleft obligations

For commercial licensing inquiries: abdel.touati@gmail.com


Acknowledgments

Built out of frustration with complex evaluation setups. We wanted something that just works — locally, fast, and without API keys.


Built with ❤️ in Lyon, France

Metadata

Release files for ragnarok-ai 1.13.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for ragnarok-ai 1.13.0
File Size Uploaded Provenance Actions
ragnarok_ai-1.13.0.tar.gz 574.2 kB With provenance Details for ragnarok_ai-1.13.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for ragnarok-ai 1.13.0
File Interpreter ABI Platform Actions
ragnarok_ai-1.13.0-py3-none-any.whl Python 3 none any Details for ragnarok_ai-1.13.0-py3-none-any.whl

Total release size: 1.0 MB

Release files / ragnarok_ai-1.13.0.tar.gz

Download URL ragnarok_ai-1.13.0.tar.gz
Size 574.2 kB
Tags Source
SHA-256 checksum
How to use checksums
9363fc2c0e868c3d3b1509799f289c41626ffc56d48e50056f3ed103fc3ea94c
BLAKE2b-256 checksum
How to use checksums
89a1725db36787a360e7fa7751264e842623002ca2bb58871c58cea774085983
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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 7, 2026.

Transparency log

Release files / ragnarok_ai-1.13.0-py3-none-any.whl

Download URL ragnarok_ai-1.13.0-py3-none-any.whl
Size 432.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
fe09d2a8450b25957c52d2638d618cf4d71839d0c8d81134b84effbb63b4ecec
BLAKE2b-256 checksum
How to use checksums
115f4eb26f65f33e0ee24328c2b58a57eb65a2c085d1ebf2d02b75193e4b88f2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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 7, 2026.

Transparency log

Security for ragnarok-ai 1.13.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.

Select from 2 files

Attestation for ragnarok_ai-1.13.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 7, 2026.

Transparency log

A 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.

Release history Release notifications | RSS feed

This release

1.13.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page