Skip to main content

hallucination-gate

A conservative grounding gate for RAG and fine-tuned generators. It does not decide whether an answer is true in the world. It decides whether the answer is supported by the evidence you pass in, then passes, rewrites, or abstains.

False release is treated as the failure mode that matters. If a rewrite would no longer answer the question, the gate abstains.

from hallucination_gate import HallucinationGate, Evidence

gate = HallucinationGate()  # neural backends (production default)
# 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 | LlamaIndex node | dict
)
return result.text  # show this to users

Each claim is scored against individual chunks, then soft-OR aggregated: a supporting chunk wins even if a neighbor has unrelated numbers. Contradiction only counts from aligned chunks (enough lexical/semantic overlap with the claim).

gate = HallucinationGate(mode="fine_tuned")
result = gate.check(query, answer, kb=your_knowledge_base)

result = gate.check(query, answer, evidence=Evidence.from_image(path="photo.jpg", ocr="..."))
result = gate.check(query, answer, evidence=Evidence.from_pdf("policy.pdf"))
@gate.protect
def my_rag(query: str):
    docs = retriever(query)
    answer = llm(query, docs)
    return answer, docs

What evidence to pass

Pass the chunks that should ground the answer. Typical RAG top-k is fine now that scoring is per-chunk, but garbage neighbors still waste work and can create borderline UNCERTAIN hits.

Pattern When
Full retriever top-k Default. Claim↔chunk alignment handles mixed neighbors.
Answer-aligned / reranked top-k Best production default — keep chunks that cite the same entities/numbers as the draft answer.
Citation-level evidence If the generator emits citations, pass only those cited chunks.
Top-1 only Debugging / demos; too brittle for real retrieval.

Do not concatenate all chunks into one string before calling check — pass a list[str] (or documents) so boundaries are preserved.

Inspect grounding with result.claims: each claim has status, source_id, citation, reason, and chunk_hits (per-chunk scores).

Heuristic vs neural (contract)

Mode How Use for
Neural (default) MiniLM embeddings + DeBERTa NLI Production gate. Override with embed_model= / nli_model= or RAG_EVAL_EMBED_MODEL / RAG_EVAL_NLI_MODEL.
Heuristic Token overlap / negation / number heuristics CI smoke, offline unit tests. Set use_heuristic=True or RAG_EVAL_HEURISTIC=1.

Heuristic is not calibrated to neural false-release / over-refusal rates. Treat heuristic PASS/ABSTAIN as a wiring check, not a quality gate. Ship production with neural backends (or an explicit judge escalation).

Optional: HALLUCINATION_GATE_JUDGE=1 plus ANTHROPIC_API_KEY or OPENAI_API_KEY escalates uncertain claims only, using the top aligned chunks (not the full bag).

What this is (and is not)

It does It does not
Check claims against your retrieved chunks / KB / OCR / PDF text Know if the KB itself is wrong
Abstain on contradiction, invented entities, and number clashes Read fine-tune weights
Drop ungrounded sentences, then abstain if the remainder misses the query Replace an LLM-as-judge on subtle reasoning, code, or math proofs
Work with any stack that can give you query, answer, evidence Guarantee multilingual performance equal to English without swapping models

Release is decided by claim grounding, not by the Bayesian network. BN scores are diagnostics only.

Eval

Held-out domains (HR, API, vaccines, Redis, K8s) report false release and over-refusal:

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

Install

pip install hallucination-gate

From GitHub:

pip install git+https://github.com/shrey315/hallucination-gate.git

From this folder:

pip install -e ".[dev]"
pytest -q

HTTP API (optional)

Only needed if you want a separate service. Library users do not need a running server.

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

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

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.1.tar.gz (53.0 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.1-py3-none-any.whl (58.2 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: hallucination_gate-0.6.1.tar.gz
  • Upload date:
  • Size: 53.0 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.1.tar.gz
Algorithm Hash digest
SHA256 1a56c057aded6bac6dade9c771b1ca009414ec655055b9888b1422f62d390942
MD5 b51e2272c17ff1626de528cec3af1962
BLAKE2b-256 0a89a773c56cc57fd6576281c1c0cccde4093af55d815a954dc574ca1dcb3f66

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for hallucination_gate-0.6.1-py3-none-any.whl
Algorithm Hash digest
SHA256 dbb88d80cffb9bda70c0ca894360688ca9f038b4288b16e1aaa94d1967240e13
MD5 87f754cda71ee9216f52008020990dae
BLAKE2b-256 57bae0eeb99ac3c705431f27fefc046f61ea3e3261ff1d090761235ce3706066

See more details on using hashes here.

Provenance

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

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

This release

0.6.1 This release

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