Skip to main content

🛡️ RAGGround

PyPI version Python versions License Test Suite Precision Concurrency

RAGGround is a lightweight, sub-millisecond hallucination guardrail, citation verifier, and RAG evaluation engine.

It verifies whether an LLM-generated answer is strictly grounded in the retrieved context documents, automatically detects extrinsic fabrications and numerical contradictions, and injects clean inline citations ([1], [2]).


⚡ Key Highlights

  • 🚀 Sub-Millisecond Execution: Tier 1 deterministic alignment evaluates in < 0.3 ms on standard CPU.
  • 🧠 Neural NLI Verification: Backed by quantized cross-encoder models with zero silent fallback.
  • 🎯 100% Precision Hallucination Defense: Catches numerical errors, swapped entities, and unsupported claims with zero false approvals.
  • 🩺 Production Readiness & Health Checks: Explicit startup diagnostics (guard.health_check(), ragground doctor).
  • 🔒 Strict Production Mode: require_model=True fails fast if neural model weights are missing or offline.
  • 🧵 Thread-Safe Multi-Worker Concurrency: Verified safe across Flask, Gunicorn, and FastAPI server workers.
  • 📚 Automated Citation Injection: Injects inline citation tags ([1]), footnotes, or HTML hover tooltips.
  • 📊 Dataset Tuning & Evaluation: Auto-tune optimal grounding and contradiction thresholds on your custom dataset.

📦 Installation

pip install ragground

🚀 Quickstart

1. Basic Single-Query Verification

from ragground.app import RAGGround

# 1. Initialize guard (InsightFace-style)
guard = RAGGround(name="nli-deberta-v3-xsmall")
guard.prepare(ctx_id=-1)  # -1 for CPU, 0 for GPU

context = """
Tesla reported Q3 automotive revenue of $20.02 billion, representing an 8% increase 
year-over-year. Free cash flow for the quarter was $2.74 billion.
"""

answer = """
Tesla reported Q3 automotive revenue of $20.02 billion, up 8% YoY. 
Free cash flow reached $2.74 billion. 
The company also announced a new smartphone for $999.
"""

report = guard.verify(context=context, answer=answer)

print("Is Grounded:       ", report.is_grounded)          # False
print("Grounding Score:   ", f"{report.grounding_score*100:.1f}%")  # 66.7%
print("Model Loaded:      ", report.model_loaded)          # True
print("Used Neural Model: ", report.used_neural_model)     # True
print("Verified Claims:   ", report.verified_count)        # 2
print("Hallucinations:    ", report.unsupported_count)     # 1

print("\nCited Answer:")
print(report.cited_answer)

2. Strict Production Mode (No Silent Failures)

In enterprise deployments, ensure the neural model is genuinely active and never silently falling back:

from ragground import RAGGround, ModelNotReadyError

# Fails fast with ModelNotReadyError if model weights are missing
guard = RAGGround(require_model=True, auto_download=False)

# Check health during app startup
health = guard.health_check()
if health["status"] != "healthy":
    raise SystemError(f"RAGGround is not healthy: {health}")

3. Threshold Tuning for Customer Datasets

Automatically find the optimal precision/recall threshold configuration for your domain:

guard = RAGGround()

# Your labeled evaluation dataset
labeled_dataset = [
    {"context": "Water is H2O.", "answer": "Water is composed of H2O.", "grounded": True},
    {"context": "Sky is blue.", "answer": "Sky is purple with yellow dots.", "grounded": False}
]

tuning = guard.tune_thresholds(labeled_dataset)
print("Recommended Threshold:", tuning["recommended_grounding_threshold"])
print("Accuracy at Recommended:", tuning["evaluation_metrics"]["accuracy"])

4. Function Decorator for Python RAG Pipelines

from ragground.decorators import verify_grounding

@verify_grounding(raise_on_hallucination=False)
def generate_rag_response(query: str, context: str) -> str:
    # Your LLM call here
    return "LLM generated response..."

report = generate_rag_response(query="...", context="...")

🛠️ Production CLI Reference

# 🩺 Health Check & Diagnostic Audit
ragground doctor
# (or: ragground verify-installation)

# 📥 Pre-download ONNX model inside Dockerfile
ragground download-model --name nli-deberta-v3-xsmall

# 🔍 Audit answer from terminal
ragground verify -c "Context text..." -a "Answer text..."

# 🎯 Auto-tune thresholds on labeled JSON dataset
ragground tune-thresholds --dataset test_data.json

# ⚡ Benchmark local CPU/GPU hardware throughput
ragground benchmark

⚙️ Configuration Options

Parameter Type Default Description
name str "nli-deberta-v3-xsmall" ONNX model identifier.
root str "~/.ragground" Root cache directory.
require_model bool False When True, raises ModelNotReadyError if neural model is missing.
grounding_threshold float 0.75 Minimum entailment probability required to mark a claim as verified.
contradiction_threshold float 0.65 Probability threshold to classify a claim as contradicted.
deterministic_threshold float 0.80 Exact/fuzzy LCS threshold for sub-millisecond fast-path verification.
ctx_id int -1 Execution provider target (-1 for CPU, 0 for CUDA/CoreML).

📄 License

MIT License. Free for commercial and open-source use.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ragground-0.2.0.tar.gz (39.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ragground-0.2.0-py3-none-any.whl (32.2 kB view details)

Uploaded Python 3

File details

Details for the file ragground-0.2.0.tar.gz.

File metadata

  • Download URL: ragground-0.2.0.tar.gz
  • Upload date:
  • Size: 39.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.6

File hashes

Hashes for ragground-0.2.0.tar.gz
Algorithm Hash digest
SHA256 92baf8c894b4260cc9bdf1b01a99e8bffa2e67636e75447e8d3d330b8a9b2a91
MD5 f5c174c3cab73f891c7ac1233980659d
BLAKE2b-256 d4e6cf12e3c32e395e2c470ea2b13063ab85d4d67196858a5cf05f9f67ec9752

See more details on using hashes here.

File details

Details for the file ragground-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: ragground-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 32.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.6

File hashes

Hashes for ragground-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 99d1e41d43d1f4e9476b84507e88be5ad4ed0130472c4e70a3a0caa1532e5665
MD5 533972f8796a4758702055c76bf9e87b
BLAKE2b-256 c1ea53a73fc7935b13d277461a59f6fd1a96a5eabde6c30ad51f4be921c2bce0

See more details on using hashes here.

Release history Release notifications | RSS feed

0.2.2

2 files

0.2.1

2 files

This release

0.2.0 This release

2 files

0.1.5

2 files

0.1.4

2 files

0.1.3

2 files

0.1.2

2 files

0.1.1

2 files

0.1.0

2 files

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