structurerag 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- structurerag/__init__.py +56 -0
- structurerag/core/__init__.py +16 -0
- structurerag/core/builder.py +309 -0
- structurerag/core/hsf.py +249 -0
- structurerag/core/reasoner.py +305 -0
- structurerag/grounding/__init__.py +20 -0
- structurerag/grounding/citation.py +173 -0
- structurerag/grounding/reranker.py +160 -0
- structurerag/grounding/retriever.py +980 -0
- structurerag/grounding/verifier.py +774 -0
- structurerag/loaders/__init__.py +6 -0
- structurerag/loaders/pdf.py +36 -0
- structurerag/loaders/text.py +16 -0
- structurerag/semantic.py +307 -0
- structurerag/structurerag.py +455 -0
- structurerag-0.1.0.dist-info/METADATA +186 -0
- structurerag-0.1.0.dist-info/RECORD +20 -0
- structurerag-0.1.0.dist-info/WHEEL +5 -0
- structurerag-0.1.0.dist-info/licenses/LICENSE +21 -0
- structurerag-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,774 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Grounding Verifier: Verifies LLM claims against HSF knowledge base.
|
|
3
|
+
|
|
4
|
+
This is the core innovation - deterministic verification of LLM outputs
|
|
5
|
+
by checking if claims can be traced back to source structures.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import re
|
|
9
|
+
from typing import List, Dict, Optional, Set, Any
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from ..core.hsf import HolisticStructuralForm
|
|
12
|
+
from ..semantic import SemanticExpander, create_default_expander
|
|
13
|
+
from .retriever import StructureRetriever, SearchResult
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class Claim:
|
|
18
|
+
"""A single claim extracted from text."""
|
|
19
|
+
id: str
|
|
20
|
+
text: str
|
|
21
|
+
start_pos: int
|
|
22
|
+
end_pos: int
|
|
23
|
+
confidence: float = 1.0
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class GroundingSpan:
|
|
28
|
+
"""A contiguous region of a claim, marked grounded or not.
|
|
29
|
+
|
|
30
|
+
Offsets are character positions within the claim text (Claim.start_pos ..
|
|
31
|
+
end_pos). ``terms`` lists the content words of an ungrounded span that no
|
|
32
|
+
single passage licensed - the same words the licensing gate refused.
|
|
33
|
+
"""
|
|
34
|
+
start: int
|
|
35
|
+
end: int
|
|
36
|
+
text: str
|
|
37
|
+
grounded: bool
|
|
38
|
+
terms: List[str] = field(default_factory=list)
|
|
39
|
+
|
|
40
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
41
|
+
return {
|
|
42
|
+
'start': self.start,
|
|
43
|
+
'end': self.end,
|
|
44
|
+
'text': self.text,
|
|
45
|
+
'grounded': self.grounded,
|
|
46
|
+
'terms': self.terms,
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass
|
|
51
|
+
class VerificationResult:
|
|
52
|
+
"""Result of verifying a claim against HSF."""
|
|
53
|
+
claim_id: str
|
|
54
|
+
claim_text: str
|
|
55
|
+
is_verified: bool
|
|
56
|
+
confidence: float
|
|
57
|
+
supporting_evidence: List[SearchResult]
|
|
58
|
+
contradicting_evidence: List[SearchResult]
|
|
59
|
+
source_references: List[Dict[str, Any]]
|
|
60
|
+
unexplained_terms: List[str] = field(default_factory=list)
|
|
61
|
+
spans: List[GroundingSpan] = field(default_factory=list)
|
|
62
|
+
unverified_numbers: List[str] = field(default_factory=list)
|
|
63
|
+
repair: Optional[Dict[str, Any]] = None
|
|
64
|
+
|
|
65
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
66
|
+
return {
|
|
67
|
+
'claim_id': self.claim_id,
|
|
68
|
+
'claim_text': self.claim_text,
|
|
69
|
+
'is_verified': self.is_verified,
|
|
70
|
+
'confidence': self.confidence,
|
|
71
|
+
'supporting_evidence': [e.to_dict() for e in self.supporting_evidence],
|
|
72
|
+
'contradicting_evidence': [e.to_dict() for e in self.contradicting_evidence],
|
|
73
|
+
'source_references': self.source_references,
|
|
74
|
+
'unexplained_terms': self.unexplained_terms,
|
|
75
|
+
'spans': [s.to_dict() for s in self.spans],
|
|
76
|
+
'unverified_numbers': self.unverified_numbers,
|
|
77
|
+
'repair': self.repair,
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class GroundingVerifier:
|
|
82
|
+
"""
|
|
83
|
+
Verifies claims from LLM outputs against the HSF knowledge base.
|
|
84
|
+
|
|
85
|
+
Key capabilities:
|
|
86
|
+
- Extract claims from text
|
|
87
|
+
- Match claims against structured knowledge
|
|
88
|
+
- Detect hallucinations (unverified claims)
|
|
89
|
+
- Provide source citations for verified claims
|
|
90
|
+
- Calculate grounding confidence scores
|
|
91
|
+
"""
|
|
92
|
+
|
|
93
|
+
def __init__(self, hsf: Optional[HolisticStructuralForm] = None,
|
|
94
|
+
retriever: Optional['StructureRetriever'] = None,
|
|
95
|
+
document_ids: Optional[List[str]] = None,
|
|
96
|
+
semantic_expander: Optional[SemanticExpander] = None):
|
|
97
|
+
"""
|
|
98
|
+
Args:
|
|
99
|
+
hsf: The knowledge base to verify against. Optional when
|
|
100
|
+
``retriever`` is supplied; a corpus-wide verifier has no single
|
|
101
|
+
document to name.
|
|
102
|
+
retriever: Retriever to use. Pass the corpus-level retriever so
|
|
103
|
+
verification scores sit on the same scale as search scores.
|
|
104
|
+
Defaults to a private BM25 index over ``hsf`` alone.
|
|
105
|
+
document_ids: Restrict evidence to these documents. Use alongside a
|
|
106
|
+
shared corpus retriever to keep evidence inside one document.
|
|
107
|
+
semantic_expander: Defines which paraphrases count as the same claim.
|
|
108
|
+
The retriever's own expander is reused when one is available, so
|
|
109
|
+
verification and retrieval agree on what a word means.
|
|
110
|
+
"""
|
|
111
|
+
if hsf is None and retriever is None:
|
|
112
|
+
raise ValueError("GroundingVerifier needs either hsf or retriever")
|
|
113
|
+
|
|
114
|
+
self.hsf = hsf
|
|
115
|
+
self.document_ids = list(document_ids) if document_ids is not None else None
|
|
116
|
+
self.retriever = retriever or StructureRetriever(hsf)
|
|
117
|
+
self.semantic_expander = (
|
|
118
|
+
semantic_expander
|
|
119
|
+
or getattr(self.retriever, 'semantic_expander', None)
|
|
120
|
+
or create_default_expander()
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
@staticmethod
|
|
124
|
+
def _relevance(result: SearchResult) -> float:
|
|
125
|
+
"""Retrieval-scale relevance of a result, even after reranking.
|
|
126
|
+
|
|
127
|
+
Rerankers replace ``SearchResult.score`` with their own scale (a 0-1
|
|
128
|
+
heuristic composite or a squashed cross-encoder logit). The BM25
|
|
129
|
+
score rides along in metadata, so relevance thresholds and confidence
|
|
130
|
+
stay on the retrieval scale regardless of reranking.
|
|
131
|
+
"""
|
|
132
|
+
return float(result.metadata.get('bm25_score', result.score))
|
|
133
|
+
|
|
134
|
+
def verify_text(self, text: str, claim_extraction_method: str = "sentence") -> List[VerificationResult]:
|
|
135
|
+
"""
|
|
136
|
+
Verify all claims in a text against the HSF.
|
|
137
|
+
|
|
138
|
+
Args:
|
|
139
|
+
text: The text containing claims to verify
|
|
140
|
+
claim_extraction_method: How to extract claims ("sentence", "clause", "full")
|
|
141
|
+
|
|
142
|
+
Returns:
|
|
143
|
+
List of VerificationResult for each claim
|
|
144
|
+
"""
|
|
145
|
+
claims = self._extract_claims(text, claim_extraction_method)
|
|
146
|
+
results = []
|
|
147
|
+
|
|
148
|
+
for claim in claims:
|
|
149
|
+
result = self.verify_claim(claim)
|
|
150
|
+
results.append(result)
|
|
151
|
+
|
|
152
|
+
return results
|
|
153
|
+
|
|
154
|
+
def verify_claim(self, claim: Claim) -> VerificationResult:
|
|
155
|
+
"""
|
|
156
|
+
Verify a single claim against the HSF.
|
|
157
|
+
|
|
158
|
+
Verification requires that the claim content actually aligns with
|
|
159
|
+
the retrieved evidence, not just that keywords overlap. A claim
|
|
160
|
+
that contradicts the source is rejected even if many words match.
|
|
161
|
+
|
|
162
|
+
Args:
|
|
163
|
+
claim: The claim to verify
|
|
164
|
+
|
|
165
|
+
Returns:
|
|
166
|
+
VerificationResult with verification status and evidence
|
|
167
|
+
"""
|
|
168
|
+
# Search for relevant evidence (broad search). Thresholds sit on the
|
|
169
|
+
# squashed score scale: see grounding/SCORING.md for raw equivalents.
|
|
170
|
+
search_results = self.retriever.search(
|
|
171
|
+
query=claim.text,
|
|
172
|
+
top_k=5,
|
|
173
|
+
fuzzy_threshold=0.20,
|
|
174
|
+
document_ids=self.document_ids,
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
# Classify each result. Anything left unexplained is handled by the
|
|
178
|
+
# licensing gate below, not by this loop.
|
|
179
|
+
supporting = []
|
|
180
|
+
contradicting = []
|
|
181
|
+
|
|
182
|
+
for result in search_results:
|
|
183
|
+
if self._has_conflict(claim.text, result.content):
|
|
184
|
+
contradicting.append(result)
|
|
185
|
+
elif self._relevance(result) >= 0.35:
|
|
186
|
+
supporting.append(result)
|
|
187
|
+
|
|
188
|
+
# Licensing is per passage, never pooled. Pooling across retrieved
|
|
189
|
+
# passages would let a term be "explained" by an unrelated sentence: a
|
|
190
|
+
# claim about water could borrow 'increases' from a sentence about
|
|
191
|
+
# coffee. One passage must account for the whole claim.
|
|
192
|
+
unexplained, best_vocab, best_result = self._best_passage_grounding(
|
|
193
|
+
claim.text, supporting)
|
|
194
|
+
spans = self._grounding_spans(claim.text, best_vocab)
|
|
195
|
+
unverified_numbers = self._unverified_numbers(claim.text, best_result)
|
|
196
|
+
|
|
197
|
+
confidence = self._calculate_confidence(claim, supporting, contradicting, unexplained)
|
|
198
|
+
is_verified = (
|
|
199
|
+
len(supporting) > 0
|
|
200
|
+
and len(contradicting) == 0
|
|
201
|
+
and not unexplained
|
|
202
|
+
and not unverified_numbers
|
|
203
|
+
and confidence >= 0.35
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
# Deterministic repair: only for refused claims, and only proposed
|
|
207
|
+
# against the one passage the gate judged the claim against. A
|
|
208
|
+
# contradicted claim gets no repair - nothing trustworthy to aim at.
|
|
209
|
+
repair = None
|
|
210
|
+
if not is_verified and best_result is not None:
|
|
211
|
+
repair = self._suggest_repair(
|
|
212
|
+
claim.text, set(unexplained), set(unverified_numbers),
|
|
213
|
+
best_result, best_vocab)
|
|
214
|
+
|
|
215
|
+
# Build source references
|
|
216
|
+
source_refs = []
|
|
217
|
+
for result in supporting[:3]:
|
|
218
|
+
source_refs.append({
|
|
219
|
+
'feature_id': result.feature_id,
|
|
220
|
+
'feature_type': result.feature_type,
|
|
221
|
+
'content': result.content,
|
|
222
|
+
'path': result.path,
|
|
223
|
+
'relevance_score': result.score,
|
|
224
|
+
'document_id': result.metadata.get('document_id')
|
|
225
|
+
})
|
|
226
|
+
|
|
227
|
+
return VerificationResult(
|
|
228
|
+
claim_id=claim.id,
|
|
229
|
+
claim_text=claim.text,
|
|
230
|
+
is_verified=is_verified,
|
|
231
|
+
confidence=confidence,
|
|
232
|
+
supporting_evidence=supporting,
|
|
233
|
+
contradicting_evidence=contradicting,
|
|
234
|
+
source_references=source_refs,
|
|
235
|
+
unexplained_terms=sorted(unexplained),
|
|
236
|
+
spans=spans,
|
|
237
|
+
unverified_numbers=unverified_numbers,
|
|
238
|
+
repair=repair,
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
def _extract_claims(self, text: str, method: str) -> List[Claim]:
|
|
242
|
+
"""Extract individual claims from text."""
|
|
243
|
+
claims = []
|
|
244
|
+
|
|
245
|
+
if method == "sentence":
|
|
246
|
+
# Split by sentence boundaries
|
|
247
|
+
sentences = re.split(r'(?<=[.!?])\s+', text)
|
|
248
|
+
cursor = 0
|
|
249
|
+
for i, sentence in enumerate(sentences):
|
|
250
|
+
sentence = sentence.strip()
|
|
251
|
+
if sentence and len(sentence) > 10: # Skip very short sentences
|
|
252
|
+
# find() from the cursor: a repeated sentence maps to its
|
|
253
|
+
# own occurrence, not all of them to the first.
|
|
254
|
+
start = text.find(sentence, cursor)
|
|
255
|
+
if start == -1:
|
|
256
|
+
start = text.find(sentence)
|
|
257
|
+
else:
|
|
258
|
+
cursor = start + len(sentence)
|
|
259
|
+
claim = Claim(
|
|
260
|
+
id=f"claim_{i}",
|
|
261
|
+
text=sentence,
|
|
262
|
+
start_pos=start,
|
|
263
|
+
end_pos=start + len(sentence)
|
|
264
|
+
)
|
|
265
|
+
claims.append(claim)
|
|
266
|
+
|
|
267
|
+
elif method == "clause":
|
|
268
|
+
# Split by clauses (simplified)
|
|
269
|
+
clauses = re.split(r'[,;:]\s+', text)
|
|
270
|
+
cursor = 0
|
|
271
|
+
for i, clause in enumerate(clauses):
|
|
272
|
+
clause = clause.strip()
|
|
273
|
+
if clause and len(clause) > 20:
|
|
274
|
+
start = text.find(clause, cursor)
|
|
275
|
+
if start == -1:
|
|
276
|
+
start = text.find(clause)
|
|
277
|
+
else:
|
|
278
|
+
cursor = start + len(clause)
|
|
279
|
+
claim = Claim(
|
|
280
|
+
id=f"claim_{i}",
|
|
281
|
+
text=clause,
|
|
282
|
+
start_pos=start,
|
|
283
|
+
end_pos=start + len(clause)
|
|
284
|
+
)
|
|
285
|
+
claims.append(claim)
|
|
286
|
+
|
|
287
|
+
else: # full
|
|
288
|
+
# Treat entire text as one claim
|
|
289
|
+
claims.append(Claim(
|
|
290
|
+
id="claim_full",
|
|
291
|
+
text=text,
|
|
292
|
+
start_pos=0,
|
|
293
|
+
end_pos=len(text)
|
|
294
|
+
))
|
|
295
|
+
|
|
296
|
+
return claims
|
|
297
|
+
|
|
298
|
+
# ── Negation / antonym dictionaries for contradiction detection ────────
|
|
299
|
+
|
|
300
|
+
_NEGATION_WORDS = frozenset({
|
|
301
|
+
'not', 'no', 'never', 'neither', 'nor', 'cannot', 'unable',
|
|
302
|
+
'without', 'lack', 'lacks', 'lacking', 'absent',
|
|
303
|
+
"don't", "doesn't", "didn't", "won't", "wouldn't", "isn't",
|
|
304
|
+
"aren't", "wasn't", "weren't", "haven't", "hasn't", "hadn't",
|
|
305
|
+
})
|
|
306
|
+
|
|
307
|
+
# Phrases that negate whatever follows them
|
|
308
|
+
_NEGATION_PHRASES = [
|
|
309
|
+
'instead of', 'rather than', 'as opposed to', 'unlike',
|
|
310
|
+
'not use', 'not using', 'does not use', 'without using',
|
|
311
|
+
'no need for', 'eliminates the need for', 'replaces',
|
|
312
|
+
]
|
|
313
|
+
|
|
314
|
+
_ANTONYM_PAIRS = [
|
|
315
|
+
('deterministic', 'non-deterministic'), ('deterministic', 'stochastic'),
|
|
316
|
+
('deterministic', 'probabilistic'),
|
|
317
|
+
('structure-based', 'embedding-based'), ('structure', 'embedding'),
|
|
318
|
+
('structural', 'embedding'), ('structural', 'vector'),
|
|
319
|
+
('lossless', 'lossy'),
|
|
320
|
+
('fast', 'slow'), ('efficient', 'inefficient'),
|
|
321
|
+
('exact', 'approximate'), ('precise', 'imprecise'),
|
|
322
|
+
('include', 'exclude'),
|
|
323
|
+
('enable', 'disable'), ('allow', 'prevent'),
|
|
324
|
+
('increase', 'decrease'), ('improve', 'degrade'),
|
|
325
|
+
]
|
|
326
|
+
|
|
327
|
+
_STOP_WORDS = frozenset({
|
|
328
|
+
'the', 'a', 'an', 'is', 'are', 'was', 'were', 'be', 'been',
|
|
329
|
+
'being', 'have', 'has', 'had', 'do', 'does', 'did', 'will',
|
|
330
|
+
'would', 'could', 'should', 'may', 'might', 'shall', 'can',
|
|
331
|
+
'and', 'or', 'but', 'if', 'of', 'at', 'by', 'for', 'with',
|
|
332
|
+
'about', 'to', 'from', 'in', 'on', 'that', 'this', 'it',
|
|
333
|
+
'its', 'as', 'into', 'through',
|
|
334
|
+
})
|
|
335
|
+
|
|
336
|
+
# A number possibly grouped with thousands commas and/or decimal:
|
|
337
|
+
# '3,000', '3000', '3.5', '1,500.25'. Tried before the word pattern so a
|
|
338
|
+
# number is one token, never split at its comma.
|
|
339
|
+
_TOKEN_RE = re.compile(r"\b\d[\d,]*(?:\.\d+)?\b|\b\w+(?:'\w+)?\b")
|
|
340
|
+
|
|
341
|
+
# Bare numbers for the dedicated number check.
|
|
342
|
+
_NUMBER_RE = re.compile(r"\b\d+(?:\.\d+)?\b")
|
|
343
|
+
|
|
344
|
+
@staticmethod
|
|
345
|
+
def _canonicalize_numbers(text: str) -> str:
|
|
346
|
+
"""Collapse number spellings so comparisons are exact yet fair.
|
|
347
|
+
|
|
348
|
+
'3,000' == '3000', '007' == '7', '3.50' == '3.5'. Verifier-side only;
|
|
349
|
+
stored text is never touched. Unit conversion is deliberately out of
|
|
350
|
+
scope: '3 km' does not satisfy '3000 m'.
|
|
351
|
+
"""
|
|
352
|
+
text = re.sub(r'(?<=\d)\s*,\s*(?=\d)', '', text) # '3 , 000' -> '3,000'
|
|
353
|
+
text = re.sub(r'(?<=\d)\s*\.\s*(?=\d)', '.', text) # '3 . 50' -> '3.50'
|
|
354
|
+
text = re.sub(r'(?<=\d),(?=\d)', '', text) # 3,000 -> 3000
|
|
355
|
+
text = re.sub(r'\b0+(\d)', r'\1', text) # 007 -> 7 (not 0.5)
|
|
356
|
+
text = re.sub(r'(\d+)\.(\d*?)0+\b', r'\1.\2', text) # 3.50 -> 3.5
|
|
357
|
+
text = re.sub(r'(\d+)\.(?!\d)', r'\1', text) # 3. -> 3
|
|
358
|
+
return text
|
|
359
|
+
|
|
360
|
+
def _tokenize_for_comparison(self, text: str) -> set:
|
|
361
|
+
"""Tokenize text into a lowercase word set for comparison.
|
|
362
|
+
|
|
363
|
+
Number-aware: '3.5' and '3,000' are single tokens, and canonicalized
|
|
364
|
+
so '3.50' in the corpus equals '3.5' in a claim.
|
|
365
|
+
"""
|
|
366
|
+
return set(re.findall(self._TOKEN_RE,
|
|
367
|
+
self._canonicalize_numbers(text.lower())))
|
|
368
|
+
|
|
369
|
+
def _tokenize_ordered(self, text: str) -> List[str]:
|
|
370
|
+
"""Same tokens as _tokenize_for_comparison, in original order."""
|
|
371
|
+
return re.findall(self._TOKEN_RE,
|
|
372
|
+
self._canonicalize_numbers(text.lower()))
|
|
373
|
+
|
|
374
|
+
def _extract_numbers(self, text: str) -> List[str]:
|
|
375
|
+
"""Canonical number strings in text, in order of appearance."""
|
|
376
|
+
return self._NUMBER_RE.findall(self._canonicalize_numbers(text.lower()))
|
|
377
|
+
|
|
378
|
+
@staticmethod
|
|
379
|
+
def _contains_term(tokens: set, text_lower: str, term: str) -> bool:
|
|
380
|
+
"""Whole-word presence of ``term``.
|
|
381
|
+
|
|
382
|
+
Substring membership puts 'fast' inside 'breakfast' and 'exact'
|
|
383
|
+
inside 'exactly', inventing contradictions out of unrelated words.
|
|
384
|
+
"""
|
|
385
|
+
if re.fullmatch(r'\w+', term):
|
|
386
|
+
return term in tokens
|
|
387
|
+
# Multi-word / hyphenated terms: boundary match on the raw text.
|
|
388
|
+
return re.search(rf'\b{re.escape(term)}\b', text_lower) is not None
|
|
389
|
+
|
|
390
|
+
@staticmethod
|
|
391
|
+
def _negation_covers_shared(negations: set, ordered: List[str],
|
|
392
|
+
shared: set) -> bool:
|
|
393
|
+
"""True when a negation word sits within a few words of a shared term."""
|
|
394
|
+
for i, word in enumerate(ordered):
|
|
395
|
+
if word in negations:
|
|
396
|
+
if any(t in shared for t in ordered[i + 1:i + 5]):
|
|
397
|
+
return True
|
|
398
|
+
return False
|
|
399
|
+
|
|
400
|
+
def _is_negated_in_text(self, term: str, text: str) -> bool:
|
|
401
|
+
"""Check if a term is negated by a preceding phrase in the text."""
|
|
402
|
+
text_lower = text.lower()
|
|
403
|
+
term_lower = term.lower()
|
|
404
|
+
if term_lower not in text_lower:
|
|
405
|
+
return False
|
|
406
|
+
for phrase in self._NEGATION_PHRASES:
|
|
407
|
+
pattern = phrase + r'\s+(?:\w+\s+){0,3}' + re.escape(term_lower)
|
|
408
|
+
if re.search(pattern, text_lower):
|
|
409
|
+
return True
|
|
410
|
+
return False
|
|
411
|
+
|
|
412
|
+
def _has_conflict(self, claim: str, evidence: str) -> bool:
|
|
413
|
+
"""
|
|
414
|
+
True when this evidence asserts the opposite of the claim.
|
|
415
|
+
|
|
416
|
+
Detects two asymmetries: a negation carried by exactly one side while
|
|
417
|
+
the rest of the content matches, and an antonym pair where each side
|
|
418
|
+
carries a different member.
|
|
419
|
+
|
|
420
|
+
This is an asymmetry detector, not a general contradiction detector.
|
|
421
|
+
A single-verb reversal ("increases" versus "suppresses") carries no
|
|
422
|
+
negation and no listed antonym pair, so it is not caught here; the
|
|
423
|
+
licensing gate in _unexplained_terms is what refuses such a claim.
|
|
424
|
+
"""
|
|
425
|
+
claim_words = self._tokenize_for_comparison(claim)
|
|
426
|
+
evidence_words = self._tokenize_for_comparison(evidence)
|
|
427
|
+
claim_ordered = self._tokenize_ordered(claim)
|
|
428
|
+
evidence_ordered = self._tokenize_ordered(evidence)
|
|
429
|
+
|
|
430
|
+
claim_negations = claim_words & self._NEGATION_WORDS
|
|
431
|
+
evidence_negations = evidence_words & self._NEGATION_WORDS
|
|
432
|
+
content_claim = claim_words - self._NEGATION_WORDS
|
|
433
|
+
content_evidence = evidence_words - self._NEGATION_WORDS
|
|
434
|
+
shared = content_claim & content_evidence
|
|
435
|
+
|
|
436
|
+
# A negation only contradicts when it actually negates the content the
|
|
437
|
+
# two texts share. A bare set difference fired on any negation word
|
|
438
|
+
# anywhere: 'The kit has no case included. The charger is fast.' was
|
|
439
|
+
# judged to contradict evidence that only says 'the charger is fast'.
|
|
440
|
+
if shared:
|
|
441
|
+
claim_negates_shared = self._negation_covers_shared(
|
|
442
|
+
claim_negations, claim_ordered, shared)
|
|
443
|
+
evidence_negates_shared = self._negation_covers_shared(
|
|
444
|
+
evidence_negations, evidence_ordered, shared)
|
|
445
|
+
if claim_negates_shared != evidence_negates_shared:
|
|
446
|
+
return True
|
|
447
|
+
|
|
448
|
+
claim_lower = claim.lower()
|
|
449
|
+
evidence_lower = evidence.lower()
|
|
450
|
+
for a, b in self._ANTONYM_PAIRS:
|
|
451
|
+
a_in_claim = self._contains_term(claim_words, claim_lower, a)
|
|
452
|
+
b_in_claim = self._contains_term(claim_words, claim_lower, b)
|
|
453
|
+
a_in_ev = self._contains_term(evidence_words, evidence_lower, a)
|
|
454
|
+
b_in_ev = self._contains_term(evidence_words, evidence_lower, b)
|
|
455
|
+
|
|
456
|
+
# Each side asserts a different member of the pair.
|
|
457
|
+
if a_in_claim and not b_in_claim and b_in_ev and not a_in_ev:
|
|
458
|
+
return True
|
|
459
|
+
if b_in_claim and not a_in_claim and a_in_ev and not b_in_ev:
|
|
460
|
+
return True
|
|
461
|
+
|
|
462
|
+
# Evidence carries both, one of them negated, and the claim asserts
|
|
463
|
+
# the negated member outright.
|
|
464
|
+
if a_in_ev and b_in_ev:
|
|
465
|
+
if a_in_claim and not b_in_claim and self._is_negated_in_text(a, evidence):
|
|
466
|
+
return True
|
|
467
|
+
if b_in_claim and not a_in_claim and self._is_negated_in_text(b, evidence):
|
|
468
|
+
return True
|
|
469
|
+
|
|
470
|
+
return False
|
|
471
|
+
|
|
472
|
+
def _normalize_terms(self, terms: Set[str]) -> Set[str]:
|
|
473
|
+
"""
|
|
474
|
+
Widen a term set to everything it licenses, using the same expansion
|
|
475
|
+
retrieval uses: the term itself, its morphological forms, and its
|
|
476
|
+
synonym group. Both sides of the comparison go through this, so
|
|
477
|
+
'embeddings' in a claim matches 'embedding' in the evidence.
|
|
478
|
+
"""
|
|
479
|
+
out: Set[str] = set()
|
|
480
|
+
for term in terms:
|
|
481
|
+
out.add(term)
|
|
482
|
+
out.update(self.semantic_expander.morphological_variants(term))
|
|
483
|
+
group = self.semantic_expander.synonym_groups.get(term)
|
|
484
|
+
if group is not None:
|
|
485
|
+
out.update(group.all_terms())
|
|
486
|
+
return out
|
|
487
|
+
|
|
488
|
+
def _evidence_vocabulary(self, result: SearchResult) -> Set[str]:
|
|
489
|
+
"""Every content term one passage can account for."""
|
|
490
|
+
words = self._tokenize_for_comparison(result.content)
|
|
491
|
+
return self._normalize_terms(words - self._STOP_WORDS)
|
|
492
|
+
|
|
493
|
+
def _best_passage_grounding(self, claim: str,
|
|
494
|
+
supporting: List[SearchResult]
|
|
495
|
+
) -> tuple:
|
|
496
|
+
"""
|
|
497
|
+
``(unexplained_terms, best_passage_vocabulary, best_passage)``.
|
|
498
|
+
|
|
499
|
+
Each supporting passage is tested alone and the best (fewest unexplained
|
|
500
|
+
terms) wins; ties prefer the higher-scoring passage, so the result is
|
|
501
|
+
reproducible. Grounding means *some* passage entails the claim, which one
|
|
502
|
+
passage must do on its own. The winning passage is returned with its
|
|
503
|
+
vocabulary, so span-level output and number checking judge the claim
|
|
504
|
+
against the same passage the gate used.
|
|
505
|
+
|
|
506
|
+
A hallucinated sentence usually reuses most of a real sentence and swaps
|
|
507
|
+
in one word. Token overlap stays high, so overlap alone cannot find it;
|
|
508
|
+
what survives is the word that came from nowhere. An antonym list cannot
|
|
509
|
+
catch it either, because that word contradicts nothing - it is simply
|
|
510
|
+
absent from the corpus. Per-term licensing does, and needs no list.
|
|
511
|
+
"""
|
|
512
|
+
if not supporting:
|
|
513
|
+
# Nothing was retrieved, so nothing in the claim is explained.
|
|
514
|
+
return self._unexplained_terms(claim, set()), set(), None
|
|
515
|
+
|
|
516
|
+
scored = [
|
|
517
|
+
(self._unexplained_terms(claim, self._evidence_vocabulary(result)),
|
|
518
|
+
self._relevance(result),
|
|
519
|
+
result)
|
|
520
|
+
for result in supporting
|
|
521
|
+
]
|
|
522
|
+
# Fewest unexplained terms wins; ties go to the higher-scoring passage.
|
|
523
|
+
unexplained, _, best_result = min(
|
|
524
|
+
scored, key=lambda triple: (len(triple[0]), -triple[1]))
|
|
525
|
+
return unexplained, self._evidence_vocabulary(best_result), best_result
|
|
526
|
+
|
|
527
|
+
def _unverified_numbers(self, claim: str, best_passage: Optional[SearchResult]
|
|
528
|
+
) -> List[str]:
|
|
529
|
+
"""Numbers in the claim the best supporting passage does not contain.
|
|
530
|
+
|
|
531
|
+
Numbers are compared canonically ('3,000' == '3000', '3.50' == '3.5',
|
|
532
|
+
'007' == '7') and per passage, like every other term: the number must
|
|
533
|
+
come from the same passage that accounts for the words. There is no
|
|
534
|
+
fuzzy path for numbers - a claim of '5000 RPM' against a corpus of
|
|
535
|
+
'3000 RPM' is a different fact, not a synonym away.
|
|
536
|
+
"""
|
|
537
|
+
claim_numbers = self._extract_numbers(claim)
|
|
538
|
+
if not claim_numbers:
|
|
539
|
+
return []
|
|
540
|
+
if best_passage is None:
|
|
541
|
+
return claim_numbers
|
|
542
|
+
present = set(self._extract_numbers(best_passage.content))
|
|
543
|
+
# Keep order of appearance, drop duplicates.
|
|
544
|
+
seen = set()
|
|
545
|
+
out = []
|
|
546
|
+
for number in claim_numbers:
|
|
547
|
+
if number not in present and number not in seen:
|
|
548
|
+
seen.add(number)
|
|
549
|
+
out.append(number)
|
|
550
|
+
return out
|
|
551
|
+
|
|
552
|
+
def _grounding_spans(self, claim_text: str,
|
|
553
|
+
evidence_vocab: Set[str]) -> List[GroundingSpan]:
|
|
554
|
+
"""Mark the claim token by token: licensed by the best passage, or not.
|
|
555
|
+
|
|
556
|
+
Contiguous tokens of the same status merge into one span. Stop words
|
|
557
|
+
and negation words carry no grounding status of their own; they glue
|
|
558
|
+
onto the surrounding spans, so the spans tile the claim from the first
|
|
559
|
+
content word to the end of the text.
|
|
560
|
+
"""
|
|
561
|
+
runs: List[List[Any]] = [] # [grounded, start, end, terms]
|
|
562
|
+
for match in self._TOKEN_RE.finditer(claim_text):
|
|
563
|
+
token = match.group(0).lower()
|
|
564
|
+
if any(ch.isdigit() for ch in token):
|
|
565
|
+
# '3,000' is one token here, but the evidence vocabulary
|
|
566
|
+
# holds canonical forms: compare '3000' to '3000'.
|
|
567
|
+
token = self._canonicalize_numbers(token)
|
|
568
|
+
if token in self._STOP_WORDS or token in self._NEGATION_WORDS:
|
|
569
|
+
if runs:
|
|
570
|
+
runs[-1][2] = match.end()
|
|
571
|
+
continue
|
|
572
|
+
grounded = bool(self._normalize_terms({token}) & evidence_vocab)
|
|
573
|
+
if runs and runs[-1][0] == grounded:
|
|
574
|
+
runs[-1][2] = match.end()
|
|
575
|
+
else:
|
|
576
|
+
if runs:
|
|
577
|
+
# Punctuation between spans belongs to the previous one.
|
|
578
|
+
runs[-1][2] = match.start()
|
|
579
|
+
runs.append([grounded, match.start(), match.end(), []])
|
|
580
|
+
if not grounded:
|
|
581
|
+
runs[-1][3].append(token)
|
|
582
|
+
if not runs:
|
|
583
|
+
return []
|
|
584
|
+
runs[-1][2] = len(claim_text)
|
|
585
|
+
return [
|
|
586
|
+
GroundingSpan(
|
|
587
|
+
start=start, end=end, text=claim_text[start:end],
|
|
588
|
+
grounded=grounded, terms=terms,
|
|
589
|
+
)
|
|
590
|
+
for grounded, start, end, terms in runs
|
|
591
|
+
]
|
|
592
|
+
|
|
593
|
+
def _unexplained_terms(self, claim: str, evidence_vocab: Set[str]) -> Set[str]:
|
|
594
|
+
"""
|
|
595
|
+
Content terms of ``claim`` not licensed by ``evidence_vocab``.
|
|
596
|
+
|
|
597
|
+
A term is licensed when any of its own forms — the term itself, its
|
|
598
|
+
morphological variants, or a member of its synonym group — is present.
|
|
599
|
+
Both sides pass through _normalize_terms, so 'embeddings' in a claim is
|
|
600
|
+
satisfied by 'embedding' in the passage.
|
|
601
|
+
"""
|
|
602
|
+
unexplained: Set[str] = set()
|
|
603
|
+
for term in self._tokenize_for_comparison(claim) - self._STOP_WORDS:
|
|
604
|
+
# One form in the evidence is enough; a claim term is not required
|
|
605
|
+
# to appear in every one of its own forms.
|
|
606
|
+
if not (self._normalize_terms({term}) & evidence_vocab):
|
|
607
|
+
unexplained.add(term)
|
|
608
|
+
return unexplained
|
|
609
|
+
|
|
610
|
+
def _calculate_confidence(self, claim: Claim,
|
|
611
|
+
supporting: List[SearchResult],
|
|
612
|
+
contradicting: List[SearchResult],
|
|
613
|
+
unexplained: Set[str]) -> float:
|
|
614
|
+
"""
|
|
615
|
+
Confidence, damped by how much of the claim the corpus cannot explain.
|
|
616
|
+
|
|
617
|
+
Retrieval scores are already capped at 1.0, so confidence without this
|
|
618
|
+
damping reached 1.0 for sentences containing a fabricated term. A claim
|
|
619
|
+
is trusted in proportion to the share of its own terms the evidence
|
|
620
|
+
accounts for.
|
|
621
|
+
"""
|
|
622
|
+
if contradicting:
|
|
623
|
+
# Contradicting evidence dominates; confidence is near zero.
|
|
624
|
+
return max(0.0, 0.1 - 0.05 * len(contradicting))
|
|
625
|
+
|
|
626
|
+
if not supporting:
|
|
627
|
+
return 0.0
|
|
628
|
+
|
|
629
|
+
claim_terms = self._tokenize_for_comparison(claim.text) - self._STOP_WORDS
|
|
630
|
+
if not claim_terms:
|
|
631
|
+
return 0.0
|
|
632
|
+
|
|
633
|
+
# Base confidence from the best supporting passage.
|
|
634
|
+
base = max(self._relevance(s) for s in supporting)
|
|
635
|
+
base += min(0.2, len(supporting) * 0.05) # independent corroboration
|
|
636
|
+
|
|
637
|
+
coverage = (len(claim_terms) - len(unexplained & claim_terms)) / len(claim_terms)
|
|
638
|
+
return max(0.0, min(1.0, base * coverage))
|
|
639
|
+
|
|
640
|
+
def _suggest_repair(self, claim_text: str, unexplained: Set[str],
|
|
641
|
+
unverified_numbers: Set[str],
|
|
642
|
+
best_result: SearchResult,
|
|
643
|
+
best_vocab: Set[str]) -> Dict[str, Any]:
|
|
644
|
+
"""Propose a corrected claim from the best supporting passage.
|
|
645
|
+
|
|
646
|
+
For every refused term (unexplained word or unverified number) the
|
|
647
|
+
claim's licensed content neighbors anchor into the passage; passage
|
|
648
|
+
tokens sitting within two words of an anchor and absent from the claim
|
|
649
|
+
are replacement candidates. Closest to the anchor wins, ties broken by
|
|
650
|
+
passage position - no model, no generation, fully reproducible.
|
|
651
|
+
|
|
652
|
+
Refused terms with no licensed neighbor stay untouched: the repair is
|
|
653
|
+
honest about what it could not fix. The passage itself rides along as
|
|
654
|
+
the citation the corrected sentence must be checked against.
|
|
655
|
+
"""
|
|
656
|
+
def canonical(token: str) -> str:
|
|
657
|
+
token = token.lower()
|
|
658
|
+
if any(ch.isdigit() for ch in token):
|
|
659
|
+
token = self._canonicalize_numbers(token)
|
|
660
|
+
return token
|
|
661
|
+
|
|
662
|
+
def is_content(token: str) -> bool:
|
|
663
|
+
return (token not in self._STOP_WORDS
|
|
664
|
+
and token not in self._NEGATION_WORDS)
|
|
665
|
+
|
|
666
|
+
def is_licensed(token: str) -> bool:
|
|
667
|
+
return bool(self._normalize_terms({token}) & best_vocab)
|
|
668
|
+
|
|
669
|
+
claim_tokens = [(canonical(m.group(0)), m.start(), m.end())
|
|
670
|
+
for m in self._TOKEN_RE.finditer(claim_text)]
|
|
671
|
+
claim_words = {tok for tok, _, _ in claim_tokens}
|
|
672
|
+
repairable = set(unexplained) | set(unverified_numbers)
|
|
673
|
+
|
|
674
|
+
passage = [canonical(m.group(0))
|
|
675
|
+
for m in self._TOKEN_RE.finditer(best_result.content)]
|
|
676
|
+
positions: Dict[str, List[int]] = {}
|
|
677
|
+
for i, tok in enumerate(passage):
|
|
678
|
+
positions.setdefault(tok, []).append(i)
|
|
679
|
+
|
|
680
|
+
rep_map: Dict[str, str] = {}
|
|
681
|
+
first_at: Dict[str, int] = {}
|
|
682
|
+
for target in sorted(repairable):
|
|
683
|
+
best = None # (anchor distance, passage position, candidate)
|
|
684
|
+
for i, (tok, start, _) in enumerate(claim_tokens):
|
|
685
|
+
if tok != target:
|
|
686
|
+
continue
|
|
687
|
+
first_at.setdefault(target, start)
|
|
688
|
+
for j in range(max(0, i - 2), min(len(claim_tokens), i + 3)):
|
|
689
|
+
if j == i:
|
|
690
|
+
continue
|
|
691
|
+
anchor = claim_tokens[j][0]
|
|
692
|
+
if not is_content(anchor) or not is_licensed(anchor):
|
|
693
|
+
continue
|
|
694
|
+
for pi in positions.get(anchor, []):
|
|
695
|
+
for pj in range(max(0, pi - 2), min(len(passage), pi + 3)):
|
|
696
|
+
cand = passage[pj]
|
|
697
|
+
if (cand in claim_words or not is_content(cand)
|
|
698
|
+
or cand in repairable):
|
|
699
|
+
continue
|
|
700
|
+
ranked = (abs(pj - pi), pi, cand)
|
|
701
|
+
if best is None or ranked < best:
|
|
702
|
+
best = ranked
|
|
703
|
+
if best is not None:
|
|
704
|
+
rep_map[target] = best[2]
|
|
705
|
+
|
|
706
|
+
corrected = claim_text
|
|
707
|
+
if rep_map:
|
|
708
|
+
for tok, start, end in reversed(claim_tokens):
|
|
709
|
+
if tok in rep_map:
|
|
710
|
+
corrected = corrected[:start] + rep_map[tok] + corrected[end:]
|
|
711
|
+
|
|
712
|
+
return {
|
|
713
|
+
'text': corrected,
|
|
714
|
+
'replacements': [
|
|
715
|
+
{'from': target, 'to': rep_map[target]}
|
|
716
|
+
for target in sorted(rep_map, key=lambda t: first_at[t])
|
|
717
|
+
],
|
|
718
|
+
'source': {
|
|
719
|
+
'content': best_result.content,
|
|
720
|
+
'feature_id': best_result.feature_id,
|
|
721
|
+
'path': best_result.path,
|
|
722
|
+
'document_id': best_result.metadata.get('document_id'),
|
|
723
|
+
},
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
def detect_hallucinations(self, text: str) -> List[Dict[str, Any]]:
|
|
727
|
+
"""
|
|
728
|
+
Detect potentially hallucinated content in text.
|
|
729
|
+
|
|
730
|
+
Returns list of unverified claims that may be hallucinations.
|
|
731
|
+
"""
|
|
732
|
+
results = self.verify_text(text)
|
|
733
|
+
|
|
734
|
+
hallucinations = []
|
|
735
|
+
for result in results:
|
|
736
|
+
if not result.is_verified and result.confidence < 0.5:
|
|
737
|
+
hallucinations.append({
|
|
738
|
+
'claim': result.claim_text,
|
|
739
|
+
'confidence': result.confidence,
|
|
740
|
+
'unexplained_terms': result.unexplained_terms,
|
|
741
|
+
'spans': [s.to_dict() for s in result.spans],
|
|
742
|
+
'unverified_numbers': result.unverified_numbers,
|
|
743
|
+
'repair': result.repair,
|
|
744
|
+
'reason': 'No supporting evidence found in knowledge base',
|
|
745
|
+
'suggestion': 'Verify this claim against source documents'
|
|
746
|
+
})
|
|
747
|
+
|
|
748
|
+
return hallucinations
|
|
749
|
+
|
|
750
|
+
def generate_citation_report(self, text: str) -> Dict[str, Any]:
|
|
751
|
+
"""
|
|
752
|
+
Generate a comprehensive citation report for text.
|
|
753
|
+
|
|
754
|
+
Shows which parts of the text are grounded and which are not.
|
|
755
|
+
"""
|
|
756
|
+
results = self.verify_text(text)
|
|
757
|
+
|
|
758
|
+
report = {
|
|
759
|
+
'total_claims': len(results),
|
|
760
|
+
'verified_claims': sum(1 for r in results if r.is_verified),
|
|
761
|
+
'unverified_claims': sum(1 for r in results if not r.is_verified),
|
|
762
|
+
'average_confidence': sum(r.confidence for r in results) / len(results) if results else 0,
|
|
763
|
+
'claims': []
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
for result in results:
|
|
767
|
+
report['claims'].append({
|
|
768
|
+
'text': result.claim_text,
|
|
769
|
+
'verified': result.is_verified,
|
|
770
|
+
'confidence': result.confidence,
|
|
771
|
+
'sources': result.source_references
|
|
772
|
+
})
|
|
773
|
+
|
|
774
|
+
return report
|