spectrag 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.
Files changed (89) hide show
  1. spectrag-0.1.0/LICENSE +21 -0
  2. spectrag-0.1.0/PKG-INFO +550 -0
  3. spectrag-0.1.0/README.md +506 -0
  4. spectrag-0.1.0/pyproject.toml +55 -0
  5. spectrag-0.1.0/setup.cfg +4 -0
  6. spectrag-0.1.0/src/spectrag/__init__.py +22 -0
  7. spectrag-0.1.0/src/spectrag/_version.py +7 -0
  8. spectrag-0.1.0/src/spectrag/cli.py +115 -0
  9. spectrag-0.1.0/src/spectrag/config.py +96 -0
  10. spectrag-0.1.0/src/spectrag/errors.py +40 -0
  11. spectrag-0.1.0/src/spectrag/ingestion.py +141 -0
  12. spectrag-0.1.0/src/spectrag/log.py +30 -0
  13. spectrag-0.1.0/src/spectrag/retrieval.py +154 -0
  14. spectrag-0.1.0/src/spectrag/utils/__init__.py +1 -0
  15. spectrag-0.1.0/src/spectrag/utils/bm25.py +53 -0
  16. spectrag-0.1.0/src/spectrag/utils/chunker.py +112 -0
  17. spectrag-0.1.0/src/spectrag/utils/clusters.py +63 -0
  18. spectrag-0.1.0/src/spectrag/utils/diffusion.py +104 -0
  19. spectrag-0.1.0/src/spectrag/utils/edge_list.py +18 -0
  20. spectrag-0.1.0/src/spectrag/utils/edges.py +38 -0
  21. spectrag-0.1.0/src/spectrag/utils/edges_content.py +110 -0
  22. spectrag-0.1.0/src/spectrag/utils/edges_structure.py +86 -0
  23. spectrag-0.1.0/src/spectrag/utils/embedder.py +89 -0
  24. spectrag-0.1.0/src/spectrag/utils/entities.py +72 -0
  25. spectrag-0.1.0/src/spectrag/utils/evaluation.py +111 -0
  26. spectrag-0.1.0/src/spectrag/utils/expansion.py +68 -0
  27. spectrag-0.1.0/src/spectrag/utils/graph.py +90 -0
  28. spectrag-0.1.0/src/spectrag/utils/graph_build.py +27 -0
  29. spectrag-0.1.0/src/spectrag/utils/graph_template.py +105 -0
  30. spectrag-0.1.0/src/spectrag/utils/graph_view.py +126 -0
  31. spectrag-0.1.0/src/spectrag/utils/llm.py +61 -0
  32. spectrag-0.1.0/src/spectrag/utils/loader.py +59 -0
  33. spectrag-0.1.0/src/spectrag/utils/metrics.py +61 -0
  34. spectrag-0.1.0/src/spectrag/utils/prompt.py +62 -0
  35. spectrag-0.1.0/src/spectrag/utils/questions.py +40 -0
  36. spectrag-0.1.0/src/spectrag/utils/references.py +43 -0
  37. spectrag-0.1.0/src/spectrag/utils/sections.py +98 -0
  38. spectrag-0.1.0/src/spectrag/utils/seeding.py +106 -0
  39. spectrag-0.1.0/src/spectrag/utils/selection.py +93 -0
  40. spectrag-0.1.0/src/spectrag/utils/selectors.py +103 -0
  41. spectrag-0.1.0/src/spectrag/utils/semantic_split.py +54 -0
  42. spectrag-0.1.0/src/spectrag/utils/spectral.py +72 -0
  43. spectrag-0.1.0/src/spectrag/utils/store.py +94 -0
  44. spectrag-0.1.0/src/spectrag/utils/tokens.py +64 -0
  45. spectrag-0.1.0/src/spectrag/utils/tuning.py +78 -0
  46. spectrag-0.1.0/src/spectrag/utils/units.py +106 -0
  47. spectrag-0.1.0/src/spectrag/utils/vector_index.py +122 -0
  48. spectrag-0.1.0/src/spectrag/validation.py +84 -0
  49. spectrag-0.1.0/src/spectrag.egg-info/PKG-INFO +550 -0
  50. spectrag-0.1.0/src/spectrag.egg-info/SOURCES.txt +87 -0
  51. spectrag-0.1.0/src/spectrag.egg-info/dependency_links.txt +1 -0
  52. spectrag-0.1.0/src/spectrag.egg-info/entry_points.txt +2 -0
  53. spectrag-0.1.0/src/spectrag.egg-info/requires.txt +22 -0
  54. spectrag-0.1.0/src/spectrag.egg-info/top_level.txt +1 -0
  55. spectrag-0.1.0/tests/test_benchmark_helpers.py +41 -0
  56. spectrag-0.1.0/tests/test_bm25.py +47 -0
  57. spectrag-0.1.0/tests/test_chunker.py +106 -0
  58. spectrag-0.1.0/tests/test_clusters.py +49 -0
  59. spectrag-0.1.0/tests/test_config.py +29 -0
  60. spectrag-0.1.0/tests/test_diffusion.py +90 -0
  61. spectrag-0.1.0/tests/test_docs.py +26 -0
  62. spectrag-0.1.0/tests/test_edges.py +143 -0
  63. spectrag-0.1.0/tests/test_embedder.py +104 -0
  64. spectrag-0.1.0/tests/test_end_to_end.py +98 -0
  65. spectrag-0.1.0/tests/test_entities.py +41 -0
  66. spectrag-0.1.0/tests/test_equivalence.py +70 -0
  67. spectrag-0.1.0/tests/test_evaluation.py +70 -0
  68. spectrag-0.1.0/tests/test_expansion.py +39 -0
  69. spectrag-0.1.0/tests/test_graph.py +57 -0
  70. spectrag-0.1.0/tests/test_graph_view.py +61 -0
  71. spectrag-0.1.0/tests/test_ingestion.py +88 -0
  72. spectrag-0.1.0/tests/test_llm.py +71 -0
  73. spectrag-0.1.0/tests/test_loader.py +52 -0
  74. spectrag-0.1.0/tests/test_metrics.py +36 -0
  75. spectrag-0.1.0/tests/test_phase2.py +125 -0
  76. spectrag-0.1.0/tests/test_production.py +132 -0
  77. spectrag-0.1.0/tests/test_prompt.py +38 -0
  78. spectrag-0.1.0/tests/test_questions.py +66 -0
  79. spectrag-0.1.0/tests/test_references.py +28 -0
  80. spectrag-0.1.0/tests/test_retrieval.py +79 -0
  81. spectrag-0.1.0/tests/test_sections.py +65 -0
  82. spectrag-0.1.0/tests/test_seeding.py +88 -0
  83. spectrag-0.1.0/tests/test_selection.py +75 -0
  84. spectrag-0.1.0/tests/test_selectors.py +74 -0
  85. spectrag-0.1.0/tests/test_semantic_split.py +40 -0
  86. spectrag-0.1.0/tests/test_spectral.py +74 -0
  87. spectrag-0.1.0/tests/test_store.py +48 -0
  88. spectrag-0.1.0/tests/test_tokens.py +44 -0
  89. spectrag-0.1.0/tests/test_units.py +37 -0
spectrag-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kumar Nishant
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,550 @@
1
+ Metadata-Version: 2.4
2
+ Name: spectrag
3
+ Version: 0.1.0
4
+ Summary: SpectRAG: spectral graph-augmented retrieval with token-budgeted context selection for multi-hop RAG
5
+ Author: Kumar Nishant
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/aion7891/Spect-RAG
8
+ Project-URL: Repository, https://github.com/aion7891/Spect-RAG
9
+ Project-URL: Issues, https://github.com/aion7891/Spect-RAG/issues
10
+ Project-URL: Paper, https://arxiv.org/abs/2610.36991
11
+ Keywords: rag,retrieval-augmented-generation,graph,spectral,retrieval,llm,multi-hop
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Operating System :: OS Independent
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: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
23
+ Classifier: Topic :: Text Processing :: Indexing
24
+ Requires-Python: >=3.10
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Requires-Dist: numpy>=1.24
28
+ Provides-Extra: tokens
29
+ Requires-Dist: tiktoken>=0.5; extra == "tokens"
30
+ Provides-Extra: pdf
31
+ Requires-Dist: pypdf>=4; extra == "pdf"
32
+ Provides-Extra: scale
33
+ Requires-Dist: scipy>=1.10; extra == "scale"
34
+ Requires-Dist: faiss-cpu>=1.8; extra == "scale"
35
+ Requires-Dist: hnswlib>=0.8; extra == "scale"
36
+ Provides-Extra: all
37
+ Requires-Dist: spectrag[pdf,scale,tokens]; extra == "all"
38
+ Provides-Extra: extras
39
+ Requires-Dist: spectrag[all]; extra == "extras"
40
+ Provides-Extra: dev
41
+ Requires-Dist: pytest>=8; extra == "dev"
42
+ Requires-Dist: build>=1; extra == "dev"
43
+ Dynamic: license-file
44
+
45
+ <p align="center"><img src="docs/assets/banner.svg" alt="SpectRAG" width="100%"></p>
46
+
47
+ <h3 align="center">Spectral graph-augmented retrieval with token-budgeted context selection for multi-hop RAG</h3>
48
+
49
+ <p align="center">
50
+ <a href="https://github.com/aion7891/Spect-RAG/actions/workflows/tests.yml"><img src="https://github.com/aion7891/Spect-RAG/actions/workflows/tests.yml/badge.svg" alt="tests"></a>
51
+ <img src="https://img.shields.io/badge/python-3.10%20%E2%80%93%203.14-blue" alt="python 3.10 to 3.14">
52
+ <img src="https://img.shields.io/badge/license-MIT-green" alt="MIT license">
53
+ <img src="https://img.shields.io/badge/required%20dependency-numpy-lightgrey" alt="only numpy required">
54
+ <a href="https://arxiv.org/abs/2610.36991"><img src="https://img.shields.io/badge/paper-arXiv%3A2610.36991-b31b1b" alt="paper"></a>
55
+ </p>
56
+
57
+ <p align="center">
58
+ <a href="#installation">Installation</a> ·
59
+ <a href="#quick-start">Quick start</a> ·
60
+ <a href="#how-it-works">How it works</a> ·
61
+ <a href="#graph-view">Graph view</a> ·
62
+ <a href="#configuration">Configuration</a> ·
63
+ <a href="#benchmark-multihoprag">Benchmark</a> ·
64
+ <a href="#citation">Citation</a>
65
+ </p>
66
+
67
+ ---
68
+
69
+ A readable, tested Python implementation of the paper *SpectRAG: Weighted Chunk Graphs for
70
+ Token-Budgeted Context Selection in Multi-Hop Retrieval-Augmented Generation*
71
+ (Sahinoglu et al., [arXiv:2610.36991](https://arxiv.org/abs/2610.36991), [PDF](docs/2610.36991v2.pdf)).
72
+
73
+ | | Plain top-k RAG | SpectRAG |
74
+ |---|---|---|
75
+ | **Unit of retrieval** | chunks ranked one by one | a *set* of chunks chosen together |
76
+ | **Near-duplicates** | often fill the context | penalised (redundancy term) |
77
+ | **Bridge evidence** (not similar to the question, but needed) | usually missed | reached by walking a weighted chunk graph |
78
+ | **Structure** (sections, entities, citations, order) | ignored | six edge signals and spectral coordinates |
79
+ | **Context size** | a fixed *k* | a token budget, filled by relevance, coverage and diversity |
80
+
81
+ <p align="center"><img src="docs/assets/pipeline.svg" alt="SpectRAG pipeline: offline ingestion builds a chunk graph and its spectral coordinates; online retrieval seeds, expands, re-scores and selects within a token budget" width="100%"></p>
82
+
83
+ ## Highlights
84
+
85
+ <table>
86
+ <tr>
87
+ <td width="50%" valign="top">
88
+
89
+ **The full method from the paper**<br>
90
+ Six edge signals, the normalised Laplacian and spectral coordinates, hybrid seeds with RRF,
91
+ two-hop graph expansion, PageRank and spectral proximity, the token-budget selector, and the
92
+ paper's alternative selectors (`mmr`, `protected_mmr`, `anchor_expand_ce`).
93
+
94
+ </td>
95
+ <td width="50%" valign="top">
96
+
97
+ **Measured, not claimed**<br>
98
+ A reproducible MultiHopRAG benchmark (1,955 test questions) against standard RAG, BM25, hybrid
99
+ RAG, MMR, HyDE and LightRAG, with confidence intervals, ablations, latency and memory.
100
+
101
+ </td>
102
+ </tr>
103
+ <tr>
104
+ <td valign="top">
105
+
106
+ **Light and offline by default**<br>
107
+ One required dependency (`numpy`). An offline embedder out of the box; plug in
108
+ `nomic-embed-text`, any embedding function, and any LLM.
109
+
110
+ </td>
111
+ <td valign="top">
112
+
113
+ **Built to scale**<br>
114
+ Exact, FAISS or HNSW vector search, a sparse eigensolver above 2,000 chunks, binary index
115
+ files: about 4 ms per query on 10k chunks.
116
+
117
+ </td>
118
+ </tr>
119
+ <tr>
120
+ <td valign="top">
121
+
122
+ **Configurable and tunable**<br>
123
+ 39 validated settings, per-query overrides, graph settings changed without re-embedding, and a
124
+ grid / random-search tuner.
125
+
126
+ </td>
127
+ <td valign="top">
128
+
129
+ **See what it retrieves**<br>
130
+ An interactive graph view of the chunk graph and of each question's retrieval path, in one
131
+ offline HTML file.
132
+
133
+ </td>
134
+ </tr>
135
+ </table>
136
+
137
+ > [!TIP]
138
+ > On MultiHopRAG, tuned SpectRAG finds more of the evidence than **standard RAG (+0.088)** and
139
+ > **hybrid RAG (+0.014, 95% CI +0.007 … +0.021)** within the same 12,000-token budget, with
140
+ > its largest gain on inference questions. [See the benchmark.](#benchmark-multihoprag)
141
+
142
+ ## Installation
143
+
144
+ ```bash
145
+ pip install "git+https://github.com/aion7891/Spect-RAG.git" # core (numpy only)
146
+ pip install "spectrag[all] @ git+https://github.com/aion7891/Spect-RAG.git" # every extra
147
+ ```
148
+
149
+ > [!NOTE]
150
+ > Installing from GitHub uses the default branch (`main`). Until the 0.1.0 work is merged
151
+ > into `main`, add `@base-2` to the URL, e.g. `pip install "git+https://github.com/aion7891/Spect-RAG.git@base-2"`.
152
+
153
+ From a clone (for development):
154
+
155
+ ```bash
156
+ git clone https://github.com/aion7891/Spect-RAG.git && cd Spect-RAG
157
+ pip install -e ".[all,dev]" # or: uv sync --all-extras
158
+ ```
159
+
160
+ | Extra | Installs | Adds |
161
+ |---|---|---|
162
+ | `tokens` | `tiktoken` | exact `cl100k_base` token counts (otherwise a word-based estimate) |
163
+ | `pdf` | `pypdf` | reading `.pdf` files |
164
+ | `scale` | `scipy`, `faiss-cpu`, `hnswlib` | sparse eigensolver and approximate nearest-neighbour search for large corpora |
165
+ | `all` | all of the above | |
166
+ | `dev` | `pytest`, `build` | tests and packaging |
167
+
168
+ Real semantic embeddings and LLM answers use a local [Ollama](https://ollama.com) server:
169
+ `ollama pull nomic-embed-text` (the paper's embedding model) and, for answers, e.g.
170
+ `ollama pull gemma3:4b`. Without Ollama, SpectRAG uses an offline hashing embedder.
171
+
172
+ Python 3.10–3.14 are tested. There is no upper version limit; Python 3.15 is waiting for a
173
+ numpy release that supports it.
174
+
175
+ ## Quick start
176
+
177
+ ```bash
178
+ python quickstart.py
179
+ ```
180
+
181
+ `quickstart.py` needs no arguments. It ingests the sample documents in `examples/docs/`, builds
182
+ the index, and prints the context for two questions. The documents, questions and every setting
183
+ are at the top of the file; set `USE_OLLAMA = True` for nomic embeddings and LLM answers.
184
+
185
+ ### Python
186
+
187
+ ```python
188
+ from spectrag import SpectRAGIngestion, SpectRAGRetrieval
189
+
190
+ # Offline, once per document set: chunk, embed, build the graph, spectral coordinates
191
+ SpectRAGIngestion("my_index").ingest("examples/docs") # a file or a folder (.txt .md .pdf)
192
+
193
+ # Online, per question
194
+ search = SpectRAGRetrieval("my_index")
195
+ result = search.search("Which company did the co-founder of Aurora Labs join after leaving?")
196
+ print(result["context"]) # text for your LLM, grouped by source document
197
+ for chunk in result["chunks"]: # ranked sources with their scores
198
+ print(chunk["rank"], chunk["doc_id"], round(chunk["score"], 3), chunk["reason"])
199
+
200
+ # Optional: an answer from any LLM (any function prompt -> text)
201
+ from spectrag.utils.llm import ollama_llm
202
+ print(search.answer("Which company did the co-founder of Aurora Labs join?", ollama_llm("gemma3:4b"))["answer"])
203
+ ```
204
+
205
+ Documents can also come from memory:
206
+ `SpectRAGIngestion("my_index").ingest_documents([{"doc_id": "a", "text": "..."}])`.
207
+
208
+ ### Command line
209
+
210
+ ```bash
211
+ spectrag ingest examples/docs --index my_index --set chunk_tokens=256 --set overlap_tokens=64
212
+ spectrag search "Where is Helios Energy based?" --index my_index --budget 2000
213
+ spectrag answer "Where is Helios Energy based?" --index my_index --model gemma3:4b
214
+ spectrag graph --index my_index --out graph.html --question "Where is Helios Energy based?"
215
+ spectrag info --index my_index
216
+ ```
217
+
218
+ `--set key=value` changes any setting (values are read as JSON); `-v` prints progress.
219
+
220
+ ## How it works
221
+
222
+ **Offline: `SpectRAGIngestion`** (once per document set)
223
+
224
+ | Step | What happens | Paper |
225
+ |---|---|---|
226
+ | 1. Chunking | Split by headings, keeping the section path, or where the topic changes (90th-percentile sentence distance). At most 1,200 tokens, 100 overlap; sentences and table rows are never cut | Section 3.3 |
227
+ | 2. Embedding | `nomic-embed-text` with the `search_document:` prefix (or the offline embedder, or your function), L2-normalised | Table 1 |
228
+ | 3. Edge signals | Six links between chunks, each in [0, 1]: semantic (k nearest neighbours), adjacency, section, shared entities, utility questions, citations | Section 3.2.1 |
229
+ | 4. Weighted graph | Weighted sum of the signals; weak edges dropped; each chunk keeps its `graph_k` strongest edges | Eq. 10 |
230
+ | 5. Spectral coordinates | The smallest non-trivial eigenvectors of the normalised Laplacian give each chunk 32 numbers that say *where it sits* in the graph's communities, not what it says | Eq. 11–13 |
231
+
232
+ **Online: `SpectRAGRetrieval`** (per question)
233
+
234
+ | Step | What happens | Paper |
235
+ |---|---|---|
236
+ | 1. Hybrid seeds | Dense, BM25 and utility-question rankings fused with RRF → 20 seeds and a relevance score for every chunk | Table 2 |
237
+ | 2. Graph expansion | Breadth-first search, 2 hops from the seeds, at most 200 candidates: this is where bridge evidence enters | Section 3.6 |
238
+ | 3. Proximity re-scoring | Relevance blended with graph proximity (Personalized PageRank + spectral closeness) | Eq. 17–18 |
239
+ | 4. Token-budget selection | A protected core, a greedy tail that trades relevance against redundancy, coverage and length, then backfill; never over the budget | Eq. 19–22 |
240
+ | 5. Answer | The context, grouped by document, in a grounded prompt for any LLM | Algorithm 1 |
241
+
242
+ <details>
243
+ <summary><b>Key equations</b></summary>
244
+
245
+ Weighted graph (Eq. 10), with edges below $\tau$ removed:
246
+
247
+ ```math
248
+ w_{ij} = \sum_{r} \alpha_r \, w^{(r)}_{ij}
249
+ ```
250
+
251
+ Normalised Laplacian (Eq. 11); the spectral coordinates are eigenvectors $u_2 \dots u_{33}$:
252
+
253
+ ```math
254
+ L_{sym} = I - D^{-1/2} \, W \, D^{-1/2}
255
+ ```
256
+
257
+ Personalized PageRank from the seeds (Eq. 18), and the re-score:
258
+
259
+ ```math
260
+ s^{(t+1)} = \beta \, r + (1-\beta)\, \tilde{A}\, s^{(t)}, \qquad
261
+ \text{score} = (1-\alpha)\,\text{relevance} + \alpha\,\text{proximity}
262
+ ```
263
+
264
+ Greedy selection under the token budget $B$ (Eq. 21–22):
265
+
266
+ ```math
267
+ U(c \mid C) = a\, s_c + b\,\text{Prox}(c) + c\,\text{ClusterGain}(c, C) + d\,\text{DocGain}(c, C) - \lambda\,\text{Red}(c, C),
268
+ \qquad c^{*} = \arg\max_{c} \frac{U(c \mid C)}{\ell(c)^{\rho}}, \quad \sum_{c \in C} \ell(c) \le B
269
+ ```
270
+
271
+ </details>
272
+
273
+ Every place where the paper leaves a detail open, and what this code chose, is listed in
274
+ [docs/DESIGN.md](docs/DESIGN.md) (D1–D64).
275
+
276
+ ## Graph view
277
+
278
+ `spectrag graph` (or `spectrag.utils.graph_view.save_graph_view`) writes one self-contained HTML
279
+ file, similar to Figure 5 of the paper. Chunks are drawn as nodes, starting from their spectral
280
+ coordinates, and edges are coloured by their strongest signal. For a question it shows the
281
+ retrieval path: seeds, chunks reached by expansion, and the selected context. Hover for a
282
+ chunk's text, click to highlight its neighbours, scroll to zoom, drag to pan, and hide signals
283
+ with the checkboxes. It needs no internet. Example: [`examples/graph_view.html`](examples/graph_view.html)
284
+ (download and open it in a browser).
285
+
286
+ <p align="center"><img src="docs/assets/graph_view.png" alt="Graph view of 600 MultiHopRAG chunks with the selected context for one question highlighted" width="100%"></p>
287
+
288
+ ## Configuration
289
+
290
+ Settings are a plain dict. Pass changes to `SpectRAGIngestion(dir, settings)`,
291
+ `SpectRAGRetrieval(dir, settings)`, `search(q, settings=...)`, or `--set` on the CLI. Every
292
+ value is checked: a typo gets "did you mean …?", a bad value says which range is allowed.
293
+ **Source** says whether the default comes from the paper or was chosen because the paper gives no value.
294
+
295
+ <details open>
296
+ <summary><b>Chunking (ingestion)</b></summary>
297
+
298
+ | Setting | Default | Meaning | Source |
299
+ |---|---|---|---|
300
+ | `chunk_tokens` / `overlap_tokens` | 1200 / 100 | maximum chunk size and overlap, in tokens | paper |
301
+ | `min_chunk_tokens` | 32 | smaller chunks are merged into the previous one | paper |
302
+ | `semantic_percentile` | 90 | topic breaks at this percentile of sentence distances | paper |
303
+ | `semantic_embedder` | `None` | embedder for those distances; `None` = the same as `embedder`, `"hash"` = much faster | chosen |
304
+
305
+ </details>
306
+
307
+ <details>
308
+ <summary><b>Embedding (ingestion)</b></summary>
309
+
310
+ | Setting | Default | Meaning | Source |
311
+ |---|---|---|---|
312
+ | `embedder` | `"hash"` | `"hash"` (offline), `"ollama"`, or a function `texts -> vectors` | chosen |
313
+ | `embed_dims` | 768 | size of the hash vectors | paper |
314
+ | `ollama_model` / `ollama_url` | `nomic-embed-text` / `http://localhost:11434` | Ollama embedding model and server | paper |
315
+
316
+ </details>
317
+
318
+ <details>
319
+ <summary><b>Vector search</b></summary>
320
+
321
+ | Setting | Default | Meaning | Source |
322
+ |---|---|---|---|
323
+ | `ann_backend` | `"auto"` | `"exact"`, `"faiss"`, `"hnsw"`, or `"auto"` (exact up to 20,000 chunks) | chosen |
324
+ | `hnsw_m` / `hnsw_ef_construction` / `hnsw_ef_search` | 32 / 200 / 128 | HNSW graph size and search effort | chosen |
325
+ | `dense_top_n` | 1000 | with an approximate backend, dense scores for the top *n* chunks only | chosen |
326
+
327
+ </details>
328
+
329
+ <details>
330
+ <summary><b>Graph (ingestion; change later with <code>rebuild_graph()</code>)</b></summary>
331
+
332
+ | Setting | Default | Meaning | Source |
333
+ |---|---|---|---|
334
+ | `edge_weights` | semantic .300, section .250, entity .200, adjacency .084, utility .083, citation .083 | α of Eq. 10 (paper configuration 1); empty signals share their weight | paper |
335
+ | `semantic_k` | 10 | nearest neighbours per chunk for semantic and utility edges | chosen |
336
+ | `edge_threshold` | 0.05 | τ: fused edges below this are dropped | chosen |
337
+ | `graph_k` | 10 | each chunk keeps at most its `graph_k` strongest edges | chosen |
338
+ | `spectral_dims` | 32 | spectral coordinates per chunk | paper |
339
+ | `n_clusters` | `None` | spectral clusters; `None` = about √(n/2) | chosen |
340
+
341
+ </details>
342
+
343
+ <details>
344
+ <summary><b>Retrieval</b></summary>
345
+
346
+ | Setting | Default | Meaning | Source |
347
+ |---|---|---|---|
348
+ | `seed_count` | 20 | seeds from hybrid search | paper |
349
+ | `hops` / `max_candidates` | 2 / 200 | graph expansion depth and cap | paper |
350
+ | `token_budget` | 12000 | tokens of context per question | paper |
351
+ | `rrf_k` | 60 | RRF constant | chosen |
352
+ | `bm25_k1` / `bm25_b` | 1.5 / 0.75 | BM25 parameters | chosen |
353
+ | `bm25_weight` | 0.5 | hybrid relevance = (1 − w)·dense + w·BM25 | chosen |
354
+ | `alpha` | 0.3 | weight of graph proximity in the re-score | chosen |
355
+ | `proximity_mode` | `"hybrid"` | `"hybrid"` (PageRank + spectral), `"ppr"`, `"spectral"`, `"heat"` (Eq. 17), `"none"` | paper |
356
+ | `ppr_beta` / `ppr_steps` | 0.15 / 30 | PageRank restart share and iterations (Eq. 18) | chosen |
357
+ | `diffusion_t` | 1.0 | heat-kernel scale t | chosen |
358
+
359
+ </details>
360
+
361
+ <details>
362
+ <summary><b>Selection</b></summary>
363
+
364
+ | Setting | Default | Meaning | Source |
365
+ |---|---|---|---|
366
+ | `selector` | `"spectrag"` | `"spectrag"`, `"mmr"`, `"protected_mmr"`, `"anchor_expand_ce"`, `"topk"` | paper |
367
+ | `core_size` | 3 | protected core (and anchors) | chosen |
368
+ | `precision_floor` | 0.4 | greedy-tail candidates must score ≥ this × the best score | chosen |
369
+ | `select_weights` | a 1.0, b 0.3, c 0.2, d 0.1, λ 0.5 | weights of Eq. 21 | chosen |
370
+ | `length_power` | 0.5 | ρ of Eq. 22 (how much short chunks are preferred) | chosen |
371
+ | `mmr_lambda` | 0.7 | MMR: relevance vs. novelty | chosen |
372
+
373
+ </details>
374
+
375
+ > [!NOTE]
376
+ > The defaults of this first release follow the paper where it gives values. On MultiHopRAG,
377
+ > settings tuned on validation questions were clearly better (see the benchmark); tuned
378
+ > defaults are planned for a later release.
379
+
380
+ ### Tuning
381
+
382
+ ```python
383
+ from spectrag import SpectRAGIngestion, SpectRAGRetrieval
384
+ from spectrag.utils.evaluation import load_questions
385
+ from spectrag.utils.tuning import tune
386
+
387
+ SpectRAGIngestion("eval_index").ingest("examples/eval/docs") # the documents the questions are about
388
+ search = SpectRAGRetrieval("eval_index")
389
+ questions = load_questions("examples/eval/questions.json") # [{"question", "evidence": [...]}, ...]
390
+ grid = {"alpha": [0.1, 0.3, 0.5], "selector": ["spectrag", "protected_mmr"], "edge_threshold": [0.05, 0.1]}
391
+ results = tune(search, questions, grid, objective="recall", budget=4000, trials=10)
392
+ print(results[0]) # best settings and their scores
393
+ ```
394
+
395
+ Graph settings (`edge_threshold`, `graph_k`, `edge_weights`, `spectral_dims`, `n_clusters`) are
396
+ applied by `search.rebuild_graph({...})` from the saved signals, so nothing is embedded again.
397
+
398
+ ### Your own models
399
+
400
+ | Plug-in | Where | Signature |
401
+ |---|---|---|
402
+ | Embedder | `settings={"embedder": fn}` (pass `embed_fn=fn` again when searching) | `fn(texts) -> vectors` |
403
+ | LLM for answers | `search.answer(question, llm_fn)` | `llm_fn(prompt) -> text` |
404
+ | Entity extractor | `SpectRAGIngestion(..., entity_fn=fn)` | `fn(text) -> list of strings` |
405
+ | Utility questions | `SpectRAGIngestion(..., question_fn=make_question_fn(llm_fn))` | `fn(text) -> list of questions` |
406
+ | Cross-encoder | `SpectRAGRetrieval(..., rerank_fn=fn)` with `selector="anchor_expand_ce"` | `fn(question, texts) -> scores` |
407
+
408
+ ### Errors and logging
409
+
410
+ All errors raised on purpose subclass `spectrag.SpectRAGError` and the matching built-in:
411
+ `SettingsError` (`ValueError`), `UnknownSettingError` (`KeyError`), `IndexError_`
412
+ (`FileNotFoundError`), `EmbedderError` (`ConnectionError`), `DocumentError` (`ValueError`).
413
+ SpectRAG is silent by default; `spectrag.enable_logging()` prints one timed line per pipeline
414
+ step, and `enable_logging("DEBUG")` one line per query.
415
+
416
+ ## Benchmark: MultiHopRAG
417
+
418
+ Real runs on [MultiHopRAG](https://arxiv.org/abs/2401.15391): 609 news articles, 7,807 chunks,
419
+ `nomic-embed-text` embeddings, a **12,000-token budget for every method**. 300 questions were
420
+ used only for tuning; all numbers below are on the other **1,955 test questions**.
421
+
422
+ | Method | Recall@5 | Recall@10 | Evidence recall (budget) | All evidence found | MRR | ms / query |
423
+ |---|---|---|---|---|---|---|
424
+ | Standard RAG (dense top-k) | 0.355 | 0.483 | 0.758 | 0.512 | 0.507 | 1.3 |
425
+ | BM25 | 0.462 | 0.577 | 0.788 | 0.545 | 0.617 | 1.0 |
426
+ | Dense + MMR | 0.359 | 0.482 | 0.756 | 0.507 | 0.508 | 1.3 |
427
+ | Hybrid RAG (dense + BM25, RRF) | 0.445 | 0.574 | 0.832 | 0.615 | 0.609 | 2.8 |
428
+ | SpectRAG, default settings | 0.385 | 0.433 | 0.803 | 0.550 | 0.592 | 4.4 |
429
+ | **SpectRAG, tuned on validation** | **0.470** | **0.592** | **0.846** | **0.639** | **0.617** | 3.5 |
430
+
431
+ <p align="center"><img src="benchmarks/results/multihoprag/recall_at_k_chunk1200.svg" alt="Recall at 2, 5 and 10 per method" width="49%"> <img src="benchmarks/results/multihoprag/budget_chunk1200.svg" alt="Evidence recall and all evidence found within the budget per method" width="49%"></p>
432
+
433
+ - **Tuned SpectRAG beats hybrid RAG**: evidence recall +0.014 (95% CI +0.007 … +0.021),
434
+ Recall@10 +0.017 (+0.009 … +0.025). Its largest gain is on **inference** questions
435
+ (0.802 vs 0.757); on comparison questions hybrid stays slightly ahead, as in the paper.
436
+ - Removing graph expansion drops evidence recall to 0.705: the graph walk is where most of the
437
+ extra evidence comes from.
438
+ - **Smaller tests:** HyDE (60 questions): 0.760, against dense 0.807. Answers with `gemma3:4b`
439
+ (30 questions): exact match 0.400 tuned SpectRAG, 0.333 dense, 0.267 hybrid (one answer = 0.033).
440
+ LightRAG on a 4-article subset could not be compared fairly (the subset fits in the budget), and
441
+ it needed about 225 s of LLM time per 1,000-word article to index.
442
+
443
+ > [!IMPORTANT]
444
+ > **The default settings are weaker than hybrid RAG** (0.803 vs 0.832). The paper's greedy
445
+ > selector with ρ = 0.5 (a value the paper does not give) prefers very short chunks. With
446
+ > `length_power = 0`, Recall@10 rises from 0.433 to 0.580, and the `topk` / `mmr` selectors reach
447
+ > 0.845 with no tuning. Tune on your own validation questions before relying on the defaults.
448
+
449
+ Reproduce (needs Ollama; quick mode takes minutes, `SPECTRAG_BENCH_FULL=1` runs the full version):
450
+
451
+ ```bash
452
+ python benchmarks/multihoprag_benchmark.py # index, tune, evaluate, latency
453
+ python benchmarks/mhr_llm_steps.py hyde # and: answers
454
+ python benchmarks/mhr_report.py # REPORT.md and the charts
455
+ python benchmarks/ann_benchmark.py # exact vs FAISS vs HNSW
456
+ ```
457
+
458
+ Full results, per-type tables, ablations and the method: [benchmarks/results/multihoprag/REPORT.md](benchmarks/results/multihoprag/REPORT.md)
459
+ and [docs/PROGRESS.md](docs/PROGRESS.md). The dataset (ODC-BY) is stored in
460
+ [`benchmarks/data/multihoprag/`](benchmarks/data/multihoprag/SOURCE.md) with checksums.
461
+
462
+ <details>
463
+ <summary><b>Scale and memory</b></summary>
464
+
465
+ | Corpus | Ingestion | Search (median) | Index | Memory |
466
+ |---|---|---|---|---|
467
+ | MultiHopRAG, 609 articles → 10,335 chunks (hash embedder) | 7.7 s | 4.1 ms | 49 MB | about 1 GB peak during ingestion |
468
+ | MultiHopRAG, 7,807 chunks (nomic-embed-text) | dominated by embedding through Ollama | 3.5–4.4 ms + 19 ms query embedding | 39.5 MB | 256 MB after loading |
469
+ | 100,000 synthetic 768-d vectors, kNN graph | exact 70.9 s, **FAISS 10.4 s** (same edges) | | | |
470
+
471
+ </details>
472
+
473
+ ## Project layout
474
+
475
+ <details>
476
+ <summary><b>Show the folders and modules</b></summary>
477
+
478
+ ```
479
+ src/spectrag/
480
+ ingestion.py, retrieval.py the two main classes
481
+ config.py, validation.py settings and their checks
482
+ errors.py, log.py, cli.py exceptions, logging, the spectrag command
483
+ utils/ one small module per step: loader, tokens, sections, units,
484
+ chunker, embedder, entities, references, questions, edges*,
485
+ graph, graph_build, spectral, clusters, vector_index, bm25,
486
+ seeding, expansion, diffusion, selection, selectors, prompt,
487
+ llm, metrics, evaluation, tuning, graph_view, store
488
+ quickstart.py runs with no arguments
489
+ examples/ sample documents, a 14-document evaluation set, demo scripts
490
+ benchmarks/ MultiHopRAG and ANN benchmarks, their data and results
491
+ tests/ unit, integration and equivalence tests
492
+ docs/ the paper, DESIGN.md, PROGRESS.md, PRODUCTION_READINESS.md,
493
+ DEVELOPMENT_LOG.md
494
+ tools/ validate_release.py (release checks on a real index)
495
+ ```
496
+
497
+ </details>
498
+
499
+ Every module is short (under about 150 lines), and functions do one thing.
500
+
501
+ ## Testing
502
+
503
+ ```bash
504
+ pytest -q # 300+ tests, under 10 seconds, offline
505
+ ```
506
+
507
+ The tests cover every formula against hand-computed or closed-form values (BM25, RRF,
508
+ PageRank, the heat kernel against `scipy.linalg.expm`, the sparse eigensolver against the dense
509
+ one, the paper's metrics). The fast vectorised code is checked against simple loop versions on
510
+ random cases, and the full pipeline runs end to end on real documents. Live Ollama tests run
511
+ when Ollama is available (`SPECTRAG_LIVE_LLM=1` for the LLM test). CI runs Linux and macOS ×
512
+ Python 3.10 / 3.12 / 3.14 × minimal / all extras, and builds and installs the wheel.
513
+
514
+ Before a release, `python tools/validate_release.py` re-checks the mathematics on the real
515
+ MultiHopRAG index (eigenpairs, PageRank, BM25, every selector and proximity mode) and that the
516
+ benchmark reproduces. The results are in the
517
+ [production-readiness report](docs/PRODUCTION_READINESS.md).
518
+
519
+ ## Limitations
520
+
521
+ - The default settings are not tuned (see the benchmark). Tuning on your own validation
522
+ questions is recommended.
523
+ - Entity extraction is rule-based unless you pass an `entity_fn`; utility questions need an LLM.
524
+ - Semantic edges and the dense eigensolver are `O(n²)` without the `scale` extra.
525
+ - The benchmark is a quick-mode run on one dataset; LightRAG was only compared on a tiny subset.
526
+ - On macOS with numpy 2.2 (Python 3.10), matrix products print spurious `RuntimeWarning`s; the
527
+ results are correct.
528
+
529
+ More: [docs/DESIGN.md](docs/DESIGN.md) (every decision), [docs/PROGRESS.md](docs/PROGRESS.md)
530
+ (the upgrade, with measurements), [CHANGELOG.md](CHANGELOG.md).
531
+
532
+ ## Citation
533
+
534
+ If you use SpectRAG, please cite the paper:
535
+
536
+ ```bibtex
537
+ @article{sahinoglu2026spectrag,
538
+ title = {SpectRAG: Weighted Chunk Graphs for Token-Budgeted Context Selection in
539
+ Multi-Hop Retrieval-Augmented Generation},
540
+ author = {Sahinoglu, Zafer and Mohammed, Abdulazeez and Kazangirler, Buse Yaren and
541
+ Kazangirler, Cahit Berkay},
542
+ journal = {arXiv preprint arXiv:2610.36991},
543
+ year = {2026}
544
+ }
545
+ ```
546
+
547
+ ## License
548
+
549
+ MIT, see [LICENSE](LICENSE). The MultiHopRAG data in `benchmarks/data/` is ODC-BY
550
+ (see its [SOURCE.md](benchmarks/data/multihoprag/SOURCE.md)).