terag 0.5.5__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 (37) hide show
  1. terag-0.5.5/LICENSE +21 -0
  2. terag-0.5.5/MANIFEST.in +5 -0
  3. terag-0.5.5/PKG-INFO +325 -0
  4. terag-0.5.5/README.md +273 -0
  5. terag-0.5.5/pyproject.toml +47 -0
  6. terag-0.5.5/requirements.txt +11 -0
  7. terag-0.5.5/setup.cfg +4 -0
  8. terag-0.5.5/terag/examples/example_usage.py +149 -0
  9. terag-0.5.5/terag/terag/__init__.py +10 -0
  10. terag-0.5.5/terag/terag/core.py +350 -0
  11. terag-0.5.5/terag/terag/embeddings/__init__.py +2 -0
  12. terag-0.5.5/terag/terag/embeddings/cache.py +482 -0
  13. terag-0.5.5/terag/terag/embeddings/manager.py +442 -0
  14. terag-0.5.5/terag/terag/graph/__init__.py +3 -0
  15. terag-0.5.5/terag/terag/graph/builder.py +763 -0
  16. terag-0.5.5/terag/terag/graph/deduplication.py +433 -0
  17. terag-0.5.5/terag/terag/graph/merger.py +329 -0
  18. terag-0.5.5/terag/terag/graph/types.py +22 -0
  19. terag-0.5.5/terag/terag/ingestion/__init__.py +3 -0
  20. terag-0.5.5/terag/terag/ingestion/groq_client.py +431 -0
  21. terag-0.5.5/terag/terag/ingestion/json_ingestion.py +536 -0
  22. terag-0.5.5/terag/terag/ingestion/ner_extraction.py +349 -0
  23. terag-0.5.5/terag/terag/ingestion/ner_extractor.py +692 -0
  24. terag-0.5.5/terag/terag/ingestion/pipeline.py +528 -0
  25. terag-0.5.5/terag/terag/retrieval/__init__.py +5 -0
  26. terag-0.5.5/terag/terag/retrieval/hybrid.py +550 -0
  27. terag-0.5.5/terag/terag/retrieval/ppr.py +466 -0
  28. terag-0.5.5/terag/terag/retrieval/query_processor.py +546 -0
  29. terag-0.5.5/terag/terag/retrieval/semantic.py +379 -0
  30. terag-0.5.5/terag/terag/utils/__init__.py +1 -0
  31. terag-0.5.5/terag/terag/utils/edge_weights.py +370 -0
  32. terag-0.5.5/terag/terag.egg-info/PKG-INFO +325 -0
  33. terag-0.5.5/terag/terag.egg-info/SOURCES.txt +35 -0
  34. terag-0.5.5/terag/terag.egg-info/dependency_links.txt +1 -0
  35. terag-0.5.5/terag/terag.egg-info/requires.txt +17 -0
  36. terag-0.5.5/terag/terag.egg-info/top_level.txt +3 -0
  37. terag-0.5.5/tests/test_core.py +38 -0
terag-0.5.5/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Rudra Naik
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,5 @@
1
+ include README.md
2
+ include LICENSE
3
+ include requirements.txt
4
+ recursive-include terag/data *
5
+ recursive-include terag/examples *
terag-0.5.5/PKG-INFO ADDED
@@ -0,0 +1,325 @@
1
+ Metadata-Version: 2.4
2
+ Name: terag
3
+ Version: 0.5.5
4
+ Summary: Token-Efficient Retrieval Augmented Generation with Graph-based Indexing
5
+ Author-email: Rudra Naik <rudra91@gmail.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2025 Rudra Naik
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://github.com/rudranaik/terag
29
+ Project-URL: Bug Tracker, https://github.com/rudranaik/terag/issues
30
+ Classifier: Programming Language :: Python :: 3
31
+ Classifier: License :: OSI Approved :: MIT License
32
+ Classifier: Operating System :: OS Independent
33
+ Requires-Python: >=3.8
34
+ Description-Content-Type: text/markdown
35
+ License-File: LICENSE
36
+ Requires-Dist: numpy
37
+ Requires-Dist: networkx
38
+ Requires-Dist: scikit-learn
39
+ Requires-Dist: openai
40
+ Requires-Dist: tiktoken
41
+ Requires-Dist: groq
42
+ Requires-Dist: python-dotenv
43
+ Requires-Dist: tqdm
44
+ Provides-Extra: dev
45
+ Requires-Dist: pytest; extra == "dev"
46
+ Requires-Dist: black; extra == "dev"
47
+ Requires-Dist: isort; extra == "dev"
48
+ Provides-Extra: fuzzy
49
+ Requires-Dist: fuzzywuzzy; extra == "fuzzy"
50
+ Requires-Dist: python-Levenshtein; extra == "fuzzy"
51
+ Dynamic: license-file
52
+
53
+ # TERAG: Token-Efficient Graph-Based RAG
54
+
55
+ **Token-Efficient Graph-Based Retrieval-Augmented Generation**
56
+
57
+ Based on the research paper: [arXiv:2509.18667](https://arxiv.org/abs/2509.18667) (September 2025)
58
+
59
+ ## Overview
60
+
61
+ TERAG is a lightweight graph-based RAG framework that achieves **80%+ of GraphRAG's accuracy while consuming only 3-11% of the output tokens**. It addresses the high cost associated with LLM token usage during graph construction that hinders large-scale adoption of graph-based RAG systems.
62
+
63
+ ## Key Advantages
64
+
65
+ - **Cost-Efficient**: 89-97% reduction in token consumption vs. traditional graph RAG
66
+ - **High Performance**: Matches GraphRAG accuracy (EM: 51.2 vs. 51.4; F1: 57.8 vs. 58.6)
67
+ - **Lightweight**: Minimal LLM usage - only for query NER and answer generation
68
+ - **Scalable**: Efficient for large document collections
69
+
70
+ ## Supported Features & Limitations
71
+
72
+ ### Supported Features
73
+ - **Graph Backend**: Built on **NetworkX** for efficient in-memory graph operations.
74
+ - **Ingestion**: Flexible JSON ingestion for chunks, Q&A pairs, and documents.
75
+ - **Retrieval Algorithms**:
76
+ - **Personalized PageRank (PPR)**: Biased random walks for entity-centric retrieval.
77
+ - **Hybrid Retrieval**: Combines PPR scores with semantic vector similarity.
78
+ - **Named Entity Recognition**:
79
+ - **LLM-based**: Uses Groq/OpenAI for high-accuracy extraction.
80
+ - **Regex Fallback**: Pattern-based extraction when LLM is unavailable.
81
+ - **Embeddings**: Integrated with **SentenceTransformers** for local semantic search.
82
+
83
+ ### Limitations
84
+ - **Graph Database**: Currently supports **NetworkX** (in-memory) only. Native support for **Neo4j** or **ArangoDB** is **NOT** currently implemented.
85
+ - **Scalability**: Best suited for small to medium-sized graphs (up to ~100k nodes) that fit in memory.
86
+
87
+ ## Architecture
88
+
89
+ ### 1. Graph Construction
90
+
91
+ TERAG uses a directed, unweighted graph **G = (V, E)** where:
92
+ - **Nodes (V)**:
93
+ - **Passage nodes** (squares): Document chunks/passages
94
+ - **Concept nodes** (circles): Named entities and document-level concepts
95
+ - **Edges (E ⊆ V×V)**: Directed connections between passages and concepts
96
+ - **Storage**: Adjacency lists for efficient neighborhood expansion
97
+
98
+ ### Visual Representation
99
+
100
+ ![TERAG Graph Structure](https://github.com/rudranaik/terag/blob/main/docs/images/graph_structure.png?raw=true)
101
+
102
+ **Legend:**
103
+ - **Passage Nodes (White Squares)**: The actual text chunks from your documents.
104
+ - **Entity Nodes (Blue Circles)**: Specific named entities (People, Orgs, Dates).
105
+ - **Concept Nodes (Purple Circles)**: Abstract topics or themes shared across passages.
106
+ - **Edges**: Bidirectional links. If Passage 1 mentions "Apple", they are connected. This allows the retrieval to "hop" from one passage to another via shared concepts.
107
+
108
+ ### 2. Concept Extraction
109
+
110
+ Lightweight concept extraction focusing on:
111
+ - **Named Entities**: People, organizations, locations, dates (dark green circles)
112
+ - **Document-level Concepts**: Key topics, themes, technical terms (dark blue circles)
113
+ - **Non-LLM Clustering**: Efficient grouping without heavy LLM usage
114
+
115
+ ### 3. Retrieval Algorithm
116
+
117
+ **Personalized PageRank (PPR)** inspired by HippoRAG:
118
+
119
+ 1. **Query NER**: Few-shot prompt extracts named entities from user query
120
+ 2. **Node Matching**: Match query entities to graph concepts
121
+ 3. **PPR Computation**: Run PPR biased towards query-relevant nodes
122
+ 4. **Weighting**: Combine frequency and semantic weights
123
+ 5. **Passage Ranking**: Return top-k most relevant passages
124
+
125
+ ### 4. Weighting Scheme
126
+
127
+ Each matched node receives an unnormalized weight:
128
+
129
+ ```
130
+ weight(node) = frequency_weight(node) × semantic_weight(node)
131
+ ```
132
+
133
+ - **Frequency Weight**: Inverse of concept frequency (rarer = more important)
134
+ - **Semantic Weight**: Embedding similarity between query and concept
135
+
136
+ ## Performance Comparison
137
+
138
+ | Method | Accuracy | Token Consumption | Relative Cost (per token to be ingested) |
139
+ |--------|----------|-------------------|---------------|
140
+ | **Nano-GraphRAG** | 100% baseline | 100% baseline | 80-200x (personal experience)|
141
+ | **LightRAG** | ~75% | ~30% | High |
142
+ | **MiniRAG** | ~70% | ~25% | High |
143
+ | **TERAG** | 80-90% | 3-11% | **3-5x** |
144
+
145
+ ## Algorithm Components
146
+
147
+ ### Graph Construction Phase
148
+
149
+ ```
150
+ 1. Chunk documents into passages (P1, P2, ..., Pn)
151
+ 2. For each passage Pi:
152
+ a. Extract named entities → ENT(Pi)
153
+ b. Extract document concepts → CON(Pi)
154
+ c. Create passage node → V_passage
155
+ 3. Cluster similar concepts (non-LLM)
156
+ 4. Create concept nodes → V_concepts
157
+ 5. Build edges:
158
+ - Pi → concept (if concept in Pi)
159
+ - concept → Pi (bidirectional)
160
+ 6. Store as adjacency list graph G = (V, E)
161
+ ```
162
+
163
+ ### Retrieval Phase
164
+
165
+ ```
166
+ 1. Query Q arrives
167
+ 2. Extract query entities → ENT(Q) [Few-shot LLM]
168
+ 3. Match ENT(Q) to graph concepts → matched_nodes
169
+ 4. Calculate restart vector R:
170
+ R[node] = freq_weight[node] × semantic_weight[node] for matched nodes
171
+ R[node] = 0 for unmatched nodes
172
+ 5. Run Personalized PageRank:
173
+ PPR(G, R, alpha=0.85, max_iter=100)
174
+ 6. Rank passages by PPR scores
175
+ 7. Return top-k passages
176
+ 8. Generate answer using LLM with retrieved passages
177
+ ```
178
+
179
+
180
+
181
+ ## Installation
182
+
183
+ ### From PyPI
184
+ ```bash
185
+ pip install terag
186
+ ```
187
+
188
+ ### From Source
189
+ ```bash
190
+ git clone https://github.com/rudranaik/terag.git
191
+ cd terag
192
+ pip install -e .
193
+ ```
194
+
195
+ ## Quick Start
196
+
197
+ Get started with TERAG in 3 simple steps:
198
+
199
+ ### 1. Setup
200
+ Ensure you have your API keys set (if using LLM features):
201
+ ```bash
202
+ export GROQ_API_KEY="your_key_here" # Optional: for LLM-based NER
203
+ export OPENAI_API_KEY="your_key_here" # Optional: for embeddings/LLM
204
+ ```
205
+
206
+ ### 2. Basic Usage
207
+ ```python
208
+ from terag import TERAG, TERAGConfig
209
+
210
+ # Define some sample data
211
+ # NOTE: The 'content' key is REQUIRED. It is the only field used for graph construction.
212
+ # 'metadata' is optional and stored but not used for indexing.
213
+ chunks = [
214
+ {"content": "Apple Inc announced strong revenue growth in Q4 2024.", "metadata": {"source": "news"}},
215
+ {"content": "Microsoft Corporation reported significant cloud achievements.", "metadata": {"source": "news"}}
216
+ ]
217
+
218
+ # Initialize TERAG
219
+ config = TERAGConfig(top_k=3)
220
+ terag = TERAG.from_chunks(chunks, config=config)
221
+
222
+ # Retrieve
223
+ results, metrics = terag.retrieve("What is the revenue growth?")
224
+
225
+ # Inspect results
226
+ for result in results:
227
+ print(f"Score: {result.score:.4f} | Content: {result.content}")
228
+ ```
229
+
230
+ ### 3. Visualization & Export
231
+ TERAG uses a custom JSON format for storage, but you can easily export to **GraphML** (supported by Gephi, Cytoscape, etc.) using NetworkX:
232
+
233
+ ```python
234
+ import networkx as nx
235
+
236
+ # Convert to NetworkX graph
237
+ G = terag.graph.to_networkx()
238
+
239
+ # Save as GraphML for visualization tools
240
+ nx.write_graphml(G, "terag_graph.graphml")
241
+ ```
242
+
243
+ ### 4. Advanced Usage
244
+ For more complex scenarios, including custom graph building and hybrid retrieval, check out `terag/examples/example_usage.py`.
245
+
246
+ ## Contributing
247
+
248
+ We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on how to help improve TERAG.
249
+
250
+ ## Configuration Guide
251
+
252
+ TERAG is highly configurable to suit different use cases. Here's what each setting does:
253
+
254
+ | Parameter | Default | Developer Explanation | Product/Business Impact |
255
+ |-----------|---------|-----------------------|-------------------------|
256
+ | `top_k` | `10` | Number of passages to return in the final result set. | **Response Depth**: Higher values give the LLM more context but increase costs and latency. Lower values are faster and cheaper but might miss details. |
257
+ | `min_concept_freq` | `2` | Minimum number of times a concept must appear in the corpus to be included in the graph. | **Noise Reduction**: Filters out one-off mentions or typos. Increase this for cleaner graphs from noisy data (e.g., social media). |
258
+ | `max_concept_freq_ratio` | `0.5` | Maximum ratio of documents a concept can appear in before being excluded (stopword filtering). | **Relevance**: Prevents common words (like "company" in a business report) from dominating the search results. |
259
+ | `ppr_alpha` | `0.15` | Damping factor for Personalized PageRank (teleport probability). | **Exploration vs. Focus**: Lower values explore further away from the query entities (finding indirect connections). Higher values stick closer to direct matches. |
260
+ | `semantic_weight` | `0.5` | Weight given to semantic similarity vs. frequency in the initial node scoring. | **Understanding**: Higher values prioritize concepts that *mean* the same thing as the query, even if spelled differently. |
261
+ | `use_llm_for_ner` | `False` | Whether to use an LLM (Groq/OpenAI) for Named Entity Recognition during ingestion/querying. | **Accuracy vs. Cost**: `True` gives much better entity extraction but costs money per query. `False` is free and fast but less accurate. |
262
+
263
+ ### Example Configuration
264
+
265
+ **For a high-precision legal search:**
266
+ ```python
267
+ config = TERAGConfig(
268
+ top_k=20, # Need comprehensive results
269
+ min_concept_freq=1, # Every detail matters
270
+ use_llm_for_ner=True, # Maximum accuracy required
271
+ ppr_alpha=0.1 # Explore indirect relationships
272
+ )
273
+ ```
274
+
275
+ **For a real-time news chatbot:**
276
+ ```python
277
+ config = TERAGConfig(
278
+ top_k=5, # Fast response needed
279
+ min_concept_freq=3, # Ignore noise
280
+ use_llm_for_ner=False, # Keep costs low
281
+ ppr_alpha=0.2 # Focus on direct matches
282
+ )
283
+ ```
284
+
285
+ - `terag/graph/builder.py`: Graph construction from chunks
286
+ - `terag/ingestion/ner_extractor.py`: Named Entity Recognition for queries/documents
287
+ - `terag/retrieval/ppr.py`: Personalized PageRank retrieval algorithm
288
+ - `terag/core.py`: Main TERAG retriever interface
289
+ - `terag/examples/example_usage.py`: Usage examples and integration tests
290
+ ```
291
+
292
+ ## Research References
293
+
294
+ - **TERAG Paper**: [arXiv:2509.18667](https://arxiv.org/abs/2509.18667) (2025)
295
+ - **HippoRAG**: Personalized PageRank for RAG (2024)
296
+ - **GraphRAG**: Microsoft's graph-based RAG (2023-2024)
297
+ - **Personalized PageRank**: Page et al., Stanford (1998)
298
+
299
+ ## Performance Metrics
300
+
301
+ ### Expected Results (based on paper)
302
+
303
+ - **Accuracy**: 80-90% of GraphRAG quality
304
+ - **Token Reduction**: 89-97% fewer tokens than GraphRAG
305
+ - **Retrieval Speed**: < 2 seconds per query
306
+ - **Graph Construction**: < 15 minutes for 400-page document
307
+
308
+ ### Our Implementation Goals
309
+
310
+ - Match paper's token efficiency (3-11% consumption)
311
+ - Achieve F1 score > 55% on multi-hop queries
312
+ - Support 100K+ node graphs efficiently
313
+ - Support 100K+ node graphs efficiently
314
+
315
+ ## Future Enhancements
316
+
317
+ - [ ] Support for dynamic graph updates
318
+ - [ ] Advanced concept clustering (embeddings-based)
319
+ - [ ] Multi-hop reasoning chains visualization
320
+ - [ ] Hybrid retrieval combining TERAG + dense vectors
321
+ - [ ] Real-time graph construction for streaming documents
322
+
323
+ ## License
324
+
325
+ MIT License
terag-0.5.5/README.md ADDED
@@ -0,0 +1,273 @@
1
+ # TERAG: Token-Efficient Graph-Based RAG
2
+
3
+ **Token-Efficient Graph-Based Retrieval-Augmented Generation**
4
+
5
+ Based on the research paper: [arXiv:2509.18667](https://arxiv.org/abs/2509.18667) (September 2025)
6
+
7
+ ## Overview
8
+
9
+ TERAG is a lightweight graph-based RAG framework that achieves **80%+ of GraphRAG's accuracy while consuming only 3-11% of the output tokens**. It addresses the high cost associated with LLM token usage during graph construction that hinders large-scale adoption of graph-based RAG systems.
10
+
11
+ ## Key Advantages
12
+
13
+ - **Cost-Efficient**: 89-97% reduction in token consumption vs. traditional graph RAG
14
+ - **High Performance**: Matches GraphRAG accuracy (EM: 51.2 vs. 51.4; F1: 57.8 vs. 58.6)
15
+ - **Lightweight**: Minimal LLM usage - only for query NER and answer generation
16
+ - **Scalable**: Efficient for large document collections
17
+
18
+ ## Supported Features & Limitations
19
+
20
+ ### Supported Features
21
+ - **Graph Backend**: Built on **NetworkX** for efficient in-memory graph operations.
22
+ - **Ingestion**: Flexible JSON ingestion for chunks, Q&A pairs, and documents.
23
+ - **Retrieval Algorithms**:
24
+ - **Personalized PageRank (PPR)**: Biased random walks for entity-centric retrieval.
25
+ - **Hybrid Retrieval**: Combines PPR scores with semantic vector similarity.
26
+ - **Named Entity Recognition**:
27
+ - **LLM-based**: Uses Groq/OpenAI for high-accuracy extraction.
28
+ - **Regex Fallback**: Pattern-based extraction when LLM is unavailable.
29
+ - **Embeddings**: Integrated with **SentenceTransformers** for local semantic search.
30
+
31
+ ### Limitations
32
+ - **Graph Database**: Currently supports **NetworkX** (in-memory) only. Native support for **Neo4j** or **ArangoDB** is **NOT** currently implemented.
33
+ - **Scalability**: Best suited for small to medium-sized graphs (up to ~100k nodes) that fit in memory.
34
+
35
+ ## Architecture
36
+
37
+ ### 1. Graph Construction
38
+
39
+ TERAG uses a directed, unweighted graph **G = (V, E)** where:
40
+ - **Nodes (V)**:
41
+ - **Passage nodes** (squares): Document chunks/passages
42
+ - **Concept nodes** (circles): Named entities and document-level concepts
43
+ - **Edges (E ⊆ V×V)**: Directed connections between passages and concepts
44
+ - **Storage**: Adjacency lists for efficient neighborhood expansion
45
+
46
+ ### Visual Representation
47
+
48
+ ![TERAG Graph Structure](https://github.com/rudranaik/terag/blob/main/docs/images/graph_structure.png?raw=true)
49
+
50
+ **Legend:**
51
+ - **Passage Nodes (White Squares)**: The actual text chunks from your documents.
52
+ - **Entity Nodes (Blue Circles)**: Specific named entities (People, Orgs, Dates).
53
+ - **Concept Nodes (Purple Circles)**: Abstract topics or themes shared across passages.
54
+ - **Edges**: Bidirectional links. If Passage 1 mentions "Apple", they are connected. This allows the retrieval to "hop" from one passage to another via shared concepts.
55
+
56
+ ### 2. Concept Extraction
57
+
58
+ Lightweight concept extraction focusing on:
59
+ - **Named Entities**: People, organizations, locations, dates (dark green circles)
60
+ - **Document-level Concepts**: Key topics, themes, technical terms (dark blue circles)
61
+ - **Non-LLM Clustering**: Efficient grouping without heavy LLM usage
62
+
63
+ ### 3. Retrieval Algorithm
64
+
65
+ **Personalized PageRank (PPR)** inspired by HippoRAG:
66
+
67
+ 1. **Query NER**: Few-shot prompt extracts named entities from user query
68
+ 2. **Node Matching**: Match query entities to graph concepts
69
+ 3. **PPR Computation**: Run PPR biased towards query-relevant nodes
70
+ 4. **Weighting**: Combine frequency and semantic weights
71
+ 5. **Passage Ranking**: Return top-k most relevant passages
72
+
73
+ ### 4. Weighting Scheme
74
+
75
+ Each matched node receives an unnormalized weight:
76
+
77
+ ```
78
+ weight(node) = frequency_weight(node) × semantic_weight(node)
79
+ ```
80
+
81
+ - **Frequency Weight**: Inverse of concept frequency (rarer = more important)
82
+ - **Semantic Weight**: Embedding similarity between query and concept
83
+
84
+ ## Performance Comparison
85
+
86
+ | Method | Accuracy | Token Consumption | Relative Cost (per token to be ingested) |
87
+ |--------|----------|-------------------|---------------|
88
+ | **Nano-GraphRAG** | 100% baseline | 100% baseline | 80-200x (personal experience)|
89
+ | **LightRAG** | ~75% | ~30% | High |
90
+ | **MiniRAG** | ~70% | ~25% | High |
91
+ | **TERAG** | 80-90% | 3-11% | **3-5x** |
92
+
93
+ ## Algorithm Components
94
+
95
+ ### Graph Construction Phase
96
+
97
+ ```
98
+ 1. Chunk documents into passages (P1, P2, ..., Pn)
99
+ 2. For each passage Pi:
100
+ a. Extract named entities → ENT(Pi)
101
+ b. Extract document concepts → CON(Pi)
102
+ c. Create passage node → V_passage
103
+ 3. Cluster similar concepts (non-LLM)
104
+ 4. Create concept nodes → V_concepts
105
+ 5. Build edges:
106
+ - Pi → concept (if concept in Pi)
107
+ - concept → Pi (bidirectional)
108
+ 6. Store as adjacency list graph G = (V, E)
109
+ ```
110
+
111
+ ### Retrieval Phase
112
+
113
+ ```
114
+ 1. Query Q arrives
115
+ 2. Extract query entities → ENT(Q) [Few-shot LLM]
116
+ 3. Match ENT(Q) to graph concepts → matched_nodes
117
+ 4. Calculate restart vector R:
118
+ R[node] = freq_weight[node] × semantic_weight[node] for matched nodes
119
+ R[node] = 0 for unmatched nodes
120
+ 5. Run Personalized PageRank:
121
+ PPR(G, R, alpha=0.85, max_iter=100)
122
+ 6. Rank passages by PPR scores
123
+ 7. Return top-k passages
124
+ 8. Generate answer using LLM with retrieved passages
125
+ ```
126
+
127
+
128
+
129
+ ## Installation
130
+
131
+ ### From PyPI
132
+ ```bash
133
+ pip install terag
134
+ ```
135
+
136
+ ### From Source
137
+ ```bash
138
+ git clone https://github.com/rudranaik/terag.git
139
+ cd terag
140
+ pip install -e .
141
+ ```
142
+
143
+ ## Quick Start
144
+
145
+ Get started with TERAG in 3 simple steps:
146
+
147
+ ### 1. Setup
148
+ Ensure you have your API keys set (if using LLM features):
149
+ ```bash
150
+ export GROQ_API_KEY="your_key_here" # Optional: for LLM-based NER
151
+ export OPENAI_API_KEY="your_key_here" # Optional: for embeddings/LLM
152
+ ```
153
+
154
+ ### 2. Basic Usage
155
+ ```python
156
+ from terag import TERAG, TERAGConfig
157
+
158
+ # Define some sample data
159
+ # NOTE: The 'content' key is REQUIRED. It is the only field used for graph construction.
160
+ # 'metadata' is optional and stored but not used for indexing.
161
+ chunks = [
162
+ {"content": "Apple Inc announced strong revenue growth in Q4 2024.", "metadata": {"source": "news"}},
163
+ {"content": "Microsoft Corporation reported significant cloud achievements.", "metadata": {"source": "news"}}
164
+ ]
165
+
166
+ # Initialize TERAG
167
+ config = TERAGConfig(top_k=3)
168
+ terag = TERAG.from_chunks(chunks, config=config)
169
+
170
+ # Retrieve
171
+ results, metrics = terag.retrieve("What is the revenue growth?")
172
+
173
+ # Inspect results
174
+ for result in results:
175
+ print(f"Score: {result.score:.4f} | Content: {result.content}")
176
+ ```
177
+
178
+ ### 3. Visualization & Export
179
+ TERAG uses a custom JSON format for storage, but you can easily export to **GraphML** (supported by Gephi, Cytoscape, etc.) using NetworkX:
180
+
181
+ ```python
182
+ import networkx as nx
183
+
184
+ # Convert to NetworkX graph
185
+ G = terag.graph.to_networkx()
186
+
187
+ # Save as GraphML for visualization tools
188
+ nx.write_graphml(G, "terag_graph.graphml")
189
+ ```
190
+
191
+ ### 4. Advanced Usage
192
+ For more complex scenarios, including custom graph building and hybrid retrieval, check out `terag/examples/example_usage.py`.
193
+
194
+ ## Contributing
195
+
196
+ We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on how to help improve TERAG.
197
+
198
+ ## Configuration Guide
199
+
200
+ TERAG is highly configurable to suit different use cases. Here's what each setting does:
201
+
202
+ | Parameter | Default | Developer Explanation | Product/Business Impact |
203
+ |-----------|---------|-----------------------|-------------------------|
204
+ | `top_k` | `10` | Number of passages to return in the final result set. | **Response Depth**: Higher values give the LLM more context but increase costs and latency. Lower values are faster and cheaper but might miss details. |
205
+ | `min_concept_freq` | `2` | Minimum number of times a concept must appear in the corpus to be included in the graph. | **Noise Reduction**: Filters out one-off mentions or typos. Increase this for cleaner graphs from noisy data (e.g., social media). |
206
+ | `max_concept_freq_ratio` | `0.5` | Maximum ratio of documents a concept can appear in before being excluded (stopword filtering). | **Relevance**: Prevents common words (like "company" in a business report) from dominating the search results. |
207
+ | `ppr_alpha` | `0.15` | Damping factor for Personalized PageRank (teleport probability). | **Exploration vs. Focus**: Lower values explore further away from the query entities (finding indirect connections). Higher values stick closer to direct matches. |
208
+ | `semantic_weight` | `0.5` | Weight given to semantic similarity vs. frequency in the initial node scoring. | **Understanding**: Higher values prioritize concepts that *mean* the same thing as the query, even if spelled differently. |
209
+ | `use_llm_for_ner` | `False` | Whether to use an LLM (Groq/OpenAI) for Named Entity Recognition during ingestion/querying. | **Accuracy vs. Cost**: `True` gives much better entity extraction but costs money per query. `False` is free and fast but less accurate. |
210
+
211
+ ### Example Configuration
212
+
213
+ **For a high-precision legal search:**
214
+ ```python
215
+ config = TERAGConfig(
216
+ top_k=20, # Need comprehensive results
217
+ min_concept_freq=1, # Every detail matters
218
+ use_llm_for_ner=True, # Maximum accuracy required
219
+ ppr_alpha=0.1 # Explore indirect relationships
220
+ )
221
+ ```
222
+
223
+ **For a real-time news chatbot:**
224
+ ```python
225
+ config = TERAGConfig(
226
+ top_k=5, # Fast response needed
227
+ min_concept_freq=3, # Ignore noise
228
+ use_llm_for_ner=False, # Keep costs low
229
+ ppr_alpha=0.2 # Focus on direct matches
230
+ )
231
+ ```
232
+
233
+ - `terag/graph/builder.py`: Graph construction from chunks
234
+ - `terag/ingestion/ner_extractor.py`: Named Entity Recognition for queries/documents
235
+ - `terag/retrieval/ppr.py`: Personalized PageRank retrieval algorithm
236
+ - `terag/core.py`: Main TERAG retriever interface
237
+ - `terag/examples/example_usage.py`: Usage examples and integration tests
238
+ ```
239
+
240
+ ## Research References
241
+
242
+ - **TERAG Paper**: [arXiv:2509.18667](https://arxiv.org/abs/2509.18667) (2025)
243
+ - **HippoRAG**: Personalized PageRank for RAG (2024)
244
+ - **GraphRAG**: Microsoft's graph-based RAG (2023-2024)
245
+ - **Personalized PageRank**: Page et al., Stanford (1998)
246
+
247
+ ## Performance Metrics
248
+
249
+ ### Expected Results (based on paper)
250
+
251
+ - **Accuracy**: 80-90% of GraphRAG quality
252
+ - **Token Reduction**: 89-97% fewer tokens than GraphRAG
253
+ - **Retrieval Speed**: < 2 seconds per query
254
+ - **Graph Construction**: < 15 minutes for 400-page document
255
+
256
+ ### Our Implementation Goals
257
+
258
+ - Match paper's token efficiency (3-11% consumption)
259
+ - Achieve F1 score > 55% on multi-hop queries
260
+ - Support 100K+ node graphs efficiently
261
+ - Support 100K+ node graphs efficiently
262
+
263
+ ## Future Enhancements
264
+
265
+ - [ ] Support for dynamic graph updates
266
+ - [ ] Advanced concept clustering (embeddings-based)
267
+ - [ ] Multi-hop reasoning chains visualization
268
+ - [ ] Hybrid retrieval combining TERAG + dense vectors
269
+ - [ ] Real-time graph construction for streaming documents
270
+
271
+ ## License
272
+
273
+ MIT License
@@ -0,0 +1,47 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "terag"
7
+ version = "0.5.5"
8
+ description = "Token-Efficient Retrieval Augmented Generation with Graph-based Indexing"
9
+ readme = "README.md"
10
+ authors = [
11
+ { name = "Rudra Naik", email = "rudra91@gmail.com" }
12
+ ]
13
+ license = { file = "LICENSE" }
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Operating System :: OS Independent",
18
+ ]
19
+ dependencies = [
20
+ "numpy",
21
+ "networkx",
22
+ "scikit-learn",
23
+ "openai",
24
+ "tiktoken",
25
+ "groq",
26
+ "python-dotenv",
27
+ "tqdm"
28
+ ]
29
+ requires-python = ">=3.8"
30
+
31
+ [project.optional-dependencies]
32
+ dev = [
33
+ "pytest",
34
+ "black",
35
+ "isort"
36
+ ]
37
+ fuzzy = [
38
+ "fuzzywuzzy",
39
+ "python-Levenshtein"
40
+ ]
41
+
42
+ [project.urls]
43
+ "Homepage" = "https://github.com/rudranaik/terag"
44
+ "Bug Tracker" = "https://github.com/rudranaik/terag/issues"
45
+
46
+ [tool.setuptools.packages.find]
47
+ where = ["terag"]
@@ -0,0 +1,11 @@
1
+ numpy>=1.21.0
2
+ sentence-transformers>=2.2.0 # Optional: for semantic weighting
3
+ networkx>=3.0
4
+ matplotlib>=3.5.0
5
+ plotly>=5.0.0
6
+ pyvis>=0.3.0
7
+ groq>=0.4.0 # For LLM API calls
8
+ requests>=2.28.0 # HTTP client
9
+ python-dotenv>=0.19.0 # Environment variable management
10
+ openai>=1.0.0 # For embedding API calls
11
+ scikit-learn>=1.0.0 # For cosine similarity calculations
terag-0.5.5/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+