structurerag 0.1.0__tar.gz
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-0.1.0/LICENSE +21 -0
- structurerag-0.1.0/PKG-INFO +186 -0
- structurerag-0.1.0/README.md +148 -0
- structurerag-0.1.0/pyproject.toml +74 -0
- structurerag-0.1.0/setup.cfg +4 -0
- structurerag-0.1.0/structurerag/__init__.py +56 -0
- structurerag-0.1.0/structurerag/core/__init__.py +16 -0
- structurerag-0.1.0/structurerag/core/builder.py +309 -0
- structurerag-0.1.0/structurerag/core/hsf.py +249 -0
- structurerag-0.1.0/structurerag/core/reasoner.py +305 -0
- structurerag-0.1.0/structurerag/grounding/__init__.py +20 -0
- structurerag-0.1.0/structurerag/grounding/citation.py +173 -0
- structurerag-0.1.0/structurerag/grounding/reranker.py +160 -0
- structurerag-0.1.0/structurerag/grounding/retriever.py +980 -0
- structurerag-0.1.0/structurerag/grounding/verifier.py +774 -0
- structurerag-0.1.0/structurerag/loaders/__init__.py +6 -0
- structurerag-0.1.0/structurerag/loaders/pdf.py +36 -0
- structurerag-0.1.0/structurerag/loaders/text.py +16 -0
- structurerag-0.1.0/structurerag/semantic.py +307 -0
- structurerag-0.1.0/structurerag/structurerag.py +455 -0
- structurerag-0.1.0/structurerag.egg-info/PKG-INFO +186 -0
- structurerag-0.1.0/structurerag.egg-info/SOURCES.txt +28 -0
- structurerag-0.1.0/structurerag.egg-info/dependency_links.txt +1 -0
- structurerag-0.1.0/structurerag.egg-info/requires.txt +16 -0
- structurerag-0.1.0/structurerag.egg-info/top_level.txt +1 -0
- structurerag-0.1.0/tests/test_hsf.py +381 -0
- structurerag-0.1.0/tests/test_performance.py +331 -0
- structurerag-0.1.0/tests/test_regression.py +1078 -0
- structurerag-0.1.0/tests/test_reranker.py +210 -0
- structurerag-0.1.0/tests/test_semantic.py +316 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Branislav Djalic
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -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,148 @@
|
|
|
1
|
+
# StructureRAG
|
|
2
|
+
|
|
3
|
+
**Deterministic retrieval-augmented generation with full source traceability. No embeddings. No vector database.**
|
|
4
|
+
|
|
5
|
+
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.
|
|
6
|
+
|
|
7
|
+
```python
|
|
8
|
+
from structurerag import StructureRAG
|
|
9
|
+
|
|
10
|
+
rag = StructureRAG()
|
|
11
|
+
rag.add_document("StructureRAG uses BM25 for deterministic retrieval. "
|
|
12
|
+
"Unlike embedding-based RAG, it provides full traceability.")
|
|
13
|
+
|
|
14
|
+
results = rag.search("deterministic retrieval", top_k=3)
|
|
15
|
+
for r in results:
|
|
16
|
+
print(f"{r.score:.2f} {r.path} {r.content}")
|
|
17
|
+
|
|
18
|
+
answer = rag.query("What does StructureRAG use for retrieval?")
|
|
19
|
+
print(answer.answer, answer.is_fully_grounded, answer.grounding_confidence)
|
|
20
|
+
|
|
21
|
+
report = rag.verify_answer("StructureRAG uses embeddings for retrieval.")
|
|
22
|
+
print(report["hallucinations"]) # caught: 'embeddings' is not in the corpus
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Installation
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pip install -e . # core, zero dependencies
|
|
29
|
+
pip install -e .[pdf] # + PDF loading
|
|
30
|
+
pip install -e .[rerank] # + cross-encoder reranking
|
|
31
|
+
pip install -e .[all] # everything
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Python 3.10+. The core library has no dependencies. `sentence-transformers` is used only if you explicitly pass `reranker=CrossEncoderReranker()`.
|
|
35
|
+
|
|
36
|
+
## What you get
|
|
37
|
+
|
|
38
|
+
| Capability | How |
|
|
39
|
+
|---|---|
|
|
40
|
+
| Document search | `search_documents()` - document-level BM25, tf accumulates across a document's sentences |
|
|
41
|
+
| Sentence search | `search()` - points at exact sentences with char offsets |
|
|
42
|
+
| Claim verification | `verify_answer()` / `verify_claim()` - fail-closed per-term licensing |
|
|
43
|
+
| Hallucination detection | `detect_hallucinations()` - names the exact unexplained words |
|
|
44
|
+
| Number checking | `unverified_numbers` - canonical comparison (`3,000` == `3000`, `3.50` == `3.5`), no fuzzy path |
|
|
45
|
+
| Deterministic repair | `repair` - refused claim corrected against its judging passage, with citation |
|
|
46
|
+
| Span-level output | `VerificationResult.spans` - char-offset regions marked grounded or not, no model |
|
|
47
|
+
| Citations | `CitationEngine` - source references for every grounded segment |
|
|
48
|
+
| Multi-hop reasoning | `reason()` - graph traversal across the hierarchy |
|
|
49
|
+
| Lossless reconstruction | `reconstruct_text(doc_id)` - byte-exact source text |
|
|
50
|
+
| Export / import | `export_hsf()` / `import_hsf()` - plain JSON, deterministic IDs |
|
|
51
|
+
|
|
52
|
+
## How verification works
|
|
53
|
+
|
|
54
|
+
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.
|
|
55
|
+
|
|
56
|
+
For QA over a corpus use `search()`. Use `verify_answer()` for claim-sized grounding checks.
|
|
57
|
+
|
|
58
|
+
### Span-level output
|
|
59
|
+
|
|
60
|
+
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:
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
result = rag.verifier.verify_claim(Claim(id="c", text=claim, start_pos=0, end_pos=len(claim)))
|
|
64
|
+
for s in result.spans:
|
|
65
|
+
print("OK " if s.grounded else "BAD", s.start, s.end, s.terms, claim[s.start:s.end])
|
|
66
|
+
# BAD 40 57 ['titanium', 'bearing'] titanium bearing.
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
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.
|
|
70
|
+
|
|
71
|
+
### Number checking
|
|
72
|
+
|
|
73
|
+
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.
|
|
74
|
+
|
|
75
|
+
### Deterministic repair
|
|
76
|
+
|
|
77
|
+
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.
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
report = rag.verify_answer("The turbine uses a titanium bearing.")
|
|
81
|
+
print(report["hallucinations"][0]["repair"])
|
|
82
|
+
# {'text': 'The turbine uses a bronze bearing.',
|
|
83
|
+
# 'replacements': [{'from': 'titanium', 'to': 'bronze'}],
|
|
84
|
+
# 'source': {'content': 'The turbine uses a bronze bearing .', ...}}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
## API
|
|
88
|
+
|
|
89
|
+
```python
|
|
90
|
+
rag = StructureRAG(reranker=None) # or StructureReranker() / CrossEncoderReranker()
|
|
91
|
+
|
|
92
|
+
doc_id = rag.add_document(text, title="Overview") # or document_id="my-id"
|
|
93
|
+
doc_id = rag.add_file("paper.pdf", title="Paper") # .txt or .pdf
|
|
94
|
+
rag.remove_document(doc_id) # rebuilds the index
|
|
95
|
+
|
|
96
|
+
rag.search(query, top_k=5, document_ids=["doc_1"]) # sentence results
|
|
97
|
+
rag.search_documents(query, top_k=5) # whole-document ranking
|
|
98
|
+
rag.query(question) # GroundedAnswer
|
|
99
|
+
rag.verify_answer(claim, document_ids=[doc_id]) # dict with hallucinations
|
|
100
|
+
rag.reason("multi hop question", max_hops=3)
|
|
101
|
+
rag.reconstruct_text(doc_id)
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## Architecture
|
|
105
|
+
|
|
106
|
+
```
|
|
107
|
+
structurerag/
|
|
108
|
+
core/ hsf.py (structure), builder.py (text to HSF), reasoner.py
|
|
109
|
+
grounding/ retriever.py (BM25 inverted index), verifier.py, citation.py, reranker.py
|
|
110
|
+
loaders/ text.py, pdf.py
|
|
111
|
+
semantic.py synonym expansion, morphology, phrase matching
|
|
112
|
+
structurerag.py StructureRAG facade
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
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.
|
|
116
|
+
|
|
117
|
+
## Performance
|
|
118
|
+
|
|
119
|
+
Zero-shot on public BEIR datasets (200 queries; `python benchmarks/beir.py`):
|
|
120
|
+
|
|
121
|
+
| SciFact | nDCG@10 | Recall@100 | ms/query |
|
|
122
|
+
|---|---:|---:|---:|
|
|
123
|
+
| BM25 (textbook) | 68.5 | 91.4 | 24 |
|
|
124
|
+
| **StructureRAG (doc-level)** | **68.7** | **91.9** | **11** |
|
|
125
|
+
| Dense MiniLM | 63.7 | 92.8 | 9 |
|
|
126
|
+
|
|
127
|
+
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.
|
|
128
|
+
|
|
129
|
+
Default recommendation: no reranker. The rule-based reranker hurts document ranking; the cross-encoder wins only on NFCorpus at 40-65x the cost.
|
|
130
|
+
|
|
131
|
+
## Tests and benchmarks
|
|
132
|
+
|
|
133
|
+
```bash
|
|
134
|
+
pip install -e .[dev]
|
|
135
|
+
python -m pytest tests/ -q # 153 tests
|
|
136
|
+
python benchmarks/benchmark.py --quick
|
|
137
|
+
python examples/basic_usage.py
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
## Limitations
|
|
141
|
+
|
|
142
|
+
- 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.
|
|
143
|
+
- The verifier needs the synonym/morphology lists to know a paraphrase; unknown wording is refused, not guessed.
|
|
144
|
+
- Indexing is O(corpus); `remove_document` rebuilds the index.
|
|
145
|
+
|
|
146
|
+
## License
|
|
147
|
+
|
|
148
|
+
MIT - see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "structurerag"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Deterministic RAG with Holistic Structural Forms - Embedding-free retrieval with full traceability"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = {text = "MIT"}
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
authors = [
|
|
13
|
+
{name = "Branislav Djalic", email = "branislav.djalic@gmail.com"}
|
|
14
|
+
]
|
|
15
|
+
keywords = [
|
|
16
|
+
"rag",
|
|
17
|
+
"retrieval",
|
|
18
|
+
"deterministic",
|
|
19
|
+
"knowledge-representation",
|
|
20
|
+
"hallucination-detection",
|
|
21
|
+
"hsf",
|
|
22
|
+
"structured-data"
|
|
23
|
+
]
|
|
24
|
+
classifiers = [
|
|
25
|
+
"Development Status :: 3 - Alpha",
|
|
26
|
+
"Intended Audience :: Developers",
|
|
27
|
+
"Intended Audience :: Science/Research",
|
|
28
|
+
"License :: OSI Approved :: MIT License",
|
|
29
|
+
"Programming Language :: Python :: 3",
|
|
30
|
+
"Programming Language :: Python :: 3.10",
|
|
31
|
+
"Programming Language :: Python :: 3.11",
|
|
32
|
+
"Programming Language :: Python :: 3.12",
|
|
33
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
34
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
dependencies = []
|
|
38
|
+
|
|
39
|
+
[project.optional-dependencies]
|
|
40
|
+
dev = [
|
|
41
|
+
"pytest>=7.0",
|
|
42
|
+
"pytest-cov>=4.0",
|
|
43
|
+
]
|
|
44
|
+
pdf = [
|
|
45
|
+
"pdfplumber>=0.9",
|
|
46
|
+
]
|
|
47
|
+
rerank = [
|
|
48
|
+
"sentence-transformers>=2.2.0",
|
|
49
|
+
]
|
|
50
|
+
all = [
|
|
51
|
+
"pdfplumber>=0.9",
|
|
52
|
+
"pytest>=7.0",
|
|
53
|
+
"pytest-cov>=4.0",
|
|
54
|
+
"sentence-transformers>=2.2.0",
|
|
55
|
+
]
|
|
56
|
+
|
|
57
|
+
[project.urls]
|
|
58
|
+
Homepage = "https://github.com/Omodaka9375/structurerag"
|
|
59
|
+
Documentation = "https://github.com/Omodaka9375/structurerag#readme"
|
|
60
|
+
Repository = "https://github.com/Omodaka9375/structurerag"
|
|
61
|
+
Issues = "https://github.com/Omodaka9375/structurerag/issues"
|
|
62
|
+
|
|
63
|
+
[tool.setuptools.packages.find]
|
|
64
|
+
where = ["."]
|
|
65
|
+
include = ["structurerag*"]
|
|
66
|
+
|
|
67
|
+
[tool.pytest.ini_options]
|
|
68
|
+
testpaths = ["tests"]
|
|
69
|
+
python_files = ["test_*.py"]
|
|
70
|
+
addopts = "-v --tb=short"
|
|
71
|
+
|
|
72
|
+
[tool.coverage.run]
|
|
73
|
+
source = ["structurerag"]
|
|
74
|
+
omit = ["tests/*", "examples/*"]
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""
|
|
2
|
+
StructureRAG: Deterministic Retrieval-Augmented Generation via Holistic Structural Forms.
|
|
3
|
+
|
|
4
|
+
Embedding-free retrieval with full traceability.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
__version__ = "0.2.0"
|
|
8
|
+
|
|
9
|
+
from .core.hsf import HolisticStructuralForm, ElementaryFeature, CompositeFeature
|
|
10
|
+
from .core.builder import StructureBuilder, PatternMiner
|
|
11
|
+
from .core.reasoner import MultiHopReasoner, ReasoningResult, ReasoningPath
|
|
12
|
+
from .grounding.retriever import StructureRetriever, SearchResult
|
|
13
|
+
from .grounding.verifier import GroundingVerifier, Claim, VerificationResult, GroundingSpan
|
|
14
|
+
from .grounding.citation import CitationEngine, Citation
|
|
15
|
+
from .grounding.reranker import StructureReranker, CrossEncoderReranker
|
|
16
|
+
from .semantic import (
|
|
17
|
+
SemanticExpander, PhraseMatcher, SynonymGroup,
|
|
18
|
+
create_default_expander, create_default_phrase_matcher,
|
|
19
|
+
)
|
|
20
|
+
from .structurerag import StructureRAG, GroundedAnswer
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"StructureRAG",
|
|
24
|
+
"GroundedAnswer",
|
|
25
|
+
"HolisticStructuralForm",
|
|
26
|
+
"ElementaryFeature",
|
|
27
|
+
"CompositeFeature",
|
|
28
|
+
"StructureBuilder",
|
|
29
|
+
"PatternMiner",
|
|
30
|
+
"MultiHopReasoner",
|
|
31
|
+
"ReasoningResult",
|
|
32
|
+
"ReasoningPath",
|
|
33
|
+
"StructureRetriever",
|
|
34
|
+
"SearchResult",
|
|
35
|
+
"GroundingVerifier",
|
|
36
|
+
"Claim",
|
|
37
|
+
"VerificationResult",
|
|
38
|
+
"GroundingSpan",
|
|
39
|
+
"CitationEngine",
|
|
40
|
+
"Citation",
|
|
41
|
+
"SemanticExpander",
|
|
42
|
+
"PhraseMatcher",
|
|
43
|
+
"SynonymGroup",
|
|
44
|
+
"create_default_expander",
|
|
45
|
+
"create_default_phrase_matcher",
|
|
46
|
+
"StructureReranker",
|
|
47
|
+
"CrossEncoderReranker",
|
|
48
|
+
]
|
|
49
|
+
|
|
50
|
+
# Backwards compatibility aliases.
|
|
51
|
+
# ``Context`` / ``ContextGraph`` were removed: the builder populated the graph
|
|
52
|
+
# but nothing in the library ever read it.
|
|
53
|
+
EnhancedSemanticExpander = SemanticExpander
|
|
54
|
+
EnhancedPhraseMatcher = PhraseMatcher
|
|
55
|
+
create_enhanced_expander = create_default_expander
|
|
56
|
+
create_enhanced_phrase_matcher = create_default_phrase_matcher
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Core HSF data structures and builders."""
|
|
2
|
+
|
|
3
|
+
from .hsf import HolisticStructuralForm, ElementaryFeature, CompositeFeature
|
|
4
|
+
from .builder import StructureBuilder, PatternMiner
|
|
5
|
+
from .reasoner import MultiHopReasoner, ReasoningResult, ReasoningPath
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"HolisticStructuralForm",
|
|
9
|
+
"ElementaryFeature",
|
|
10
|
+
"CompositeFeature",
|
|
11
|
+
"StructureBuilder",
|
|
12
|
+
"PatternMiner",
|
|
13
|
+
"MultiHopReasoner",
|
|
14
|
+
"ReasoningResult",
|
|
15
|
+
"ReasoningPath",
|
|
16
|
+
]
|