terag 0.5.5__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- examples/example_usage.py +149 -0
- terag/__init__.py +10 -0
- terag/core.py +350 -0
- terag/embeddings/__init__.py +2 -0
- terag/embeddings/cache.py +482 -0
- terag/embeddings/manager.py +442 -0
- terag/graph/__init__.py +3 -0
- terag/graph/builder.py +763 -0
- terag/graph/deduplication.py +433 -0
- terag/graph/merger.py +329 -0
- terag/graph/types.py +22 -0
- terag/ingestion/__init__.py +3 -0
- terag/ingestion/groq_client.py +431 -0
- terag/ingestion/json_ingestion.py +536 -0
- terag/ingestion/ner_extraction.py +349 -0
- terag/ingestion/ner_extractor.py +692 -0
- terag/ingestion/pipeline.py +528 -0
- terag/retrieval/__init__.py +5 -0
- terag/retrieval/hybrid.py +550 -0
- terag/retrieval/ppr.py +466 -0
- terag/retrieval/query_processor.py +546 -0
- terag/retrieval/semantic.py +379 -0
- terag/utils/__init__.py +1 -0
- terag/utils/edge_weights.py +370 -0
- terag-0.5.5.dist-info/METADATA +325 -0
- terag-0.5.5.dist-info/RECORD +29 -0
- terag-0.5.5.dist-info/WHEEL +5 -0
- terag-0.5.5.dist-info/licenses/LICENSE +21 -0
- terag-0.5.5.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TERAG Example Usage
|
|
3
|
+
|
|
4
|
+
Demonstrates how to:
|
|
5
|
+
1. Build TERAG from existing chunks
|
|
6
|
+
2. Save and load graphs
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import sys
|
|
10
|
+
import os
|
|
11
|
+
import json
|
|
12
|
+
import argparse
|
|
13
|
+
from typing import List, Dict
|
|
14
|
+
|
|
15
|
+
# Add parent directory to path for imports
|
|
16
|
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
17
|
+
|
|
18
|
+
from terag import TERAG, TERAGConfig
|
|
19
|
+
from terag.core import create_terag_from_existing_chunks
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def example_1_basic_usage():
|
|
23
|
+
"""Example 1: Basic TERAG usage"""
|
|
24
|
+
print("\n" + "=" * 70)
|
|
25
|
+
print("EXAMPLE 1: Basic TERAG Usage")
|
|
26
|
+
print("=" * 70)
|
|
27
|
+
|
|
28
|
+
# Sample chunks
|
|
29
|
+
chunks = [
|
|
30
|
+
{
|
|
31
|
+
"content": "Apple Inc reported Q4 2024 revenue of $120 billion, a 15% increase year-over-year.",
|
|
32
|
+
"metadata": {"source": "earnings_report", "page": 1}
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
"content": "The iPhone division contributed $65 billion to total revenue in Q4 2024.",
|
|
36
|
+
"metadata": {"source": "earnings_report", "page": 2}
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
"content": "Apple's services segment grew 20% reaching $25 billion in quarterly revenue.",
|
|
40
|
+
"metadata": {"source": "earnings_report", "page": 3}
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
"content": "Microsoft Azure cloud revenue increased 30% in Q4 2024 to $35 billion.",
|
|
44
|
+
"metadata": {"source": "microsoft_report", "page": 1}
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
"content": "Competition intensified between Apple and Microsoft in cloud services market.",
|
|
48
|
+
"metadata": {"source": "market_analysis", "page": 1}
|
|
49
|
+
}
|
|
50
|
+
]
|
|
51
|
+
|
|
52
|
+
# Build TERAG
|
|
53
|
+
config = TERAGConfig(
|
|
54
|
+
min_concept_freq=1,
|
|
55
|
+
max_concept_freq_ratio=0.8,
|
|
56
|
+
top_k=3
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
terag = TERAG.from_chunks(chunks, config=config, verbose=True)
|
|
60
|
+
|
|
61
|
+
# Query
|
|
62
|
+
query = "What was Apple's revenue in Q4 2024?"
|
|
63
|
+
print(f"\n\nQuery: {query}")
|
|
64
|
+
print("-" * 70)
|
|
65
|
+
|
|
66
|
+
results, metrics = terag.retrieve(query, verbose=True)
|
|
67
|
+
|
|
68
|
+
print("\n\nTop Results:")
|
|
69
|
+
for i, result in enumerate(results, 1):
|
|
70
|
+
print(f"\n{i}. [Score: {result.score:.4f}] {result.passage_id}")
|
|
71
|
+
print(f" Content: {result.content}")
|
|
72
|
+
print(f" Matched concepts: {result.matched_concepts}")
|
|
73
|
+
|
|
74
|
+
print(f"\n\nRetrieval metrics:")
|
|
75
|
+
print(f" - Query entities: {metrics.num_query_entities}")
|
|
76
|
+
print(f" - Matched concepts: {metrics.num_matched_concepts}")
|
|
77
|
+
print(f" - Retrieval time: {metrics.retrieval_time:.3f}s")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def example_2_save_and_load_graph():
|
|
81
|
+
"""Example 2: Save and load pre-built graph"""
|
|
82
|
+
print("\n" + "=" * 70)
|
|
83
|
+
print("EXAMPLE 2: Save and Load Graph")
|
|
84
|
+
print("=" * 70)
|
|
85
|
+
|
|
86
|
+
chunks = [
|
|
87
|
+
{"content": "Apple reported $120B revenue in Q4 2024.", "metadata": {}},
|
|
88
|
+
{"content": "Microsoft Azure grew 30% in Q4.", "metadata": {}},
|
|
89
|
+
{"content": "Tech sector competition intensified in 2024.", "metadata": {}}
|
|
90
|
+
]
|
|
91
|
+
|
|
92
|
+
# Build and save
|
|
93
|
+
print("\n1. Building graph...")
|
|
94
|
+
config = TERAGConfig(min_concept_freq=1)
|
|
95
|
+
terag = TERAG.from_chunks(chunks, config=config, verbose=True)
|
|
96
|
+
|
|
97
|
+
graph_file = "test_terag_graph.json"
|
|
98
|
+
terag.save_graph(graph_file)
|
|
99
|
+
print(f"\n Graph saved to {graph_file}")
|
|
100
|
+
|
|
101
|
+
# Load from file
|
|
102
|
+
print(f"\n2. Loading graph from {graph_file}...")
|
|
103
|
+
terag_loaded = TERAG.from_graph_file(graph_file, config=config, verbose=True)
|
|
104
|
+
|
|
105
|
+
# Test retrieval
|
|
106
|
+
query = "What was Apple's revenue?"
|
|
107
|
+
results, metrics = terag_loaded.retrieve(query, verbose=False)
|
|
108
|
+
|
|
109
|
+
print(f"\n3. Retrieval test:")
|
|
110
|
+
print(f" Query: {query}")
|
|
111
|
+
print(f" Results: {len(results)}")
|
|
112
|
+
print(f" Time: {metrics.retrieval_time:.3f}s")
|
|
113
|
+
|
|
114
|
+
# Cleanup
|
|
115
|
+
if os.path.exists(graph_file):
|
|
116
|
+
os.remove(graph_file)
|
|
117
|
+
print(f"\n Cleaned up {graph_file}")
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def main():
|
|
121
|
+
"""Run examples"""
|
|
122
|
+
parser = argparse.ArgumentParser(description="TERAG Example Usage")
|
|
123
|
+
parser.add_argument(
|
|
124
|
+
"--example",
|
|
125
|
+
type=int,
|
|
126
|
+
choices=[1, 2],
|
|
127
|
+
help="Run specific example (1-2, default: all)"
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
args = parser.parse_args()
|
|
131
|
+
|
|
132
|
+
print("\n" + "=" * 70)
|
|
133
|
+
print("TERAG: Token-Efficient Graph-Based RAG")
|
|
134
|
+
print("Example Usage Demonstrations")
|
|
135
|
+
print("=" * 70)
|
|
136
|
+
|
|
137
|
+
if args.example == 1 or args.example is None:
|
|
138
|
+
example_1_basic_usage()
|
|
139
|
+
|
|
140
|
+
if args.example == 2 or args.example is None:
|
|
141
|
+
example_2_save_and_load_graph()
|
|
142
|
+
|
|
143
|
+
print("\n" + "=" * 70)
|
|
144
|
+
print("Examples complete!")
|
|
145
|
+
print("=" * 70)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
if __name__ == "__main__":
|
|
149
|
+
main()
|
terag/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
from .graph.builder import TERAGGraph, GraphBuilder
|
|
2
|
+
from .retrieval.hybrid import HybridRetriever
|
|
3
|
+
from .retrieval.semantic import SemanticRetriever
|
|
4
|
+
from .retrieval import PPRRetriever
|
|
5
|
+
from .ingestion.pipeline import run_ner_extraction, build_graph_from_ner, merge_graphs, deduplicate_graph
|
|
6
|
+
from terag.core import TERAG, TERAGConfig
|
|
7
|
+
|
|
8
|
+
__all__ = ["TERAG", "TERAGConfig"]
|
|
9
|
+
|
|
10
|
+
__version__ = "0.5.1"
|
terag/core.py
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TERAG Main Retriever Interface
|
|
3
|
+
|
|
4
|
+
Complete TERAG retrieval system integrating:
|
|
5
|
+
1. Graph construction from chunks
|
|
6
|
+
2. Named Entity Recognition
|
|
7
|
+
3. Personalized PageRank retrieval
|
|
8
|
+
4. Result ranking and formatting
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
from typing import List, Dict, Optional, Tuple
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
import time
|
|
15
|
+
|
|
16
|
+
from terag.graph.builder import TERAGGraph, GraphBuilder
|
|
17
|
+
from terag.ingestion.ner_extractor import NERExtractor, QueryNER, extract_concepts_from_text
|
|
18
|
+
from terag.retrieval.ppr import TERAGRetriever as PPRRetriever, RetrievalResult, RetrievalMetrics
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class TERAGConfig:
|
|
23
|
+
"""Configuration for TERAG system"""
|
|
24
|
+
# Graph construction
|
|
25
|
+
min_concept_freq: int = 2
|
|
26
|
+
max_concept_freq_ratio: float = 0.5
|
|
27
|
+
enable_concept_clustering: bool = False
|
|
28
|
+
|
|
29
|
+
# PPR parameters
|
|
30
|
+
ppr_alpha: float = 0.15
|
|
31
|
+
ppr_max_iterations: int = 100
|
|
32
|
+
|
|
33
|
+
# Weighting
|
|
34
|
+
semantic_weight: float = 0.5
|
|
35
|
+
frequency_weight: float = 0.5
|
|
36
|
+
|
|
37
|
+
# Retrieval
|
|
38
|
+
top_k: int = 10
|
|
39
|
+
|
|
40
|
+
# Optional LLM for enhanced NER
|
|
41
|
+
use_llm_for_ner: bool = False
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class TERAG:
|
|
45
|
+
"""
|
|
46
|
+
Complete TERAG system
|
|
47
|
+
|
|
48
|
+
Usage:
|
|
49
|
+
# Build from chunks
|
|
50
|
+
terag = TERAG.from_chunks(chunks, config)
|
|
51
|
+
|
|
52
|
+
# Retrieve
|
|
53
|
+
results = terag.retrieve(query, top_k=10)
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
def __init__(
|
|
57
|
+
self,
|
|
58
|
+
graph: TERAGGraph,
|
|
59
|
+
config: TERAGConfig,
|
|
60
|
+
embedding_model: Optional[object] = None
|
|
61
|
+
):
|
|
62
|
+
self.graph = graph
|
|
63
|
+
self.config = config
|
|
64
|
+
self.embedding_model = embedding_model
|
|
65
|
+
|
|
66
|
+
# Initialize components
|
|
67
|
+
self.ner_extractor = NERExtractor(use_llm=config.use_llm_for_ner)
|
|
68
|
+
self.query_ner = QueryNER()
|
|
69
|
+
self.retriever = PPRRetriever(
|
|
70
|
+
graph=graph,
|
|
71
|
+
embedding_model=embedding_model,
|
|
72
|
+
alpha=config.ppr_alpha,
|
|
73
|
+
ppr_max_iterations=config.ppr_max_iterations
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
@classmethod
|
|
77
|
+
def from_chunks(
|
|
78
|
+
cls,
|
|
79
|
+
chunks: List[Dict],
|
|
80
|
+
config: Optional[TERAGConfig] = None,
|
|
81
|
+
embedding_model: Optional[object] = None,
|
|
82
|
+
verbose: bool = True
|
|
83
|
+
) -> 'TERAG':
|
|
84
|
+
"""
|
|
85
|
+
Build TERAG system from document chunks
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
chunks: List of chunk dicts with 'content' and 'metadata'
|
|
89
|
+
config: TERAG configuration
|
|
90
|
+
embedding_model: Optional embedding model (e.g., SentenceTransformer)
|
|
91
|
+
verbose: Print progress
|
|
92
|
+
|
|
93
|
+
Returns:
|
|
94
|
+
TERAG system ready for retrieval
|
|
95
|
+
"""
|
|
96
|
+
if config is None:
|
|
97
|
+
config = TERAGConfig()
|
|
98
|
+
|
|
99
|
+
if verbose:
|
|
100
|
+
print("Building TERAG system from chunks...")
|
|
101
|
+
print(f" Chunks: {len(chunks)}")
|
|
102
|
+
print(f" Config: {config}")
|
|
103
|
+
|
|
104
|
+
start_time = time.time()
|
|
105
|
+
|
|
106
|
+
# Build graph
|
|
107
|
+
builder = GraphBuilder(
|
|
108
|
+
min_concept_freq=config.min_concept_freq,
|
|
109
|
+
max_concept_freq_ratio=config.max_concept_freq_ratio,
|
|
110
|
+
enable_concept_clustering=config.enable_concept_clustering
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
graph = builder.build_graph_from_chunks(
|
|
114
|
+
chunks=chunks,
|
|
115
|
+
extract_concepts_fn=extract_concepts_from_text
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
build_time = time.time() - start_time
|
|
119
|
+
|
|
120
|
+
if verbose:
|
|
121
|
+
print(f"\nGraph built in {build_time:.2f}s")
|
|
122
|
+
stats = graph.get_statistics()
|
|
123
|
+
print(f" Passages: {stats['num_passages']}")
|
|
124
|
+
print(f" Concepts: {stats['num_concepts']}")
|
|
125
|
+
print(f" Edges: {stats['num_edges']}")
|
|
126
|
+
|
|
127
|
+
# Create TERAG system
|
|
128
|
+
terag = cls(graph=graph, config=config, embedding_model=embedding_model)
|
|
129
|
+
|
|
130
|
+
return terag
|
|
131
|
+
|
|
132
|
+
@classmethod
|
|
133
|
+
def from_chunks_file(
|
|
134
|
+
cls,
|
|
135
|
+
chunks_file: str,
|
|
136
|
+
config: Optional[TERAGConfig] = None,
|
|
137
|
+
embedding_model: Optional[object] = None,
|
|
138
|
+
verbose: bool = True
|
|
139
|
+
) -> 'TERAG':
|
|
140
|
+
"""
|
|
141
|
+
Build TERAG system from chunks JSON file
|
|
142
|
+
|
|
143
|
+
Args:
|
|
144
|
+
chunks_file: Path to chunks JSON file
|
|
145
|
+
config: TERAG configuration
|
|
146
|
+
embedding_model: Optional embedding model
|
|
147
|
+
verbose: Print progress
|
|
148
|
+
|
|
149
|
+
Returns:
|
|
150
|
+
TERAG system
|
|
151
|
+
"""
|
|
152
|
+
if verbose:
|
|
153
|
+
print(f"Loading chunks from {chunks_file}...")
|
|
154
|
+
|
|
155
|
+
with open(chunks_file, 'r', encoding='utf-8') as f:
|
|
156
|
+
chunks = json.load(f)
|
|
157
|
+
|
|
158
|
+
return cls.from_chunks(chunks, config, embedding_model, verbose)
|
|
159
|
+
|
|
160
|
+
@classmethod
|
|
161
|
+
def from_graph_file(
|
|
162
|
+
cls,
|
|
163
|
+
graph_file: str,
|
|
164
|
+
config: Optional[TERAGConfig] = None,
|
|
165
|
+
embedding_model: Optional[object] = None,
|
|
166
|
+
verbose: bool = True
|
|
167
|
+
) -> 'TERAG':
|
|
168
|
+
"""
|
|
169
|
+
Load TERAG system from pre-built graph file
|
|
170
|
+
|
|
171
|
+
Args:
|
|
172
|
+
graph_file: Path to graph JSON file
|
|
173
|
+
config: TERAG configuration
|
|
174
|
+
embedding_model: Optional embedding model
|
|
175
|
+
verbose: Print progress
|
|
176
|
+
|
|
177
|
+
Returns:
|
|
178
|
+
TERAG system
|
|
179
|
+
"""
|
|
180
|
+
if verbose:
|
|
181
|
+
print(f"Loading graph from {graph_file}...")
|
|
182
|
+
|
|
183
|
+
graph = TERAGGraph.load_from_file(graph_file)
|
|
184
|
+
|
|
185
|
+
if config is None:
|
|
186
|
+
config = TERAGConfig()
|
|
187
|
+
|
|
188
|
+
if verbose:
|
|
189
|
+
stats = graph.get_statistics()
|
|
190
|
+
print(f" Passages: {stats['num_passages']}")
|
|
191
|
+
print(f" Concepts: {stats['num_concepts']}")
|
|
192
|
+
print(f" Edges: {stats['num_edges']}")
|
|
193
|
+
|
|
194
|
+
return cls(graph=graph, config=config, embedding_model=embedding_model)
|
|
195
|
+
|
|
196
|
+
def retrieve(
|
|
197
|
+
self,
|
|
198
|
+
query: str,
|
|
199
|
+
top_k: Optional[int] = None,
|
|
200
|
+
verbose: bool = False
|
|
201
|
+
) -> Tuple[List[RetrievalResult], RetrievalMetrics]:
|
|
202
|
+
"""
|
|
203
|
+
Retrieve relevant passages for a query
|
|
204
|
+
|
|
205
|
+
Args:
|
|
206
|
+
query: User query
|
|
207
|
+
top_k: Number of results (default: from config)
|
|
208
|
+
verbose: Print progress
|
|
209
|
+
|
|
210
|
+
Returns:
|
|
211
|
+
(results, metrics)
|
|
212
|
+
"""
|
|
213
|
+
if top_k is None:
|
|
214
|
+
top_k = self.config.top_k
|
|
215
|
+
|
|
216
|
+
# Extract query entities
|
|
217
|
+
query_entities = self.query_ner.extract_query_entities(query)
|
|
218
|
+
|
|
219
|
+
# Retrieve using PPR
|
|
220
|
+
results, metrics = self.retriever.retrieve(
|
|
221
|
+
query=query,
|
|
222
|
+
query_entities=query_entities,
|
|
223
|
+
top_k=top_k,
|
|
224
|
+
semantic_weight=self.config.semantic_weight,
|
|
225
|
+
frequency_weight=self.config.frequency_weight,
|
|
226
|
+
verbose=verbose
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
return results, metrics
|
|
230
|
+
|
|
231
|
+
def save_graph(self, filepath: str):
|
|
232
|
+
"""Save graph to file for reuse"""
|
|
233
|
+
self.graph.save_to_file(filepath)
|
|
234
|
+
print(f"Graph saved to {filepath}")
|
|
235
|
+
|
|
236
|
+
def get_graph_statistics(self) -> Dict:
|
|
237
|
+
"""Get graph statistics"""
|
|
238
|
+
return self.graph.get_statistics()
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def create_terag_from_existing_chunks(
|
|
242
|
+
chunks_file: str = "chunks_full_metadata.json",
|
|
243
|
+
output_graph_file: Optional[str] = "terag_graph.json",
|
|
244
|
+
config: Optional[TERAGConfig] = None,
|
|
245
|
+
embedding_model_name: str = "all-MiniLM-L6-v2"
|
|
246
|
+
) -> TERAG:
|
|
247
|
+
"""
|
|
248
|
+
Convenience function to create TERAG from existing chunks
|
|
249
|
+
|
|
250
|
+
Args:
|
|
251
|
+
chunks_file: Path to chunks file
|
|
252
|
+
output_graph_file: Where to save graph (None = don't save)
|
|
253
|
+
config: TERAG config
|
|
254
|
+
embedding_model_name: Name of embedding model to use
|
|
255
|
+
|
|
256
|
+
Returns:
|
|
257
|
+
TERAG system ready for use
|
|
258
|
+
"""
|
|
259
|
+
# Load embedding model if available
|
|
260
|
+
embedding_model = None
|
|
261
|
+
try:
|
|
262
|
+
from sentence_transformers import SentenceTransformer
|
|
263
|
+
print(f"Loading embedding model: {embedding_model_name}")
|
|
264
|
+
embedding_model = SentenceTransformer(embedding_model_name)
|
|
265
|
+
except ImportError:
|
|
266
|
+
print("Warning: sentence-transformers not available, semantic weighting disabled")
|
|
267
|
+
|
|
268
|
+
# Build TERAG
|
|
269
|
+
terag = TERAG.from_chunks_file(
|
|
270
|
+
chunks_file=chunks_file,
|
|
271
|
+
config=config,
|
|
272
|
+
embedding_model=embedding_model,
|
|
273
|
+
verbose=True
|
|
274
|
+
)
|
|
275
|
+
|
|
276
|
+
# Save graph if requested
|
|
277
|
+
if output_graph_file:
|
|
278
|
+
terag.save_graph(output_graph_file)
|
|
279
|
+
|
|
280
|
+
return terag
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
# Convenience functions for integration
|
|
284
|
+
def build_terag_from_chunks(chunks: List[Dict], **kwargs) -> TERAG:
|
|
285
|
+
"""Quick function to build TERAG from chunks"""
|
|
286
|
+
return TERAG.from_chunks(chunks, **kwargs)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def load_terag_from_graph(graph_file: str, **kwargs) -> TERAG:
|
|
290
|
+
"""Quick function to load TERAG from graph file"""
|
|
291
|
+
return TERAG.from_graph_file(graph_file, **kwargs)
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
if __name__ == "__main__":
|
|
295
|
+
print("TERAG Main Interface - Test")
|
|
296
|
+
print("=" * 60)
|
|
297
|
+
|
|
298
|
+
# Test with simple chunks
|
|
299
|
+
test_chunks = [
|
|
300
|
+
{
|
|
301
|
+
"content": "Apple Inc announced strong revenue growth in Q4 2024, reaching $120 billion.",
|
|
302
|
+
"metadata": {"source": "financial_report", "page": 1}
|
|
303
|
+
},
|
|
304
|
+
{
|
|
305
|
+
"content": "Microsoft Corporation reported significant achievements in cloud computing.",
|
|
306
|
+
"metadata": {"source": "financial_report", "page": 2}
|
|
307
|
+
},
|
|
308
|
+
{
|
|
309
|
+
"content": "The technology sector saw increased competition between Apple and Microsoft.",
|
|
310
|
+
"metadata": {"source": "market_analysis", "page": 1}
|
|
311
|
+
},
|
|
312
|
+
{
|
|
313
|
+
"content": "Q4 2024 was a strong quarter for major tech companies with record revenues.",
|
|
314
|
+
"metadata": {"source": "market_analysis", "page": 2}
|
|
315
|
+
}
|
|
316
|
+
]
|
|
317
|
+
|
|
318
|
+
# Build TERAG
|
|
319
|
+
config = TERAGConfig(
|
|
320
|
+
min_concept_freq=1,
|
|
321
|
+
top_k=3
|
|
322
|
+
)
|
|
323
|
+
|
|
324
|
+
terag = TERAG.from_chunks(test_chunks, config=config, verbose=True)
|
|
325
|
+
|
|
326
|
+
# Test queries
|
|
327
|
+
test_queries = [
|
|
328
|
+
"What was Apple's revenue in Q4 2024?",
|
|
329
|
+
"How did Microsoft perform?",
|
|
330
|
+
"Which companies competed in technology?"
|
|
331
|
+
]
|
|
332
|
+
|
|
333
|
+
print("\n" + "=" * 60)
|
|
334
|
+
print("Testing Retrieval")
|
|
335
|
+
print("=" * 60)
|
|
336
|
+
|
|
337
|
+
for query in test_queries:
|
|
338
|
+
print(f"\nQuery: {query}")
|
|
339
|
+
print("-" * 60)
|
|
340
|
+
|
|
341
|
+
results, metrics = terag.retrieve(query, verbose=True)
|
|
342
|
+
|
|
343
|
+
print("\nTop Results:")
|
|
344
|
+
for i, result in enumerate(results, 1):
|
|
345
|
+
print(f"\n{i}. [Score: {result.score:.4f}]")
|
|
346
|
+
print(f" {result.content}")
|
|
347
|
+
print(f" Matched concepts: {result.matched_concepts}")
|
|
348
|
+
|
|
349
|
+
print(f"\nMetrics: Retrieved {metrics.num_results} results in {metrics.retrieval_time:.3f}s")
|
|
350
|
+
print("=" * 60)
|