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, composed 2–3 hop (strict may pass), inferred NLI-only (strict will not), retrieval-poison abstain, temporal/negation/scope, source reliability
  • 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.4.tar.gz (92.2 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.4-py3-none-any.whl (101.5 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: hallucination_gate-0.9.4.tar.gz
  • Upload date:
  • Size: 92.2 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.4.tar.gz
Algorithm Hash digest
SHA256 ee04128b0127409ff7d744457ed559e76d49ce1275d0d57e33fb5feca4f4980e
MD5 6dcafb2cd5586a5881d8ce11b5b21229
BLAKE2b-256 2783b940a9c9ef428e5b771eb02689acafd6a827a15ba1aead427dc86d0d7dae

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for hallucination_gate-0.9.4-py3-none-any.whl
Algorithm Hash digest
SHA256 1492d3fece0f81222324568949aa52b83bcd2d918f19d9726e42fc2d010202f0
MD5 b659f53850e9cbf73a29917ed003b3c0
BLAKE2b-256 85f4b4dc6a38126d29e4319ba5b1f4abc00e64e85091b8f045d00124c6e8ab7a

See more details on using hashes here.

Provenance

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

Supported by

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