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,455 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Main StructureRAG class - the primary interface for the library.
|
|
3
|
+
|
|
4
|
+
This provides a unified API for:
|
|
5
|
+
- Building HSF from documents
|
|
6
|
+
- Searching with structure-based retrieval
|
|
7
|
+
- Grounding LLM responses
|
|
8
|
+
- Generating citations
|
|
9
|
+
|
|
10
|
+
One retriever, one verifier and one citation engine serve the whole collection.
|
|
11
|
+
BM25 statistics are therefore computed over every document, so a hit from one
|
|
12
|
+
document and a hit from another are directly comparable and can be ranked
|
|
13
|
+
against each other.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from typing import List, Dict, Optional, Any
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
|
|
19
|
+
from .core.hsf import HolisticStructuralForm
|
|
20
|
+
from .core.builder import StructureBuilder
|
|
21
|
+
from .core.reasoner import MultiHopReasoner, ReasoningResult
|
|
22
|
+
from .grounding.retriever import StructureRetriever, SearchResult
|
|
23
|
+
from .grounding.verifier import GroundingVerifier, Claim
|
|
24
|
+
from .grounding.citation import CitationEngine, Citation
|
|
25
|
+
from .loaders.text import load_text_file
|
|
26
|
+
from .loaders.pdf import load_pdf
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class GroundedAnswer:
|
|
31
|
+
"""A complete answer with grounding information."""
|
|
32
|
+
answer: str
|
|
33
|
+
is_fully_grounded: bool
|
|
34
|
+
grounding_confidence: float
|
|
35
|
+
citations: List[Citation]
|
|
36
|
+
hallucinated_segments: List[Dict[str, Any]]
|
|
37
|
+
metadata: Dict[str, Any]
|
|
38
|
+
|
|
39
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
40
|
+
return {
|
|
41
|
+
'answer': self.answer,
|
|
42
|
+
'is_fully_grounded': self.is_fully_grounded,
|
|
43
|
+
'grounding_confidence': self.grounding_confidence,
|
|
44
|
+
'citations': [c.to_dict() for c in self.citations],
|
|
45
|
+
'hallucinated_segments': self.hallucinated_segments,
|
|
46
|
+
'metadata': self.metadata
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class StructureRAG:
|
|
51
|
+
"""
|
|
52
|
+
Main interface for StructureRAG - Deterministic RAG with HSF.
|
|
53
|
+
|
|
54
|
+
Usage:
|
|
55
|
+
rag = StructureRAG()
|
|
56
|
+
rag.add_document("path/to/document.pdf")
|
|
57
|
+
answer = rag.query("Your question here")
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
def __init__(self, reranker: Optional[Any] = None):
|
|
61
|
+
self.documents: Dict[str, HolisticStructuralForm] = {}
|
|
62
|
+
self.reasoners: Dict[str, MultiHopReasoner] = {}
|
|
63
|
+
self._doc_counter = 0
|
|
64
|
+
|
|
65
|
+
self.retriever = StructureRetriever({}, reranker=reranker)
|
|
66
|
+
self.verifier = GroundingVerifier(retriever=self.retriever)
|
|
67
|
+
self.citation_engine = CitationEngine(None)
|
|
68
|
+
|
|
69
|
+
def _next_doc_id(self) -> str:
|
|
70
|
+
"""Monotonic auto ID. A plain ``len(documents) + 1`` reuses an ID
|
|
71
|
+
after remove_document and collides on the next add."""
|
|
72
|
+
while True:
|
|
73
|
+
self._doc_counter += 1
|
|
74
|
+
candidate = f"doc_{self._doc_counter}"
|
|
75
|
+
if candidate not in self.documents:
|
|
76
|
+
return candidate
|
|
77
|
+
|
|
78
|
+
def add_document(self, content: str, document_id: str = None,
|
|
79
|
+
title: str = "") -> str:
|
|
80
|
+
"""
|
|
81
|
+
Add a document to the knowledge base.
|
|
82
|
+
|
|
83
|
+
Args:
|
|
84
|
+
content: The document text content
|
|
85
|
+
document_id: Optional ID (auto-generated if not provided)
|
|
86
|
+
title: Optional document title
|
|
87
|
+
|
|
88
|
+
Returns:
|
|
89
|
+
The document ID
|
|
90
|
+
"""
|
|
91
|
+
doc_id = document_id or self._next_doc_id()
|
|
92
|
+
|
|
93
|
+
if doc_id in self.documents:
|
|
94
|
+
raise ValueError(f"Document '{doc_id}' already exists. Use a new ID or remove it first.")
|
|
95
|
+
|
|
96
|
+
builder = StructureBuilder(document_id=doc_id)
|
|
97
|
+
hsf = builder.build(content, title=title)
|
|
98
|
+
|
|
99
|
+
self.documents[doc_id] = hsf
|
|
100
|
+
self.retriever.add_document(hsf, doc_id=doc_id)
|
|
101
|
+
|
|
102
|
+
reasoner = MultiHopReasoner(hsf)
|
|
103
|
+
reasoner.build()
|
|
104
|
+
self.reasoners[doc_id] = reasoner
|
|
105
|
+
|
|
106
|
+
return doc_id
|
|
107
|
+
|
|
108
|
+
def add_file(self, filepath: str, document_id: str = None,
|
|
109
|
+
title: str = "") -> str:
|
|
110
|
+
"""
|
|
111
|
+
Add a document from a file path (text or PDF).
|
|
112
|
+
|
|
113
|
+
Args:
|
|
114
|
+
filepath: Path to a .txt or .pdf file
|
|
115
|
+
document_id: Optional ID (auto-generated if not provided)
|
|
116
|
+
title: Optional document title (defaults to filename)
|
|
117
|
+
|
|
118
|
+
Returns:
|
|
119
|
+
The document ID
|
|
120
|
+
"""
|
|
121
|
+
import os
|
|
122
|
+
ext = os.path.splitext(filepath)[1].lower()
|
|
123
|
+
if ext == '.pdf':
|
|
124
|
+
content = load_pdf(filepath)
|
|
125
|
+
else:
|
|
126
|
+
content = load_text_file(filepath)
|
|
127
|
+
if not title:
|
|
128
|
+
title = os.path.basename(filepath)
|
|
129
|
+
return self.add_document(content, document_id=document_id, title=title)
|
|
130
|
+
|
|
131
|
+
def remove_document(self, document_id: str) -> bool:
|
|
132
|
+
"""
|
|
133
|
+
Remove a document from the knowledge base.
|
|
134
|
+
|
|
135
|
+
Args:
|
|
136
|
+
document_id: ID of the document to remove
|
|
137
|
+
|
|
138
|
+
Returns:
|
|
139
|
+
True if the document was removed, False if not found
|
|
140
|
+
"""
|
|
141
|
+
if document_id not in self.documents:
|
|
142
|
+
return False
|
|
143
|
+
|
|
144
|
+
del self.documents[document_id]
|
|
145
|
+
self.reasoners.pop(document_id, None)
|
|
146
|
+
self.retriever.remove_document(document_id)
|
|
147
|
+
return True
|
|
148
|
+
|
|
149
|
+
def get_document(self, document_id: str) -> Optional[HolisticStructuralForm]:
|
|
150
|
+
"""Get a document by ID."""
|
|
151
|
+
return self.documents.get(document_id)
|
|
152
|
+
|
|
153
|
+
def reconstruct_text(self, document_id: str) -> Optional[str]:
|
|
154
|
+
"""Rebuild a document's exact source text from its HSF."""
|
|
155
|
+
hsf = self.documents.get(document_id)
|
|
156
|
+
return hsf.reconstruct_text() if hsf is not None else None
|
|
157
|
+
|
|
158
|
+
def list_documents(self) -> List[Dict[str, Any]]:
|
|
159
|
+
"""List all documents in the knowledge base."""
|
|
160
|
+
return [
|
|
161
|
+
{
|
|
162
|
+
'id': doc_id,
|
|
163
|
+
'title': hsf.title,
|
|
164
|
+
'structure': hsf.get_structure_summary()
|
|
165
|
+
}
|
|
166
|
+
for doc_id, hsf in self.documents.items()
|
|
167
|
+
]
|
|
168
|
+
|
|
169
|
+
def search(self, query: str, document_ids: List[str] = None,
|
|
170
|
+
top_k: int = 5, fuzzy_threshold: float = 0.20,
|
|
171
|
+
normalize: bool = True) -> List[SearchResult]:
|
|
172
|
+
"""
|
|
173
|
+
Search across documents using structure-based retrieval.
|
|
174
|
+
|
|
175
|
+
Args:
|
|
176
|
+
query: Search query (natural language or keywords)
|
|
177
|
+
document_ids: Specific documents to search (all if None)
|
|
178
|
+
top_k: Maximum results to return
|
|
179
|
+
fuzzy_threshold: Minimum score threshold
|
|
180
|
+
normalize: Strip stop/question words before searching
|
|
181
|
+
|
|
182
|
+
Returns:
|
|
183
|
+
List of search results, ranked against corpus-wide BM25 statistics
|
|
184
|
+
"""
|
|
185
|
+
effective_query = self._normalize_query(query) if normalize else query
|
|
186
|
+
|
|
187
|
+
return self.retriever.search(
|
|
188
|
+
effective_query, top_k=top_k, fuzzy_threshold=fuzzy_threshold,
|
|
189
|
+
document_ids=document_ids,
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
def search_documents(self, query: str, document_ids: List[str] = None,
|
|
193
|
+
top_k: int = 5, normalize: bool = True) -> List[SearchResult]:
|
|
194
|
+
"""
|
|
195
|
+
Search for whole DOCUMENTS, ranked with document-level BM25.
|
|
196
|
+
|
|
197
|
+
Where :meth:`search` returns sentences (for claim grounding and
|
|
198
|
+
citations), this ranks documents the way textbook BM25 does: a
|
|
199
|
+
document's term frequency accumulates across all of its sentences.
|
|
200
|
+
Use it for corpus-level retrieval ("which documents discuss X?");
|
|
201
|
+
keep using search() when results must point at exact sentences.
|
|
202
|
+
|
|
203
|
+
Args:
|
|
204
|
+
query: Search query (natural language or keywords)
|
|
205
|
+
document_ids: Specific documents to search (all if None)
|
|
206
|
+
top_k: Maximum results to return
|
|
207
|
+
normalize: Strip stop/question words before searching
|
|
208
|
+
|
|
209
|
+
Returns:
|
|
210
|
+
SearchResult per document (feature_type 'document'), ranked best
|
|
211
|
+
first. Each result's metadata carries the document_id and its
|
|
212
|
+
score is the same monotonic squash as search().
|
|
213
|
+
"""
|
|
214
|
+
effective_query = self._normalize_query(query) if normalize else query
|
|
215
|
+
|
|
216
|
+
return self.retriever.search_documents(
|
|
217
|
+
effective_query, top_k=top_k, document_ids=document_ids,
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
def _normalize_query(self, query: str) -> str:
|
|
221
|
+
"""
|
|
222
|
+
Normalize query by removing stop words and question words.
|
|
223
|
+
|
|
224
|
+
This improves search accuracy for natural language questions.
|
|
225
|
+
"""
|
|
226
|
+
import re
|
|
227
|
+
|
|
228
|
+
# Common English stop words and question words
|
|
229
|
+
stop_words = {
|
|
230
|
+
'what', 'which', 'who', 'whom', 'whose', 'when', 'where', 'why', 'how',
|
|
231
|
+
'is', 'are', 'was', 'were', 'be', 'been', 'being',
|
|
232
|
+
'do', 'does', 'did', 'done', 'doing',
|
|
233
|
+
'have', 'has', 'had', 'having',
|
|
234
|
+
'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for',
|
|
235
|
+
'of', 'with', 'by', 'from', 'as', 'into', 'through', 'during',
|
|
236
|
+
'this', 'that', 'these', 'those', 'it', 'its'
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
# Tokenize and filter
|
|
240
|
+
words = re.findall(r'\b\w+\b', query.lower())
|
|
241
|
+
filtered = [w for w in words if w not in stop_words]
|
|
242
|
+
|
|
243
|
+
return ' '.join(filtered) if filtered else query
|
|
244
|
+
|
|
245
|
+
def query(self, query: str, llm_callback=None,
|
|
246
|
+
document_ids: List[str] = None, fuzzy_threshold: float = 0.20) -> GroundedAnswer:
|
|
247
|
+
"""
|
|
248
|
+
Answer a query with grounding and verification.
|
|
249
|
+
|
|
250
|
+
Pipeline:
|
|
251
|
+
1. Search for relevant passages
|
|
252
|
+
2. Generate answer (optionally using LLM)
|
|
253
|
+
3. Verify the generated answer against the corpus
|
|
254
|
+
4. Generate citations from the verifying evidence
|
|
255
|
+
|
|
256
|
+
Verification always runs on the answer that is about to be returned.
|
|
257
|
+
Previously it was skipped whenever more than one passage was retrieved,
|
|
258
|
+
which reported unverified answers as fully grounded.
|
|
259
|
+
|
|
260
|
+
Args:
|
|
261
|
+
query: The question to answer
|
|
262
|
+
llm_callback: Optional function that generates answer from query
|
|
263
|
+
If None, returns the top retrieved passage as answer
|
|
264
|
+
document_ids: Documents to search
|
|
265
|
+
fuzzy_threshold: Minimum similarity score for retrieval
|
|
266
|
+
|
|
267
|
+
Returns:
|
|
268
|
+
GroundedAnswer with citations and verification status
|
|
269
|
+
"""
|
|
270
|
+
search_results = self.search(
|
|
271
|
+
query, document_ids=document_ids, top_k=5, fuzzy_threshold=fuzzy_threshold
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
if not search_results:
|
|
275
|
+
return GroundedAnswer(
|
|
276
|
+
answer="No relevant information found.",
|
|
277
|
+
is_fully_grounded=False,
|
|
278
|
+
grounding_confidence=0.0,
|
|
279
|
+
citations=[],
|
|
280
|
+
hallucinated_segments=[],
|
|
281
|
+
metadata={'query': query, 'search_results': 0}
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
answer = (
|
|
285
|
+
llm_callback(query, search_results) if llm_callback
|
|
286
|
+
else search_results[0].content
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
verification = self.verifier.verify_claim(Claim(
|
|
290
|
+
id='answer', text=answer, start_pos=0, end_pos=len(answer)
|
|
291
|
+
))
|
|
292
|
+
|
|
293
|
+
citations = [
|
|
294
|
+
self.citation_engine.create_citation(self._result_from_reference(ref))
|
|
295
|
+
for ref in verification.source_references
|
|
296
|
+
]
|
|
297
|
+
|
|
298
|
+
hallucinated = [] if verification.is_verified else [{
|
|
299
|
+
'segment': answer,
|
|
300
|
+
'reason': 'Corpus does not account for every term in this claim',
|
|
301
|
+
'confidence': verification.confidence,
|
|
302
|
+
'unexplained_terms': verification.unexplained_terms,
|
|
303
|
+
}]
|
|
304
|
+
|
|
305
|
+
return GroundedAnswer(
|
|
306
|
+
answer=answer,
|
|
307
|
+
is_fully_grounded=verification.is_verified,
|
|
308
|
+
grounding_confidence=verification.confidence,
|
|
309
|
+
citations=citations,
|
|
310
|
+
hallucinated_segments=hallucinated,
|
|
311
|
+
metadata={
|
|
312
|
+
'query': query,
|
|
313
|
+
'search_results': len(search_results),
|
|
314
|
+
'retrieval_top_score': search_results[0].score,
|
|
315
|
+
}
|
|
316
|
+
)
|
|
317
|
+
|
|
318
|
+
def verify_answer(self, answer: str,
|
|
319
|
+
document_ids: List[str] = None) -> Dict[str, Any]:
|
|
320
|
+
"""
|
|
321
|
+
Verify an answer against the knowledge base.
|
|
322
|
+
|
|
323
|
+
Args:
|
|
324
|
+
answer: The answer text to verify
|
|
325
|
+
document_ids: Documents to verify against
|
|
326
|
+
|
|
327
|
+
Returns:
|
|
328
|
+
Verification report
|
|
329
|
+
"""
|
|
330
|
+
if document_ids is not None:
|
|
331
|
+
unknown = [d for d in document_ids if d not in self.documents]
|
|
332
|
+
if unknown:
|
|
333
|
+
raise KeyError(f"Unknown document ids: {unknown}")
|
|
334
|
+
|
|
335
|
+
# Scoping to documents means a scoped verifier: the corpus retriever is
|
|
336
|
+
# reused, only the evidence window narrows.
|
|
337
|
+
verifier = self.verifier if document_ids is None else GroundingVerifier(
|
|
338
|
+
retriever=self.retriever, document_ids=document_ids
|
|
339
|
+
)
|
|
340
|
+
results = verifier.verify_text(answer)
|
|
341
|
+
|
|
342
|
+
report: Dict[str, Any] = {
|
|
343
|
+
'answer': answer,
|
|
344
|
+
'documents_checked': len(document_ids) if document_ids is not None else len(self.documents),
|
|
345
|
+
'verified_claims': sum(1 for r in results if r.is_verified),
|
|
346
|
+
'unverified_claims': sum(1 for r in results if not r.is_verified),
|
|
347
|
+
'hallucinations': [],
|
|
348
|
+
'citations': []
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
for result in results:
|
|
352
|
+
if result.is_verified:
|
|
353
|
+
for ref in result.source_references:
|
|
354
|
+
report['citations'].append(
|
|
355
|
+
self.citation_engine.create_citation(self._result_from_reference(ref))
|
|
356
|
+
)
|
|
357
|
+
else:
|
|
358
|
+
report['hallucinations'].append({
|
|
359
|
+
'claim': result.claim_text,
|
|
360
|
+
'confidence': result.confidence,
|
|
361
|
+
'unexplained_terms': result.unexplained_terms,
|
|
362
|
+
'spans': [s.to_dict() for s in result.spans],
|
|
363
|
+
'unverified_numbers': result.unverified_numbers,
|
|
364
|
+
'repair': result.repair,
|
|
365
|
+
})
|
|
366
|
+
|
|
367
|
+
return report
|
|
368
|
+
|
|
369
|
+
@staticmethod
|
|
370
|
+
def _result_from_reference(reference: Dict[str, Any]) -> SearchResult:
|
|
371
|
+
"""Rebuild a SearchResult from a verifier source reference."""
|
|
372
|
+
return SearchResult(
|
|
373
|
+
feature_id=reference['feature_id'],
|
|
374
|
+
feature_type=reference['feature_type'],
|
|
375
|
+
content=reference['content'],
|
|
376
|
+
score=reference['relevance_score'],
|
|
377
|
+
path=reference['path'],
|
|
378
|
+
metadata={'document_id': reference['document_id']},
|
|
379
|
+
)
|
|
380
|
+
|
|
381
|
+
def export_hsf(self, document_id: str, filepath: str):
|
|
382
|
+
"""Export HSF to JSON file."""
|
|
383
|
+
if document_id in self.documents:
|
|
384
|
+
self.documents[document_id].save(filepath)
|
|
385
|
+
|
|
386
|
+
def reason(self, query: str, document_ids: List[str] = None,
|
|
387
|
+
max_hops: int = 3) -> ReasoningResult:
|
|
388
|
+
"""
|
|
389
|
+
Multi-hop reasoning across documents.
|
|
390
|
+
|
|
391
|
+
Args:
|
|
392
|
+
query: The query to reason about
|
|
393
|
+
document_ids: Documents to reason over (all if None)
|
|
394
|
+
max_hops: Maximum traversal hops
|
|
395
|
+
|
|
396
|
+
Returns:
|
|
397
|
+
ReasoningResult with evidence and paths
|
|
398
|
+
"""
|
|
399
|
+
if document_ids is None:
|
|
400
|
+
document_ids = list(self.documents.keys())
|
|
401
|
+
|
|
402
|
+
# Aggregate evidence from all requested documents
|
|
403
|
+
all_evidence = []
|
|
404
|
+
all_paths = []
|
|
405
|
+
searched = 0
|
|
406
|
+
for doc_id in document_ids:
|
|
407
|
+
reasoner = self.reasoners.get(doc_id)
|
|
408
|
+
if reasoner is None:
|
|
409
|
+
continue
|
|
410
|
+
searched += 1
|
|
411
|
+
result = reasoner.reason_about(query, max_hops=max_hops)
|
|
412
|
+
all_evidence.extend(result.evidence)
|
|
413
|
+
all_paths.extend(result.paths)
|
|
414
|
+
|
|
415
|
+
if not all_evidence:
|
|
416
|
+
return ReasoningResult(
|
|
417
|
+
query=query, found=False, evidence=[], paths=[],
|
|
418
|
+
confidence=0.0, explanation="No related concepts found"
|
|
419
|
+
)
|
|
420
|
+
|
|
421
|
+
avg_conf = sum(e['confidence'] for e in all_evidence) / len(all_evidence)
|
|
422
|
+
return ReasoningResult(
|
|
423
|
+
query=query, found=True, evidence=all_evidence,
|
|
424
|
+
paths=all_paths, confidence=avg_conf,
|
|
425
|
+
explanation=f"Found {len(all_evidence)} related concepts across {searched} documents"
|
|
426
|
+
)
|
|
427
|
+
|
|
428
|
+
def import_hsf(self, filepath: str, document_id: str = None) -> str:
|
|
429
|
+
"""Import HSF from JSON file."""
|
|
430
|
+
hsf = HolisticStructuralForm.load(filepath)
|
|
431
|
+
doc_id = document_id or hsf.document_id
|
|
432
|
+
|
|
433
|
+
if doc_id in self.documents:
|
|
434
|
+
raise ValueError(f"Document '{doc_id}' already exists. Use a new ID or remove it first.")
|
|
435
|
+
|
|
436
|
+
self.documents[doc_id] = hsf
|
|
437
|
+
self.retriever.add_document(hsf, doc_id=doc_id)
|
|
438
|
+
|
|
439
|
+
reasoner = MultiHopReasoner(hsf)
|
|
440
|
+
reasoner.build()
|
|
441
|
+
self.reasoners[doc_id] = reasoner
|
|
442
|
+
|
|
443
|
+
return doc_id
|
|
444
|
+
|
|
445
|
+
def get_statistics(self) -> Dict[str, Any]:
|
|
446
|
+
"""Get overall statistics about the knowledge base."""
|
|
447
|
+
total_elements = sum(len(hsf.elementary_features) for hsf in self.documents.values())
|
|
448
|
+
total_composites = sum(len(hsf.composite_features) for hsf in self.documents.values())
|
|
449
|
+
|
|
450
|
+
return {
|
|
451
|
+
'total_documents': len(self.documents),
|
|
452
|
+
'total_elementary_features': total_elements,
|
|
453
|
+
'total_composite_features': total_composites,
|
|
454
|
+
'average_document_size': total_elements / max(1, len(self.documents))
|
|
455
|
+
}
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: structurerag
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Deterministic RAG with Holistic Structural Forms - Embedding-free retrieval with full traceability
|
|
5
|
+
Author-email: Branislav Djalic <branislav.djalic@gmail.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Omodaka9375/structurerag
|
|
8
|
+
Project-URL: Documentation, https://github.com/Omodaka9375/structurerag#readme
|
|
9
|
+
Project-URL: Repository, https://github.com/Omodaka9375/structurerag
|
|
10
|
+
Project-URL: Issues, https://github.com/Omodaka9375/structurerag/issues
|
|
11
|
+
Keywords: rag,retrieval,deterministic,knowledge-representation,hallucination-detection,hsf,structured-data
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Intended Audience :: Science/Research
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
21
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
22
|
+
Requires-Python: >=3.10
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Provides-Extra: dev
|
|
26
|
+
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
27
|
+
Requires-Dist: pytest-cov>=4.0; extra == "dev"
|
|
28
|
+
Provides-Extra: pdf
|
|
29
|
+
Requires-Dist: pdfplumber>=0.9; extra == "pdf"
|
|
30
|
+
Provides-Extra: rerank
|
|
31
|
+
Requires-Dist: sentence-transformers>=2.2.0; extra == "rerank"
|
|
32
|
+
Provides-Extra: all
|
|
33
|
+
Requires-Dist: pdfplumber>=0.9; extra == "all"
|
|
34
|
+
Requires-Dist: pytest>=7.0; extra == "all"
|
|
35
|
+
Requires-Dist: pytest-cov>=4.0; extra == "all"
|
|
36
|
+
Requires-Dist: sentence-transformers>=2.2.0; extra == "all"
|
|
37
|
+
Dynamic: license-file
|
|
38
|
+
|
|
39
|
+
# StructureRAG
|
|
40
|
+
|
|
41
|
+
**Deterministic retrieval-augmented generation with full source traceability. No embeddings. No vector database.**
|
|
42
|
+
|
|
43
|
+
StructureRAG turns text into a hierarchical structure (document > sentence > word), indexes it with BM25, and can verify any claim against it. Every result carries its exact source path and character offsets. Same corpus, same query, same answer, every time.
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from structurerag import StructureRAG
|
|
47
|
+
|
|
48
|
+
rag = StructureRAG()
|
|
49
|
+
rag.add_document("StructureRAG uses BM25 for deterministic retrieval. "
|
|
50
|
+
"Unlike embedding-based RAG, it provides full traceability.")
|
|
51
|
+
|
|
52
|
+
results = rag.search("deterministic retrieval", top_k=3)
|
|
53
|
+
for r in results:
|
|
54
|
+
print(f"{r.score:.2f} {r.path} {r.content}")
|
|
55
|
+
|
|
56
|
+
answer = rag.query("What does StructureRAG use for retrieval?")
|
|
57
|
+
print(answer.answer, answer.is_fully_grounded, answer.grounding_confidence)
|
|
58
|
+
|
|
59
|
+
report = rag.verify_answer("StructureRAG uses embeddings for retrieval.")
|
|
60
|
+
print(report["hallucinations"]) # caught: 'embeddings' is not in the corpus
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Installation
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
pip install -e . # core, zero dependencies
|
|
67
|
+
pip install -e .[pdf] # + PDF loading
|
|
68
|
+
pip install -e .[rerank] # + cross-encoder reranking
|
|
69
|
+
pip install -e .[all] # everything
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Python 3.10+. The core library has no dependencies. `sentence-transformers` is used only if you explicitly pass `reranker=CrossEncoderReranker()`.
|
|
73
|
+
|
|
74
|
+
## What you get
|
|
75
|
+
|
|
76
|
+
| Capability | How |
|
|
77
|
+
|---|---|
|
|
78
|
+
| Document search | `search_documents()` - document-level BM25, tf accumulates across a document's sentences |
|
|
79
|
+
| Sentence search | `search()` - points at exact sentences with char offsets |
|
|
80
|
+
| Claim verification | `verify_answer()` / `verify_claim()` - fail-closed per-term licensing |
|
|
81
|
+
| Hallucination detection | `detect_hallucinations()` - names the exact unexplained words |
|
|
82
|
+
| Number checking | `unverified_numbers` - canonical comparison (`3,000` == `3000`, `3.50` == `3.5`), no fuzzy path |
|
|
83
|
+
| Deterministic repair | `repair` - refused claim corrected against its judging passage, with citation |
|
|
84
|
+
| Span-level output | `VerificationResult.spans` - char-offset regions marked grounded or not, no model |
|
|
85
|
+
| Citations | `CitationEngine` - source references for every grounded segment |
|
|
86
|
+
| Multi-hop reasoning | `reason()` - graph traversal across the hierarchy |
|
|
87
|
+
| Lossless reconstruction | `reconstruct_text(doc_id)` - byte-exact source text |
|
|
88
|
+
| Export / import | `export_hsf()` / `import_hsf()` - plain JSON, deterministic IDs |
|
|
89
|
+
|
|
90
|
+
## How verification works
|
|
91
|
+
|
|
92
|
+
A claim is grounded only if **one single passage** accounts for **every content term** - the term itself, a morphological variant, or a synonym. Anything left over is reported in `unexplained_terms` and the claim is refused. Grounding is never pooled across passages. This makes the verifier deliberately conservative: a genuine paraphrase using a word the synonym list does not know is refused. Correct bias for a hallucination detector.
|
|
93
|
+
|
|
94
|
+
For QA over a corpus use `search()`. Use `verify_answer()` for claim-sized grounding checks.
|
|
95
|
+
|
|
96
|
+
### Span-level output
|
|
97
|
+
|
|
98
|
+
Every verification result marks which parts of the claim the corpus accounts for, as character offsets - the same output shape as encoder-based detectors like LettuceDetect, without a model:
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
result = rag.verifier.verify_claim(Claim(id="c", text=claim, start_pos=0, end_pos=len(claim)))
|
|
102
|
+
for s in result.spans:
|
|
103
|
+
print("OK " if s.grounded else "BAD", s.start, s.end, s.terms, claim[s.start:s.end])
|
|
104
|
+
# BAD 40 57 ['titanium', 'bearing'] titanium bearing.
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Offsets are relative to the claim text. Ungrounded spans list the content words no single passage licensed; spans tile the claim from its first content word to the end.
|
|
108
|
+
|
|
109
|
+
### Number checking
|
|
110
|
+
|
|
111
|
+
Numbers are verified strictly, against the same passage that accounts for the words. Spellings compare canonically - `3,000` equals `3000`, `3.50` equals `3.5`, `007` equals `7` - but there is no fuzzy path: `5000 RPM` against a corpus of `3000 RPM` is a different fact, and unit conversion is deliberately out of scope (`3 km` never satisfies `3000 m`). Failed numbers land in `unverified_numbers` on the result, the hallucination report, and `to_dict()`, and block verification.
|
|
112
|
+
|
|
113
|
+
### Deterministic repair
|
|
114
|
+
|
|
115
|
+
A refused claim comes back with a corrected version proposed from the very passage the gate judged it against. Anchors are the claim's licensed content words; the passage token closest to an anchor becomes the replacement. No model, no generation, fully reproducible - and honest: terms the passage cannot fix stay untouched, and the source passage rides along as the citation.
|
|
116
|
+
|
|
117
|
+
```python
|
|
118
|
+
report = rag.verify_answer("The turbine uses a titanium bearing.")
|
|
119
|
+
print(report["hallucinations"][0]["repair"])
|
|
120
|
+
# {'text': 'The turbine uses a bronze bearing.',
|
|
121
|
+
# 'replacements': [{'from': 'titanium', 'to': 'bronze'}],
|
|
122
|
+
# 'source': {'content': 'The turbine uses a bronze bearing .', ...}}
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
## API
|
|
126
|
+
|
|
127
|
+
```python
|
|
128
|
+
rag = StructureRAG(reranker=None) # or StructureReranker() / CrossEncoderReranker()
|
|
129
|
+
|
|
130
|
+
doc_id = rag.add_document(text, title="Overview") # or document_id="my-id"
|
|
131
|
+
doc_id = rag.add_file("paper.pdf", title="Paper") # .txt or .pdf
|
|
132
|
+
rag.remove_document(doc_id) # rebuilds the index
|
|
133
|
+
|
|
134
|
+
rag.search(query, top_k=5, document_ids=["doc_1"]) # sentence results
|
|
135
|
+
rag.search_documents(query, top_k=5) # whole-document ranking
|
|
136
|
+
rag.query(question) # GroundedAnswer
|
|
137
|
+
rag.verify_answer(claim, document_ids=[doc_id]) # dict with hallucinations
|
|
138
|
+
rag.reason("multi hop question", max_hops=3)
|
|
139
|
+
rag.reconstruct_text(doc_id)
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
## Architecture
|
|
143
|
+
|
|
144
|
+
```
|
|
145
|
+
structurerag/
|
|
146
|
+
core/ hsf.py (structure), builder.py (text to HSF), reasoner.py
|
|
147
|
+
grounding/ retriever.py (BM25 inverted index), verifier.py, citation.py, reranker.py
|
|
148
|
+
loaders/ text.py, pdf.py
|
|
149
|
+
semantic.py synonym expansion, morphology, phrase matching
|
|
150
|
+
structurerag.py StructureRAG facade
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
One retriever serves the whole corpus; BM25 statistics (document frequency, average length) are corpus-wide, so hits in different documents rank on the same scale. Feature IDs are deterministic hashes, so exports are reproducible.
|
|
154
|
+
|
|
155
|
+
## Performance
|
|
156
|
+
|
|
157
|
+
Zero-shot on public BEIR datasets (200 queries; `python benchmarks/beir.py`):
|
|
158
|
+
|
|
159
|
+
| SciFact | nDCG@10 | Recall@100 | ms/query |
|
|
160
|
+
|---|---:|---:|---:|
|
|
161
|
+
| BM25 (textbook) | 68.5 | 91.4 | 24 |
|
|
162
|
+
| **StructureRAG (doc-level)** | **68.7** | **91.9** | **11** |
|
|
163
|
+
| Dense MiniLM | 63.7 | 92.8 | 9 |
|
|
164
|
+
|
|
165
|
+
StructureRAG matches or beats the textbook BM25 baseline on SciFact and NFCorpus (35.5 vs 35.1) at about half the query cost - and adds source paths, deterministic ordering, byte-exact reconstruction, and fail-closed verification, which no baseline provides. Dense embeddings and rank fusion were measured and removed: zero effect on retrieval quality, ~92 ms/query cost.
|
|
166
|
+
|
|
167
|
+
Default recommendation: no reranker. The rule-based reranker hurts document ranking; the cross-encoder wins only on NFCorpus at 40-65x the cost.
|
|
168
|
+
|
|
169
|
+
## Tests and benchmarks
|
|
170
|
+
|
|
171
|
+
```bash
|
|
172
|
+
pip install -e .[dev]
|
|
173
|
+
python -m pytest tests/ -q # 153 tests
|
|
174
|
+
python benchmarks/benchmark.py --quick
|
|
175
|
+
python examples/basic_usage.py
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
## Limitations
|
|
179
|
+
|
|
180
|
+
- Purely lexical: paraphrase-heavy workloads where queries share no vocabulary with the corpus need a semantic index. That is the stated trade for determinism and speed.
|
|
181
|
+
- The verifier needs the synonym/morphology lists to know a paraphrase; unknown wording is refused, not guessed.
|
|
182
|
+
- Indexing is O(corpus); `remove_document` rebuilds the index.
|
|
183
|
+
|
|
184
|
+
## License
|
|
185
|
+
|
|
186
|
+
MIT - see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
structurerag/__init__.py,sha256=GOHs83inO_ysvJzUlqxWmO21q2zWknGlSgW9B4qEutk,1823
|
|
2
|
+
structurerag/semantic.py,sha256=Hb81UUb97RbXDM7cT807uT8v0DWnA8Ssyq71Bfr-wuE,13774
|
|
3
|
+
structurerag/structurerag.py,sha256=P1Ut19kOmx5zxTX1S4kM-vTV1i2FsUROhzshARBJ6gc,17016
|
|
4
|
+
structurerag/core/__init__.py,sha256=OWNfN-Fqe3riTHYZg5eIS2fJuHS1qcHcnl1bIdDyw74,452
|
|
5
|
+
structurerag/core/builder.py,sha256=KvAUHdCCxHkacxfTPbJqvSRaa2r47qaTepdzd_IwqcA,11972
|
|
6
|
+
structurerag/core/hsf.py,sha256=_QToQPhDM50pwXrmyKTvz8TG9zFgJsWWu927sQ2Ec48,9635
|
|
7
|
+
structurerag/core/reasoner.py,sha256=ZKXO-2EkUbJSq66651r9W0ZRkX8tOFuhlPrHoMdNbSY,11129
|
|
8
|
+
structurerag/grounding/__init__.py,sha256=3dZDEbesfCqtoo0PsV7gNEsZs7__wlAWLudXgZvqKrY,577
|
|
9
|
+
structurerag/grounding/citation.py,sha256=S_uZ18qm6NFQjgE9JMsPWrUBc8kBXKhiSsKBQ54BkL8,5961
|
|
10
|
+
structurerag/grounding/reranker.py,sha256=Mi1BwWKH5LZYPYdvmE4IIWPCNGEy8z1E0JV307oG9Ig,5764
|
|
11
|
+
structurerag/grounding/retriever.py,sha256=U6fwsF26CDLc10RVJcLlhA9y_Dvh45SzQOZz0wswrIs,43004
|
|
12
|
+
structurerag/grounding/verifier.py,sha256=gxkS9D0fr67Sc4DeNfMIl6-RfKYtOOo8GHmWsjLRT-o,33233
|
|
13
|
+
structurerag/loaders/__init__.py,sha256=Lg-tPrykLeLOzsLLEuPGRV4YJfbh5sReGr-FccXpsyE,146
|
|
14
|
+
structurerag/loaders/pdf.py,sha256=S9Ab10O0xXr2jK7QThhfwxa_zE-5sBZ_7SiE8S9OtP4,942
|
|
15
|
+
structurerag/loaders/text.py,sha256=p89oqdim_9FkUIHs5PCxhvtGCuynkumdHsWriZVKLgo,367
|
|
16
|
+
structurerag-0.1.0.dist-info/licenses/LICENSE,sha256=QvvVuZL8DBRUw6du9L2uC84uaQkdEWTOQArU7h3SwEk,1073
|
|
17
|
+
structurerag-0.1.0.dist-info/METADATA,sha256=lD5FRTtBHqMy6dymGHIavbLlN7IN-XI8ffj1-T1HA0o,9536
|
|
18
|
+
structurerag-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
19
|
+
structurerag-0.1.0.dist-info/top_level.txt,sha256=NBsfx83FBOT2AnMtxKgWxluZEa9j1tOK32kIL8woY60,13
|
|
20
|
+
structurerag-0.1.0.dist-info/RECORD,,
|