Skip to main content

hallucination-gate

PyPI Python License: MIT CI

Conservative grounding gate for RAG and fine-tuned LLMs.
Verify answers against your evidence → pass, rewrite, or abstain.

False release is the failure mode that matters. Neighbor chunks no longer veto a claim another chunk fully supports.

Install

pip install -U hallucination-gate
pip install "hallucination-gate[ocr]"   # Tesseract / EasyOCR / scanned PDFs

Quick start

from hallucination_gate import HallucinationGate, Evidence

gate = HallucinationGate()  # neural default (production)
# gate = HallucinationGate(use_heuristic=True)  # CI / offline smoke only

result = gate.check(
    query=user_query,
    answer=llm_answer,
    context=retrieved_docs,  # str | list[str] | LangChain Document | dict
)
return result.text  # show this to users
gate = HallucinationGate(mode="fine_tuned")
result = gate.check(query, answer, kb=your_knowledge_base)

# Images / PDFs / OCR
result = gate.check(query, answer, evidence=Evidence.from_image(path="warranty_card.jpg"))
result = gate.check(query, answer, evidence=Evidence.from_pdf("policy.pdf"))
result = gate.check(query, answer, evidence=Evidence.from_ocr(path="scanned.pdf"))
@gate.protect
def my_rag(query: str):
    docs = retriever(query)
    answer = llm(query, docs)
    return answer, docs

Inspect result.claims / result.diagnostics for claim↔chunk status, citations, and reasons.

OCR

pip install "hallucination-gate[ocr]"
# system: Tesseract binary (+ poppler for scanned PDFs)
from hallucination_gate import Evidence, ocr_available

print(ocr_available())  # pillow / tesseract / easyocr

ev = Evidence.from_image(path="card.jpg")          # auto-OCR + preprocess
ev = Evidence.from_ocr(path="scanned_policy.pdf")  # page OCR fallback

Upscale → contrast → denoise, then Tesseract and/or EasyOCR. Image-only PDFs OCR when text extract is empty.

Evidence patterns

Pattern When
Full retriever top-k Default. Per-chunk soft-OR handles mixed neighbors.
Reranked / answer-aligned top-k Best production default.
Citation-level chunks If the generator emits citations, pass only those.
Top-1 only Demos; too brittle for real retrieval.

Pass a list[str] (or documents)—do not concatenate top-k into one bag.

Heuristic vs neural

Mode How Use for
Neural (default) MiniLM + DeBERTa NLI Production
Heuristic Token / negation / number heuristics CI smoke (use_heuristic=True or RAG_EVAL_HEURISTIC=1)

Heuristic is a wiring check, not a calibrated quality gate.

Optional judge on uncertain claims only: HALLUCINATION_GATE_JUDGE=1 + ANTHROPIC_API_KEY or OPENAI_API_KEY.

What this is (and is not)

It does It does not
Ground claims in your chunks / KB / OCR / PDF Know if the KB itself is wrong
Abstain on contradiction, invented entities, number clashes Read fine-tune weights
Drop ungrounded sentences; abstain if the rest misses the query Replace LLM-as-judge on subtle code/math proofs

Release is decided by claim grounding. BN scores are diagnostics only.

Drawbacks

  • Latency & cost — the neural path adds real inference time (and GPU/CPU load) on every gated answer.
  • Over-refusal — conservative by design; correct extractive answers can still be abstained (e.g. ~0.9 release on some held-out suites).
  • Only as good as evidence — if retrieval is wrong or incomplete, the gate cannot save you. It checks support, not world truth.
  • Weak on hard cases — subtle reasoning, math, code, or paraphrases that NLI misses can slip through or get blocked wrongly.
  • Heuristic ≠ quality gate — token heuristics are a wiring check, not a calibrated faithfulness metric.
  • Ops surface — model downloads, Hugging Face Hub, Windows symlink quirks, and heavy deps (sentence-transformers, torch, etc.).
  • Diagnostics vs product UXclaims / diagnostics help you debug; end users still just see abstain/rewrite text.

Bottom line: Strong as a conservative release firewall after retrieval. Weak as a fast, high-recall answer scorer or a full substitute for eval frameworks (RAGAS-style metrics, regression suites, domain labels).

Eval

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

HTTP API (optional)

Library users do not need a server.

uvicorn bayesian_rag_evaluator.api.main:app --reload --port 8000

POST /v1/answer{safe_answer, released, request_id, latency_ms} only.

License

MIT

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.6.5.tar.gz (57.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.6.5-py3-none-any.whl (62.4 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: hallucination_gate-0.6.5.tar.gz
  • Upload date:
  • Size: 57.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.6.5.tar.gz
Algorithm Hash digest
SHA256 84b3f5de752a5fbb6f94b54ec4b463a2cde8b2ee19d89eed1fc689c05ee348c4
MD5 c69b273b2e1d86a1de6c135758f6200d
BLAKE2b-256 517f440028fb89e3aa8693c92417584873acc79098924c57476b97ad01e70b93

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for hallucination_gate-0.6.5-py3-none-any.whl
Algorithm Hash digest
SHA256 fba72672730b2d1d989993140eb6b210c23b066b2fb9baeb7a0e297cfdb71613
MD5 0bac2547734ee3d8982054fe59e00afa
BLAKE2b-256 d499098c3cdbff5863152d9e565140ae85f5a33786c2941ad254e9ce7a8c37d7

See more details on using hashes here.

Provenance

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

0.9.1

2 files

0.9.0

2 files

0.8.0

2 files

0.7.0

2 files

This release

0.6.5 This release

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