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.5), 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="cross-encoder/nli-deberta-v3-small",  # any HuggingFace NLI model
    embed_model="BAAI/bge-small-en-v1.5",            # any sentence-transformers model
    topic_threshold=0.5,                             # raise to be more selective
)
Parameter Default Description
nli_model cross-encoder/nli-deberta-v3-small HuggingFace NLI model used for classification
embed_model BAAI/bge-small-en-v1.5 Sentence-transformers model used for topic similarity
topic_threshold 0.5 Minimum cosine similarity required before running NLI

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.1.0.tar.gz (13.9 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.1.0-py3-none-any.whl (16.3 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: contradict_text-0.1.0.tar.gz
  • Upload date:
  • Size: 13.9 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.1.0.tar.gz
Algorithm Hash digest
SHA256 4bdaf4b466ffc61dae8898d7456648ae2a35dcb3b3aa6058345205327dce5fd7
MD5 3b535da1efc4394b7c1df364cb5e38f0
BLAKE2b-256 5625be8c253a42527813e772779789a6417b363027bf93e09e1054b1f62c00df

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for contradict_text-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0f6d3aadb4faf432e12f6e503e5fe0cfcace688df6a2a5f5ef8f92b94ad8997b
MD5 7c63d36b9899002712c9e78a61f867a3
BLAKE2b-256 2a895dc9dd6b2f232f3647d389d3d68ca3b41d3568530ed8b5a9d2920fcd517d

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