Code

NLI Alignment Detector API

Python
NLI
Cross-Encoder
API
Bottle
Machine Learning

Universal text alignment API using bidirectional NLI for symmetric alignment detection. Returns alignment scores [-1, +1] via averaged entailment checks. Zero-dependency Bottle framework, 38 lines.

Bottle API code showing CrossEncoder NLI model with apply_softmax normalization
INPUT                          PROCESS                           OUTPUT
┌─────────────────┐
│ "Market crash"  │──┐
└─────────────────┘  │          ┌───────────────────────┐         ┌────────────────┐
                     ├────────▶│  NLI Cross-Encoder    │───────▶│ Alignment:     │
┌─────────────────┐  │          │                       │         │    -0.850      │
│ "Bullish trend" │──┘          │  Bidirectional check  │         │                │
└─────────────────┘             │  text1 → text2        │         │ -1 = opposite  │
                                │  text2 → text1        │         │  0 = neutral   │
                                └──────────┬────────────┘         │ +1 = aligned   │
                                           │                      └────────────────┘
                                           ▼
                                ┌──────────────────────┐
                                │ apply_softmax=True   │
                                │ → probabilities [0,1]│
                                └──────────┬───────────┘
                                           ▼
                                ┌──────────────────────┐
                                │ entailment - contra  │
                                │ Average both dirs    │
                                │ → [-1, +1] range     │
                                └──────────────────────┘

Minimal API that tells you how two texts align using AI logic instead of just similarity matching.

Send any two texts → get back an alignment score from -1 (opposite) to +1 (aligned). Unlike cosine similarity that only shows “how related”, this captures direction: whether things support or contradict each other. The model checks “if text1 is true, does text2 logically follow?” in both directions, then averages for symmetry. Uses entailment and contradiction probabilities from apply_softmax=True to compute symmetric alignment. 38 lines, two endpoints (/api/alignment, /api/info)

from bottle import post, get, run, request, response
from sentence_transformers import CrossEncoder

model = CrossEncoder("./models/nli-deberta-v3-base")

@post('/api/alignment')
def alignment():
    data = request.json
    text1 = data.get('text1', '')
    text2 = data.get('text2', '')

    if not text1 or not text2:
        response.status = 400
        return {'error': 'Both text1 and text2 are required'}

    scores = model.predict([
        (text1, text2),  # If text1 is true, is text2 also true?
        (text2, text1)   # If text2 is true, is text1 also true?
    ], apply_softmax=True)

    dir1 = scores[0][1] - scores[0][0] 
    dir2 = scores[1][1] - scores[1][0] 

    alignment = float(round((dir1 + dir2) / 2, 3)) 

    return {
        'text1': text1,
        'text2': text2,
        'alignment': alignment
    }

@get('/api/info')
def info():
    """API metadata and capabilities"""
    return {
        'name': 'nli-alignment-detector',
        'version': '2.0.0',
        'description': 'Bidirectional NLI for symmetric alignment - detects if texts support (+1), contradict (-1), or are unrelated (0)',
        'model': 'cross-encoder/nli-deberta-v3-base',
        'use_cases': ['fact-checking', 'contradiction-detection', 'policy-compliance', 'sentiment-consistency', 'logical-validation'],
        'alignment_range': [-1.0, 1.0],
        'interpretation': {'-1': 'contradiction', '0': 'unrelated/neutral', '+1': 'alignment/support'},
        'endpoints': ['/api/alignment', '/api/info']
    }

if __name__ == '__main__':
    run(host='0.0.0.0', port=5000, debug=True)

Unlike standard NLI (A→B only), bidirectional checking (A→B AND B→A averaged) provides symmetric alignment - crucial when neither text is definitively the “premise” or “hypothesis,” and you need mutual consistency rather than one-way entailment.

Use Cases

  1. Fact-Checking & Claim Verification

    Document-level NLI verifies if claims are entailed by source documents. Bidirectional checking ensures mutual consistency between evidence and claims.

    • Scientific claim verification with fine-tuned NLI models
    • Fake news detection by comparing article content against verified sources
  2. Contradiction Detection

    Detecting if two statements contradict, support, or are neutral to each other.

    • Multi-turn dialogue: Reduces conflicting responses in conversational AI
    • Content moderation: Flags contradictory information within documents
  3. Policy Compliance & Customer Support

    Determines if user messages are consistent with account data or policy rules.

    • Customer support automation: Check if user requests align with account policies
    • Compliance checking: Verify statements against regulatory requirements
  4. Legal & Contract Review

    Flags clauses that contradict standard templates or other contract sections.

    • Contract analysis: Detect conflicting terms
    • Requirements analysis: Ensure specifications don’t contradict
  5. Sentiment Consistency Analysis

    Financial sentiment alignment: Check if two statements about the same entity/topic align.

    • Market sentiment tracking: Detect contradictory signals
    • Brand sentiment monitoring: Identify inconsistent messaging
  6. Logical Validation

    Knowledge graph coherence checking using extracted entities and relations.

    • Database consistency: Verify records don’t contradict
    • Multi-source information fusion: Resolve conflicting data

Sources: