Local-first evaluation framework for RAG pipelines and AI agents
pip install ragnarok-ai==1.12.3 Copy PIP instructions
Local-first RAG evaluation framework for LLM applications
Evaluate, benchmark, and monitor your RAG pipelines — 100% locally, no API keys required.
Problem • Solution • Quick Start • Installation • Roadmap
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:
ragnarok-ai is a lightweight, local-first framework to evaluate RAG pipelines.
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.
ragnarok-ai is built around a small set of guarantees:
Benchmarked on Apple M2 16GB, Python 3.10 (RAGnarok-AI v1.4.0):
Retrieval is pure computation — instant. LLM-as-Judge is the bottleneck (~25s/eval), but runs 100% local.
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.
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:
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.
# 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.
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.
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:
Also works with FaithfulnessEvaluator(llm, medical_mode=True).
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.
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/ ├── 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 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:
Contributions are welcome! Please read CONTRIBUTING.md for guidelines.
For commercial licensing inquiries: abdel.touati@gmail.com
Built out of frustration with complex evaluation setups. We wanted something that just works — locally, fast, and without API keys.
Both files in this release have provenance metadata.
GNU Affero General Public License v3 (AGPL-3.0)
all anthropic chroma cli dev docs dspy faiss groq haystack langchain langgraph llamaindex milvus mistral ollama openai pgvector pinecone qdrant semantic-kernel telemetry together tui vllm weaviate
agents ai benchmarking evaluation llm local-first nlp ollama rag retrieval testing
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
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 verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 6, 2026.
Both files in this release have been uploaded with provenance metadata.
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.
Yanked reason: RecursionError on from ragnarok_ai.adapters import ; fixed in 1.12.1




