Skip to main content

Semantic contradiction detection for text pairs using NLI models

Project description

contradict-text

Semantic contradiction detection for text pairs using NLI models.

Built for RAG pipelines, fact-checking workflows, and any use case where you need to know if two passages conflict with each other.

How it works

  1. Topic filter embeds both texts and computes cosine similarity. If the similarity is below a configurable threshold (default 0.3), the pair is skipped and returned as neutral without calling the NLI model.
  2. NLI classification passes similar pairs to a Natural Language Inference model that returns one of contradiction, entailment, or neutral, along with a confidence score.

This two-step design keeps inference fast: unrelated pairs never reach the expensive NLI step.

Installation

pip install contradict-text

Requires Python 3.10+.

Note: The PyPI package is contradict-text but the Python import name is contradict.

Quick start

from contradict import ContradictionDetector

detector = ContradictionDetector()

result = detector.check(
    "Rituximab is highly effective for refractory pemphigus vulgaris.",
    "Rituximab shows no significant benefit over standard therapy in PV.",
)
print(result.label)            # "contradiction"
print(result.score)            # e.g. 0.91
print(result.topic_similarity) # e.g. 0.83
print(result.is_contradiction) # True

Scanning a list of texts

scan() checks every pair in a list and returns only the contradicting ones: useful for comparing retrieved chunks in a RAG pipeline.

results = detector.scan(
    texts=[chunk["content"] for chunk in retrieved_docs],
    sources=[chunk["path"] for chunk in retrieved_docs],
)

for r in results:
    print(f"{r.source_a}  vs  {r.source_b} - score: {r.score:.2f}")

scan() runs in O(n²) time over the number of texts, so keep lists reasonably small or pre-filter with your own retriever. Passing sources is optional; if omitted, source_a and source_b will be None. If provided, sources must have the same length as texts.

Configuration

detector = ContradictionDetector(
    nli_model="MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli",  # any HuggingFace NLI model
    embed_model="BAAI/bge-small-en-v1.5",            # any sentence-transformers model
    topic_threshold=0.3,                             # raise to be more selective
)
Parameter Default Description
nli_model MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli HuggingFace NLI model used for classification
embed_model BAAI/bge-small-en-v1.5 Sentence-transformers model used for topic similarity
topic_threshold 0.3 Minimum cosine similarity required before running NLI
contradiction_threshold 0.3 Minimum raw contradiction probability to override the NLI argmax result

ContradictionResult fields

Field Type Description
text_a str First input text
text_b str Second input text
label str "contradiction", "entailment", or "neutral"
score float NLI confidence (0–1); 0.0 when NLI was skipped
topic_similarity float Cosine similarity between the two embeddings
source_a str | None Optional identifier for the source of text_a
source_b str | None Optional identifier for the source of text_b
nli_skipped bool True when topic similarity was below threshold and NLI was not run
is_contradiction bool Convenience property: True when label == "contradiction"

Development

pip install -e ".[dev]"
pytest

License

Apache 2.0

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

contradict_text-0.2.1.tar.gz (14.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

contradict_text-0.2.1-py3-none-any.whl (16.5 kB view details)

Uploaded Python 3

File details

Details for the file contradict_text-0.2.1.tar.gz.

File metadata

  • Download URL: contradict_text-0.2.1.tar.gz
  • Upload date:
  • Size: 14.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.0

File hashes

Hashes for contradict_text-0.2.1.tar.gz
Algorithm Hash digest
SHA256 13ffce2d6cfc7f41c9560fce97377caea816d2830f8a5e8e63a17c3f36e4669c
MD5 d3d7742bdc053156f746a3a74dc12e32
BLAKE2b-256 fb1720b6ea0de8e09792329b7c76edb452203e537941055aa670a9ba0e140e11

See more details on using hashes here.

File details

Details for the file contradict_text-0.2.1-py3-none-any.whl.

File metadata

File hashes

Hashes for contradict_text-0.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 c3a68837de4ed67e56e43454fdae733b052ddd1c61b519cac3a6182a7d1366f8
MD5 4cc531d07637d920ffe75ec8736e0fb0
BLAKE2b-256 9aa4b0274f05d467638e2b59c54843dfc1527d234fda02c7ca51a7256e678100

See more details on using hashes here.

Supported by

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