Skip to main content

🛡️ RAGGround

PyPI version Python versions License Test Suite 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.
  • 🎯 Conservative Hallucination Defense: Routes numerical discrepancies, changed entities, and uncertain paraphrases through neural verification instead of approving them from fuzzy overlap alone.
  • 🩺 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.

🎯 Scope & Boundaries (When to Use & When NOT to Use)

✅ Recommended Use Cases (What RAGGround is Made For):

  • Factual Q&A RAG Pipelines: Verifying that the LLM only answers with information present in retrieved chunks.
  • Extrinsic Hallucination Defense: Catching invented dates, names, prices, and features not stated in reference documents.
  • Inline Citation Injection: Automatically mapping each verified sentence back to its source document ID.
  • Latency-Critical Applications: High-throughput APIs where calling an external LLM for evaluation is too slow or costly.

⚠️ Scope & Known Limitations (When NOT to Use as Sole Arbiter):

  • World Truth Fact-Checking: RAGGround verifies grounding against retrieved text, not cosmic world truth. If the retrieved context contains false information, an answer faithfully repeating that context will be marked as grounded.
  • Complex Multi-Step Math: Not a symbolic calculator or formal proof engine.
  • Raw Code & JSON Schemas: Optimized for natural language English prose; structured data and raw code syntax may require custom extraction.
  • Contexts Exceeding 512 Tokens: Operates best on chunk-level contexts (100–300 words). Large document contexts should be split into passages.
  • Non-English / Multilingual: Current quantized NLI models are trained primarily on English datasets.

📦 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 High-confidence overlap threshold for deterministic verification.
fuzzy_threshold float 0.60 Minimum overlap score considered by the deterministic fuzzy matcher.
min_content_word_coverage float 0.75 Required content-word coverage before deterministic verification.
split_compound_sentences bool True Split compound sentences into independently verifiable claims.
ignore_discourse bool True Exclude standalone greetings and acknowledgements from factual claims.
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.2.tar.gz (42.5 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.2-py3-none-any.whl (34.0 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: ragground-0.2.2.tar.gz
  • Upload date:
  • Size: 42.5 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.2.tar.gz
Algorithm Hash digest
SHA256 34a4e7ddd0bb0c2f9e572ca6c2a17ef9dd6e26f408ace5877332e9c668c60eb9
MD5 65a65a7d56db4dc99781d0400ba976aa
BLAKE2b-256 73e508c91adf856bb639584ecebe119305d55a4cd240085dfbe4ed52d3b73195

See more details on using hashes here.

File details

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

File metadata

  • Download URL: ragground-0.2.2-py3-none-any.whl
  • Upload date:
  • Size: 34.0 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.2-py3-none-any.whl
Algorithm Hash digest
SHA256 b3471d9877519027c8bbf769c2f9ffe5cdb756f579053afa557028a2e5e2e97b
MD5 4853bdefa7cba089e5d0a98ea3ae998c
BLAKE2b-256 7494b002846d547a14b8f9d9667628ed62aa27f8c85f412c00bfeb4ac030f5f1

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

0.2.2 This release

2 files

0.2.1

2 files

0.2.0

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