hallucination-gate
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) vsquality(MiniLM + DeBERTa-small) vsquality_plus(mpnet + DeBERTa-base); policiesstrict/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_answeris 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_plusis 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. - Shadow —
HallucinationGate(shadow=True)keeps user-visibletextas the model answer; inspectgated_text/releasedas 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 gate —
use_heuristic=Trueis 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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
caa3a05d08f513a1971e0f3486c8bd108ddf3b143c21543997818ae531b3e100
|
|
| MD5 |
87c7a7094c05b87a7eade40915499eeb
|
|
| BLAKE2b-256 |
5321f70e442ee705210442b43d6b0d4436bee64ba52226a0d17b5f0a7f71020e
|
Provenance
The following attestation bundles were made for hallucination_gate-0.9.3.tar.gz:
Publisher:
publish.yml on shrey315/hallucination-gate
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
hallucination_gate-0.9.3.tar.gz -
Subject digest:
caa3a05d08f513a1971e0f3486c8bd108ddf3b143c21543997818ae531b3e100 - Sigstore transparency entry: 2504071387
- Sigstore integration time:
-
Permalink:
shrey315/hallucination-gate@aad9eedfad187898c703d5d72c071a467c3cf732 -
Branch / Tag:
refs/tags/v0.9.3 - Owner: https://github.com/shrey315
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@aad9eedfad187898c703d5d72c071a467c3cf732 -
Trigger Event:
release
-
Statement type:
File details
Details for the file hallucination_gate-0.9.3-py3-none-any.whl.
File metadata
- Download URL: hallucination_gate-0.9.3-py3-none-any.whl
- Upload date:
- Size: 101.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via:
twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
374ef749cb52edef2a7ece3677b612869c9736b6ebc42c33b90bf8407e1dc23f
|
|
| MD5 |
5f2df6d913fa65e43cca7d1bcbb7b2f9
|
|
| BLAKE2b-256 |
f2e90cc6b542692ad326338b6c4c418a3a8f8b071a634adcfaeaf15efc65eedc
|
Provenance
The following attestation bundles were made for hallucination_gate-0.9.3-py3-none-any.whl:
Publisher:
publish.yml on shrey315/hallucination-gate
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
hallucination_gate-0.9.3-py3-none-any.whl -
Subject digest:
374ef749cb52edef2a7ece3677b612869c9736b6ebc42c33b90bf8407e1dc23f - Sigstore transparency entry: 2504071686
- Sigstore integration time:
-
Permalink:
shrey315/hallucination-gate@aad9eedfad187898c703d5d72c071a467c3cf732 -
Branch / Tag:
refs/tags/v0.9.3 - Owner: https://github.com/shrey315
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@aad9eedfad187898c703d5d72c071a467c3cf732 -
Trigger Event:
release
-
Statement type: