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 (MiniLM + DeBERTa-small) vs quality_plus (mpnet + DeBERTa-base); 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[neural]"   # MiniLM + DeBERTa (quality / quality_plus)
pip install "hallucination-gate[api]"      # FastAPI sidecar
pip install "hallucination-gate[bn]"       # optional BN diagnostics
pip install "hallucination-gate[ocr]"      # optional OCR

Core install is heuristic (ci) only — no Hugging Face download. Neural models download on first quality / quality_plus call.

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

# labeled false-release on *your* DB traces:
hallucination-gate eval-corpus your_labels.jsonl

# 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",  # "ci" smoke; "quality_plus" for stronger NLI
    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)
# result.release_authority == "claim_status"
# result.scores_are_calibrated is False
# result.evidence_gap in {"none","retrieval","generation","mixed","contradiction"}
return result.text

Shadow mode logs the gate without changing user-visible text:

gate = HallucinationGate(use_heuristic=True, policy="strict", shadow=True)
result = gate.check(query, answer, context=retrieved_docs)
# users still see the model answer
print(result.text)
# counterfactual enforce decision
print(result.gated_text, result.released, result.action)

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)

  • BN is diagnostic. safe_answer is decided by claim status, not by Bayesian posteriors. Those scores are discrete fusion (P(high)+0.5·P(medium)), not calibrated P(hallucination).
  • Latency & cost — neural path adds inference time / GPU·CPU load per sample. quality_plus is heavier on purpose.
  • Over-refusal — conservative gate can abstain on good extractive answers. Published rates: docs/EVAL.md.
  • Only as good as evidence — checks support, not world truth. Faithful answers to weakly aligned chunks abstain (evidence_gap=retrieval). The gate cannot invent missing chunks.
  • ShadowHallucinationGate(shadow=True) keeps user-visible text as the model answer; inspect gated_text / released as the counterfactual.
  • Hard cases — math/code extras and equation clashes are on the lock. Composed multi-hop (AND of extractive facts across 2–3 chunks) may release; speculative NLI-only inferred joins do not in strict.
  • Heuristic ≠ quality gateuse_heuristic=True is for CI smoke, not calibrated faithfulness.
  • Ops surface — sidecar Prometheus /metrics, per-key tenant labels, shared process. Not a multi-tenant platform.
  • Not magic — still needs your domain labels (relevant_contexts / ground_truth) and human review for hard cases.

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
hallucination-gate eval-corpus
hallucination-gate eval-heldout --neural
hallucination-gate eval-corpus your_labels.jsonl

Published false-release and over-refusal: docs/EVAL.md.

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.3.tar.gz (92.1 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.3-py3-none-any.whl (101.4 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: hallucination_gate-0.9.3.tar.gz
  • Upload date:
  • Size: 92.1 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.3.tar.gz
Algorithm Hash digest
SHA256 caa3a05d08f513a1971e0f3486c8bd108ddf3b143c21543997818ae531b3e100
MD5 87c7a7094c05b87a7eade40915499eeb
BLAKE2b-256 5321f70e442ee705210442b43d6b0d4436bee64ba52226a0d17b5f0a7f71020e

See more details on using hashes here.

Provenance

The following attestation bundles were made for hallucination_gate-0.9.3.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.3-py3-none-any.whl.

File metadata

File hashes

Hashes for hallucination_gate-0.9.3-py3-none-any.whl
Algorithm Hash digest
SHA256 374ef749cb52edef2a7ece3677b612869c9736b6ebc42c33b90bf8407e1dc23f
MD5 5f2df6d913fa65e43cca7d1bcbb7b2f9
BLAKE2b-256 f2e90cc6b542692ad326338b6c4c418a3a8f8b071a634adcfaeaf15efc65eedc

See more details on using hashes here.

Provenance

The following attestation bundles were made for hallucination_gate-0.9.3-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

This release

0.9.3 This release

2 files

0.9.2

2 files

0.9.1

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