Metadata-Version: 2.5
Name: ragnarok-ai
Version: 1.13.0
Summary: Local-first evaluation framework for RAG pipelines and AI agents
Project-URL: Homepage, https://github.com/2501Pr0ject/RAGnarok-AI
Project-URL: Repository, https://github.com/2501Pr0ject/RAGnarok-AI
Project-URL: Documentation, https://2501pr0ject.github.io/RAGnarok-AI/
Project-URL: Issues, https://github.com/2501Pr0ject/RAGnarok-AI/issues
Author-email: Abdelatif Touati <abdel.touati@gmail.com>
License: AGPL-3.0
License-File: LICENSE
License-File: LICENSE-COMMERCIAL.md
License-File: NOTICE
Keywords: agents,ai,benchmarking,evaluation,llm,local-first,nlp,ollama,rag,retrieval,testing
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: GNU Affero General Public License v3
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: pydantic-settings>=2.0
Requires-Dist: pydantic>=2.0.1
Requires-Dist: pysbd<0.4,>=0.3.4
Requires-Dist: pyyaml>=6.0
Requires-Dist: rich>=12.3
Requires-Dist: typer>=0.16
Provides-Extra: all
Requires-Dist: asyncpg>=0.29; extra == 'all'
Requires-Dist: chromadb>=0.4; extra == 'all'
Requires-Dist: dspy-ai>=2.0; extra == 'all'
Requires-Dist: faiss-cpu>=1.7; extra == 'all'
Requires-Dist: haystack-ai>=2.0; extra == 'all'
Requires-Dist: httpx>=0.27; extra == 'all'
Requires-Dist: langchain-community>=0.0.10; extra == 'all'
Requires-Dist: langchain>=0.1; extra == 'all'
Requires-Dist: langgraph>=0.1; extra == 'all'
Requires-Dist: llama-index-core>=0.10; extra == 'all'
Requires-Dist: opentelemetry-api>=1.20; extra == 'all'
Requires-Dist: opentelemetry-exporter-otlp-proto-grpc>=1.20; extra == 'all'
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.20; extra == 'all'
Requires-Dist: opentelemetry-sdk>=1.20; extra == 'all'
Requires-Dist: pgvector>=0.2; extra == 'all'
Requires-Dist: pinecone-client>=3.0; extra == 'all'
Requires-Dist: pymilvus>=2.3; extra == 'all'
Requires-Dist: qdrant-client>=1.7; extra == 'all'
Requires-Dist: rich>=12.3; extra == 'all'
Requires-Dist: semantic-kernel>=1.0; extra == 'all'
Requires-Dist: textual>=0.60; extra == 'all'
Requires-Dist: typer>=0.16; extra == 'all'
Requires-Dist: weaviate-client>=4.0; extra == 'all'
Provides-Extra: anthropic
Requires-Dist: httpx>=0.27; extra == 'anthropic'
Provides-Extra: chroma
Requires-Dist: chromadb>=0.4; extra == 'chroma'
Provides-Extra: cli
Requires-Dist: rich>=12.3; extra == 'cli'
Requires-Dist: typer>=0.16; extra == 'cli'
Provides-Extra: dev
Requires-Dist: httpx>=0.27; extra == 'dev'
Requires-Dist: mypy>=1.8; extra == 'dev'
Requires-Dist: pip-audit>=2.7; extra == 'dev'
Requires-Dist: pre-commit>=3.6; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
Requires-Dist: pytest-cov>=4.0; extra == 'dev'
Requires-Dist: pytest-randomly>=3.15; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: respx>=0.20; extra == 'dev'
Requires-Dist: ruff>=0.3; extra == 'dev'
Requires-Dist: time-machine>=2.10; extra == 'dev'
Requires-Dist: types-pyyaml>=6.0; extra == 'dev'
Provides-Extra: docs
Requires-Dist: mkdocs-material>=9.5; extra == 'docs'
Requires-Dist: mkdocs-minify-plugin>=0.8; extra == 'docs'
Requires-Dist: mkdocs>=1.6; extra == 'docs'
Provides-Extra: dspy
Requires-Dist: dspy-ai>=2.0; extra == 'dspy'
Provides-Extra: faiss
Requires-Dist: faiss-cpu>=1.7; extra == 'faiss'
Provides-Extra: groq
Requires-Dist: httpx>=0.27; extra == 'groq'
Provides-Extra: haystack
Requires-Dist: haystack-ai>=2.0; extra == 'haystack'
Provides-Extra: hhem
Requires-Dist: huggingface-hub>=0.23; extra == 'hhem'
Requires-Dist: safetensors>=0.4; extra == 'hhem'
Requires-Dist: torch>=2.1; extra == 'hhem'
Requires-Dist: transformers>=4.40; extra == 'hhem'
Provides-Extra: langchain
Requires-Dist: langchain-community>=0.0.10; extra == 'langchain'
Requires-Dist: langchain>=0.1; extra == 'langchain'
Provides-Extra: langgraph
Requires-Dist: langgraph>=0.1; extra == 'langgraph'
Provides-Extra: llamaindex
Requires-Dist: llama-index-core>=0.10; extra == 'llamaindex'
Provides-Extra: milvus
Requires-Dist: pymilvus>=2.3; extra == 'milvus'
Provides-Extra: minicheck
Requires-Dist: huggingface-hub>=0.23; extra == 'minicheck'
Requires-Dist: nltk>=3.9; extra == 'minicheck'
Requires-Dist: torch>=2.6; extra == 'minicheck'
Requires-Dist: transformers>=4.40; extra == 'minicheck'
Provides-Extra: mistral
Requires-Dist: httpx>=0.27; extra == 'mistral'
Provides-Extra: ollama
Requires-Dist: httpx>=0.27; extra == 'ollama'
Provides-Extra: openai
Requires-Dist: httpx>=0.27; extra == 'openai'
Provides-Extra: pgvector
Requires-Dist: asyncpg>=0.29; extra == 'pgvector'
Requires-Dist: pgvector>=0.2; extra == 'pgvector'
Provides-Extra: pinecone
Requires-Dist: pinecone-client>=3.0; extra == 'pinecone'
Provides-Extra: qdrant
Requires-Dist: qdrant-client>=1.7; extra == 'qdrant'
Provides-Extra: semantic-kernel
Requires-Dist: semantic-kernel>=1.0; extra == 'semantic-kernel'
Provides-Extra: telemetry
Requires-Dist: opentelemetry-api>=1.20; extra == 'telemetry'
Requires-Dist: opentelemetry-exporter-otlp-proto-grpc>=1.20; extra == 'telemetry'
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.20; extra == 'telemetry'
Requires-Dist: opentelemetry-sdk>=1.20; extra == 'telemetry'
Provides-Extra: together
Requires-Dist: httpx>=0.27; extra == 'together'
Provides-Extra: tui
Requires-Dist: textual>=0.60; extra == 'tui'
Provides-Extra: vllm
Requires-Dist: httpx>=0.27; extra == 'vllm'
Provides-Extra: weaviate
Requires-Dist: weaviate-client>=4.0; extra == 'weaviate'
Description-Content-Type: text/markdown

<p align="center">
  <img src="https://raw.githubusercontent.com/2501Pr0ject/RAGnarok-AI/main/assets/logo.png" alt="ragnarok-ai logo" width="300">
</p>

<p align="center">
  <strong>Local-first RAG evaluation framework for LLM applications</strong>
</p>

<p align="center">
  Evaluate, benchmark, and monitor your RAG pipelines — 100% locally, no API keys required.
</p>

<p align="center">
  <a href="https://pypi.org/project/ragnarok-ai/"><img src="https://img.shields.io/pypi/v/ragnarok-ai.svg" alt="PyPI"></a>
  <a href="https://github.com/2501Pr0ject/RAGnarok-AI/actions/workflows/ci.yml"><img src="https://github.com/2501Pr0ject/RAGnarok-AI/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
  <a href="https://www.python.org/downloads/"><img src="https://img.shields.io/badge/python-3.10+-blue.svg" alt="Python 3.10+"></a>
  <a href="https://www.gnu.org/licenses/agpl-3.0"><img src="https://img.shields.io/badge/License-AGPL--3.0-green.svg" alt="License: AGPL-3.0"></a>
  <a href="https://github.com/astral-sh/ruff"><img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json" alt="Ruff"></a>
  <a href="https://mypy-lang.org/"><img src="https://img.shields.io/badge/type%20checked-mypy-blue.svg" alt="Type Checked: mypy"></a>
  <a href="https://colab.research.google.com/drive/1BC90iuDMwYi4u9I59jfcjNYiBd2MNvTA?usp=sharing"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a>
  <a href="https://huggingface.co/spaces/ragnarok-ai/retrieval-metrics-demo"><img src="https://img.shields.io/badge/Open%20in-Spaces-yellow.svg" alt="Open in Spaces"></a>
  <a href="https://huggingface.co/ragnarok-ai"><img src="https://img.shields.io/badge/Hugging%20Face-ragnarok--ai-yellow.svg" alt="Hugging Face: ragnarok-ai"></a>
</p>

<p align="center">
  <a href="#the-problem">Problem</a> •
  <a href="#the-solution">Solution</a> •
  <a href="#quick-start">Quick Start</a> •
  <a href="#installation">Installation</a> •
  <a href="#roadmap">Roadmap</a>
</p>

---

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

<p align="center">
  <img src="https://raw.githubusercontent.com/2501Pr0ject/RAGnarok-AI/main/assets/overview.png" alt="RAGnarok-AI Overview" width="900">
</p>

```python
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](#llm-as-judge-v12).

---

## 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 →](benchmarks/README.md)

---

## Quick Start

**Try it now:** [Open in Google Colab](https://colab.research.google.com/drive/1BC90iuDMwYi4u9I59jfcjNYiBd2MNvTA?usp=sharing)

### Prerequisites

- Python 3.10+
- [Ollama](https://ollama.ai/) running locally
- [uv](https://github.com/astral-sh/uv) (recommended) or pip

### Install

```bash
pip install ragnarok-ai
```

With optional dependencies:

```bash
pip install ragnarok-ai[ollama,qdrant]
```

### Run your first evaluation

```bash
# 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

```bash
pip install ragnarok-ai
```

### Optional dependencies

```bash
# 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

```bash
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

```yaml
# .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

```python
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

```python
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:

```python
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:**
```bash
# 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.

```python
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](https://github.com/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:

```python
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:

```python
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

<details>
<summary><strong>v0.1 — Foundation</strong></summary>

- [x] Project setup & architecture
- [x] Core retrieval metrics (precision, recall, MRR, NDCG)
- [x] Ollama adapter
- [x] Console reporter
- [x] JSON reporter
- [x] Basic CLI
- [x] CI/CD with GitHub Actions

</details>

<details>
<summary><strong>v0.2 — Generation Metrics & Reporting</strong></summary>

- [x] Qdrant adapter
- [x] Faithfulness evaluator
- [x] Relevance evaluator
- [x] Hallucination detection
- [x] HTML report with drill-down (failed questions, retrieved chunks)
- [x] Intelligent CI gating (stable metrics fail, LLM judgments warn)

</details>

<details>
<summary><strong>v0.3 — Test Generation & Golden Sets</strong></summary>

- [x] Synthetic question generation
- [x] Multi-hop question support
- [x] Adversarial question generation
- [x] Checkpointing system
- [x] Golden set support (human-validated, versioned question sets)
- [x] Baselines library (configs + expected results)
- [x] NovaTech example dataset for quickstart

</details>

<details>
<summary><strong>v0.4 — Framework Adapters & Observability</strong></summary>

- [x] LangChain integration
- [x] LangGraph integration
- [x] Custom RAG protocol support
- [x] OpenTelemetry export for tracing & debugging

</details>

<details>
<summary><strong>v0.5 — Performance & Scale</strong></summary>

- [x] Async parallelization (`max_concurrency` parameter)
- [x] Result caching (`MemoryCache`, `DiskCache`, `CacheProtocol`)
- [x] Batch processing (`BatchEvaluator` for 1000+ queries)
- [x] Progress callbacks (sync and async support)
- [x] Timeout and retry (`timeout`, `max_retries`, `retry_delay`)
- [x] Cache error handling (graceful degradation)

</details>

<details>
<summary><strong>v0.6 — Cloud & Local Adapters</strong></summary>

- [x] vLLM adapter (local high-performance inference)
- [x] OpenAI adapter (optional cloud fallback)
- [x] Anthropic adapter
- [x] ChromaDB adapter
- [x] FAISS adapter (pure local, no server)

</details>

<details>
<summary><strong>v0.7 — Framework Adapters</strong></summary>

- [x] LlamaIndex adapter (Retriever, QueryEngine, Index)
- [x] DSPy adapter (Retrieve, Module, RAG pattern)
- [x] Custom RAG support via `RAGProtocol`
- [x] Adapter contribution guide

</details>

<details>
<summary><strong>v0.8 — Comparison & Benchmarking</strong></summary>

- [x] Comparison mode (`compare()` for side-by-side evaluation)
- [x] Regression detection (alert on quality drop vs baseline)
- [x] Benchmark history tracking (time-series storage)
- [x] Diff reports (what changed between runs)

</details>

<details>
<summary><strong>v0.9 — Agent Evaluation</strong></summary>

- [x] `AgentProtocol` for agent pipelines
- [x] Tool-use correctness metrics (precision, recall, F1)
- [x] Multi-step reasoning evaluators (coherence, goal progress, efficiency)
- [x] ReAct/CoT pattern adapters
- [x] Trajectory analysis (loops, dead ends, failure detection)
- [x] Visualization (ASCII, Mermaid, HTML reports)

</details>

<details>
<summary><strong>v1.0 — Production Ready</strong></summary>

- [x] PyPI publish (`pip install ragnarok-ai`)
- [x] Stable public API
- [x] Complete README with examples
- [x] CHANGELOG.md (v0.1 → v1.0)

</details>

<details>
<summary><strong>v1.1 — CLI Complete</strong></summary>

- [x] `ragnarok generate` command (synthetic testset generation)
- [x] `ragnarok benchmark` command (history tracking, regression detection)
- [x] Standardized JSON envelope for `--json` output
- [x] E2E tests for CLI workflow
- [x] Trusted Publishing (PyPI OIDC)

</details>

<details>
<summary><strong>v1.2 — LLM-as-Judge</strong></summary>

- [x] `LLMJudge` class with Prometheus 2 integration
- [x] Multi-criteria evaluation (faithfulness, relevance, hallucination, completeness)
- [x] 100% local evaluation with Ollama (Q5_K_M quantization, ~5GB)
- [x] Rubric-based prompts with 1-5 scoring normalized to 0-1
- [x] Detailed explanations for each judgment
- [x] Batch evaluation support
- [x] Robust JSON parsing for LLM responses (handles incomplete JSON)
- [x] `keep_alive` support for Ollama (prevents model unloading between requests)

</details>

<details>
<summary><strong>v1.2.5 — Plugin Architecture</strong></summary>

- [x] Plugin system based on Python entry points
- [x] `PluginRegistry` singleton for adapter discovery
- [x] Dynamic discovery of external plugins via `importlib.metadata`
- [x] `ragnarok plugins` CLI command (list, info, filters)
- [x] Support for 4 namespaces: llm, vectorstore, framework, evaluator
- [x] LOCAL/CLOUD classification for all adapters
- [x] Plugin documentation (`docs/PLUGINS.md`)
- [x] E2E plugin test with mock package

</details>

<details>
<summary><strong>v1.3.0 — Cost Tracking</strong></summary>

- [x] Cost tracking module (`ragnarok_ai.cost`)
- [x] Pricing table for OpenAI, Anthropic, Groq, Mistral, Together AI
- [x] Token counting with tiktoken (fallback to estimation)
- [x] `CostTracker` class with context manager support
- [x] `track_cost=True` parameter in `evaluate()`
- [x] Formatted summary table and JSON export
- [x] Local providers (Ollama, vLLM) = $0.00
- [x] Automatic tracking in LLM adapters

</details>

<details>
<summary><strong>v1.3.1 — Jupyter Integration</strong></summary>

- [x] Jupyter notebook module (`ragnarok_ai.notebook`)
- [x] Rich HTML display for evaluation results
- [x] Metrics visualization with progress bars
- [x] Cost breakdown tables
- [x] Pipeline comparison display
- [x] Auto-detection of notebook environment

</details>

<details>
<summary><strong>v1.4.0 — More Integrations</strong></summary>

- [x] **LLM Adapters**: Groq, Mistral, Together AI
- [x] **VectorStore Adapters**: Pinecone, Weaviate, Milvus, pgvector
- [x] **Framework Adapters**: Haystack, Semantic Kernel
- [x] **Medical Mode**: Abbreviation normalizer with 350+ terms (contributed by [@harish1120](https://github.com/harish1120))
- [x] **CLI**: `ragnarok judge` command, `--config ragnarok.yaml` support
- [x] **Docs**: MkDocs documentation site, performance benchmarks

</details>

<details>
<summary><strong>v1.4.1 — Dataset Versioning</strong></summary>

- [x] **Shared hashing utilities**: Canonical JSON, SHA256, content-based keys
- [x] **TestSet versioning**: `schema_version`, `dataset_version`, `created_at`, `author`, `source`
- [x] **Dataset diff**: `ragnarok dataset diff` CLI command
- [x] **Stable item keys**: `metadata.id` or content hash fallback
- [x] **Diff report**: Added/removed/modified/unchanged detection

</details>

<details>
<summary><strong>v1.5.0 — Enterprise Deployment</strong></summary>

- [x] **Kubernetes Helm Chart**: Job and CronJob modes, ConfigMap, PVC support
- [x] **Air-Gapped Deployment Guide**: Complete documentation for offline environments
- [x] **Docker improvements**: Fixed Dockerfile for proper module installation
- [x] **Data Sovereignty**: Designed for data sovereignty: data never leaves your infrastructure, suited to GDPR- or HIPAA-constrained environments

</details>

<details>
<summary><strong>v1.6.0 — Production Monitoring</strong></summary>

- [x] **MonitorClient**: Instrument RAG pipelines with configurable sampling
- [x] **Monitor Daemon**: HTTP server with `/ingest`, `/metrics`, `/health`, `/stats`
- [x] **Prometheus Export**: Request counts, success rate, latency percentiles
- [x] **SQLite Storage**: 7-day trace retention, 90-day aggregate retention
- [x] **CLI Commands**: `ragnarok monitor start|stop|status|stats`
- [x] **PII Safety**: Query hashing (SHA256)
- [x] **Custom Metadata**: Tenant/route slicing support

</details>

<details>
<summary><strong>v1.7.0 — Alerting</strong></summary>

- [x] **AlertManager**: Multi-channel alert dispatch with concurrent sending
- [x] **AlertRule**: Threshold-based rules with cooldown support
- [x] **WebhookAlertAdapter**: Generic HTTP webhook notifications
- [x] **SlackAlertAdapter**: Slack notifications with Block Kit formatting
- [x] **Alert Protocols**: Alert, AlertResult, AlertSeverity (INFO, WARNING, CRITICAL)
- [x] **Public Exports**: AlertManager, AlertRule, AlertSeverity from package root

</details>

<details>
<summary><strong>v1.8.0 — Medical Disambiguation</strong></summary>

- [x] **SLMDisambiguator**: Resolve ambiguous medical abbreviations (MS, PE, CP...) with a small local model via closed-set classification
- [x] **Tiered Escalation**: Keyword scorer first, SLM only on zero context hits, priority fallback on abstention
- [x] **Decision Caching**: Per (abbreviation, context window) LRU cache
- [x] **DisambiguationStrategy Protocol**: Pluggable resolution backends
- [x] **Evaluator Integration**: `disambiguation_llm` parameter on LLMJudge and FaithfulnessEvaluator
- [x] **Traceability**: SLM-resolved expansions tagged `[slm]`

</details>

<details>
<summary><strong>v1.9.0 — Production Intelligence</strong></summary>

- [x] **Drift Detection**: PSI-based distribution drift + metric drift against a recorded, PII-free baseline, wired into alerting
- [x] **Live A/B Testing**: deterministic traffic splitting, z-test / Welch comparison, conservative winner rule
- [x] **Root-Cause Diagnosis**: classify evaluation failures (retrieval miss, ranking, hallucination...) with actionable recommendations
- [x] **MonitorStore.get_traces**: window queries over raw production traces

</details>

<details>
<summary><strong>v1.10.0 — Trustworthy Evaluation</strong></summary>

- [x] **Production-Mined Testsets**: build test sets from real traffic (frequent/failing/slow queries), with opt-in PII-scrubbed query capture
- [x] **Judge Calibration**: measure judge-vs-human agreement (Cohen's kappa, error rates by direction, recommended pass threshold)

</details>

<details>
<summary><strong>v1.11.0 — Developer Experience</strong></summary>

- [x] **Real Test Set Evaluation**: `ragnarok evaluate --testset t.json --pipeline module:attr` runs your own pipeline
- [x] **Streaming Evaluation**: results appear as each query completes, with running metric averages
- [x] **Live Terminal Panel**: progress, running metrics, latest queries; plain-line fallback in CI logs
- [x] **Interactive Results TUI**: `ragnarok view results.json` (textual, optional `[tui]` extra)
- [x] **README Repositioning**: identity led by ragnarok-ai's own guarantees

</details>

### 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

<p align="center">
  <img src="https://raw.githubusercontent.com/2501Pr0ject/RAGnarok-AI/main/assets/architecture.png" alt="RAGnarok-AI Architecture" width="1000">
</p>

<details>
<summary><strong>View project structure</strong></summary>

```
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
```

</details>

---

## Development

```bash
# 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`.

```python
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.

```python
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.

```bash
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:

```python
# 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

```python
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](https://github.com/2501Pr0ject/RAGnarok-AI/issues/new?template=bug_report.yml) |
| Feedback / UX | [Share feedback](https://github.com/2501Pr0ject/RAGnarok-AI/issues/new?template=feedback.yml) |
| Feature request | [Request a feature](https://github.com/2501Pr0ject/RAGnarok-AI/issues/new?template=feature_request.yml) |
| Questions / Ideas | [Discussions](https://github.com/2501Pr0ject/RAGnarok-AI/discussions) |

---

## Contributing

Contributions are welcome! Please read [CONTRIBUTING.md](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](LICENSE) | Open source projects, personal use, research |
| [Commercial](LICENSE-COMMERCIAL.md) | 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.

---

<p align="center">
  <sub>Built with ❤️ in Lyon, France</sub>
</p>
