Skip to main content

hallucination-gate

PyPI Python License: MIT CI

RAG quality system + conservative release gate for RAG and fine-tuned LLMs.

End-to-end system design (pipeline, claim lock, BN, eval, sidecar): ARCHITECTURE.md.

Visual architecture (download): SVG · PNG

  • Eval: claim-level faithfulness / relevancy / context metrics
  • Retrieval: hit@k, recall@k, MRR, nDCG@k
  • Regression: save baseline → diff → fail CI
  • Latency budget: p50 / p95 / p99 / max ceilings
  • Modes: ci (heuristic smoke) vs quality (neural); policies strict / balanced
  • Gate: pass / rewrite / abstain for production safe_answer
  • Lock upgrades: structured claims, multi-hop inferred (not a release in strict), temporal/negation/scope, source reliability, calibrated fusion
  • Bench: hallucination-gate eval-adversarial / eval-benchmark

Author: Shreyas G.

Install

pip install -U hallucination-gate
pip install "hallucination-gate[ocr]"   # optional OCR

RAG eval (RAGAS replacement path)

from hallucination_gate import RAGEval, LatencyBudget

evaler = RAGEval(
    use_heuristic=True,  # CI; omit for neural production eval
    latency_budget=LatencyBudget(p95_ms=1500, max_ms=5000),
)
report = evaler.evaluate(
    [
        {
            "query": "What is the warranty?",
            "answer": "The Titan watch has a 2-year warranty.",
            "contexts": [
                "The Titan watch has a 2-year warranty covering defects.",
                "Shipping takes 3-5 days.",
            ],
            "ground_truth": "2-year warranty for manufacturing defects.",
            "relevant_contexts": [
                "The Titan watch has a 2-year warranty covering defects."
            ],
            # or: "relevant_indices": [0],
        }
    ],
    save_baseline_path="baselines/titan.json",
    # baseline_path="baselines/titan.json",
    # fail_on_regression=True,
)
print(report.aggregate)   # faithfulness, answer_relevancy, ...
print(report.retrieval)   # hit_at_k, mrr, ndcg_at_k, ...
print(report.latency)     # p50/p95/p99 + budget ok
report.raise_if_failed()
hallucination-gate eval-dataset samples.jsonl --out report.json \
  --save-baseline baselines/titan.json --p95-ms 1500

# later in CI:
hallucination-gate eval-dataset samples.jsonl \
  --baseline baselines/titan.json --fail-on-regression --p95-ms 1500
Metric How this package scores it
faithfulness Fraction of answer claims supported by individual chunks (contradictions penalize)
answer_relevancy Query↔answer embedding relevance
context_precision Labeled relevant_contexts if provided; else claim-aligned chunk proxy
context_recall Requires ground_truth — fraction of reference facts covered by contexts
hit@k / MRR / nDCG Ranked retrieval vs relevant_contexts or relevant_indices
latency budget p50/p95/p99/max vs LatencyBudget
regression Diff aggregates/retrieval/latency vs saved baseline; fail CI on drops
groundedness / hallucination_risk / release_safety BN posteriors from the same evidence stack

Why this beats typical RAGAS setups for grounding: claim-level soft-OR against neighbors, retrieval+latency+regression in one report, false-release oriented gate, multimodal/OCR evidence, and a production safe_answer path — not only a mean score.

Production gate

from hallucination_gate import HallucinationGate, Evidence

gate = HallucinationGate(
    quality_mode="quality",  # or "ci" for heuristic smoke only
    policy="balanced",       # or "strict" for max false-release lock
    warm=True,               # preload models — cuts cold-start tails
)
result = gate.check(query, answer, context=retrieved_docs)
return result.text

Context chunks are aligned/filtered to the query+answer by default (generic overlap/embedding score — no domain lexicon). Metrics expose both context_precision_labeled and context_precision_aligned.

report = gate.evaluate(samples)  # same backends as the gate

OCR

from hallucination_gate import Evidence, ocr_available

ev = Evidence.from_image(path="warranty_card.jpg")
ev = Evidence.from_ocr(path="scanned_policy.pdf")

Drawbacks (honest)

  • Latency & cost — neural path adds inference time / GPU·CPU load per sample.
  • Over-refusal — conservative gate can abstain on good extractive answers.
  • Only as good as evidence — checks support, not world truth; bad retrieval still hurts.
  • Hard cases — subtle math/code/reasoning can fool or over-block NLI.
  • Heuristic ≠ quality gateuse_heuristic=True is for CI smoke, not calibrated faithfulness.
  • Ops surface — HF downloads, torch/sentence-transformers weight, Windows symlink quirks.
  • Not magic — still needs your domain labels (relevant_contexts / ground_truth) and human review for hard cases; the stack now covers grounding + retrieval + latency SLOs + regression diffs.

Eval (gate safety)

pip install -e ".[dev]"
set RAG_EVAL_HEURISTIC=1
pytest -q -m "not neural"
hallucination-gate eval-heldout
hallucination-gate eval-adversarial
hallucination-gate eval-benchmark

License

MIT © Shreyas G

Download files

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

Source Distribution

hallucination_gate-0.9.1.tar.gz (79.4 kB view details)

Uploaded Source

Built Distribution

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

hallucination_gate-0.9.1-py3-none-any.whl (89.2 kB view details)

Uploaded Python 3

File details

Details for the file hallucination_gate-0.9.1.tar.gz.

File metadata

  • Download URL: hallucination_gate-0.9.1.tar.gz
  • Upload date:
  • Size: 79.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for hallucination_gate-0.9.1.tar.gz
Algorithm Hash digest
SHA256 e82c5b8b8af63e527ddd9bd3ff6a7b83d541bfe3f9c943b97fdf07e1016d8fff
MD5 82a2c18b99af42582700a8ec43c14032
BLAKE2b-256 37f277e1a6e3c972949ebd8559578d1846c619a5a36a6373c7c684a9b2f797c0

See more details on using hashes here.

Provenance

The following attestation bundles were made for hallucination_gate-0.9.1.tar.gz:

Publisher: publish.yml on shrey315/hallucination-gate

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file hallucination_gate-0.9.1-py3-none-any.whl.

File metadata

File hashes

Hashes for hallucination_gate-0.9.1-py3-none-any.whl
Algorithm Hash digest
SHA256 b2ae6b172fa0bf65654d82d5ce69532a6bf28ff78994f81292cfcb52752d94f4
MD5 2f5c7e70709b95b5d400fe470f1d8cfc
BLAKE2b-256 311b1fc36f78a8d6b917c948d3f86902de6308779d0043a2ec4b9a3664e4c952

See more details on using hashes here.

Provenance

The following attestation bundles were made for hallucination_gate-0.9.1-py3-none-any.whl:

Publisher: publish.yml on shrey315/hallucination-gate

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

0.9.4

2 files

0.9.3

2 files

0.9.2

2 files

This release

0.9.1 This release

2 files

0.9.0

2 files

0.8.0

2 files

0.7.0

2 files

0.6.5

2 files

0.6.4

2 files

0.6.3

2 files

0.6.2

2 files

0.6.1

2 files

0.6.0

2 files

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page