structurerag 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,305 @@
1
+ """
2
+ Multi-hop Reasoning Module.
3
+
4
+ Enables reasoning through the HSF hierarchy:
5
+ - Traverse from sentence to paragraph to section
6
+ - Find related concepts across the hierarchy
7
+ - Aggregate evidence from multiple levels
8
+ - Support multi-hop queries (A implies B, B implies C, therefore A implies C)
9
+ """
10
+
11
+ import re
12
+ from typing import List, Dict, Set, Tuple, Any
13
+ from dataclasses import dataclass
14
+ from collections import defaultdict, deque
15
+
16
+ from .hsf import HolisticStructuralForm, CompositeFeature, ElementaryFeature
17
+
18
+
19
+ @dataclass
20
+ class ReasoningPath:
21
+ """A path through the HSF hierarchy for reasoning."""
22
+ start_feature_id: str
23
+ end_feature_id: str
24
+ hops: List[str] # Feature IDs in the path
25
+ relationship: str # Type of relationship (e.g., "contains", "part_of", "related_to")
26
+ confidence: float = 1.0
27
+
28
+
29
+ @dataclass
30
+ class ReasoningResult:
31
+ """Result of multi-hop reasoning."""
32
+ query: str
33
+ found: bool
34
+ evidence: List[Dict[str, Any]]
35
+ paths: List[ReasoningPath]
36
+ confidence: float
37
+ explanation: str
38
+
39
+
40
+ class MultiHopReasoner:
41
+ """
42
+ Multi-hop reasoner that traverses HSF hierarchy.
43
+
44
+ Capabilities:
45
+ - Find related concepts across hierarchy levels
46
+ - Aggregate evidence from multiple sentences/paragraphs
47
+ - Support transitive reasoning
48
+ - Build knowledge graphs from HSF structure
49
+ """
50
+
51
+ def __init__(self, hsf: HolisticStructuralForm):
52
+ self.hsf = hsf
53
+ self._relationship_graph: Dict[str, Set[str]] = defaultdict(set)
54
+ self._concept_index: Dict[str, Set[str]] = defaultdict(set) # concept -> feature IDs
55
+ self._parent_of: Dict[str, str] = {}
56
+ self._built = False
57
+
58
+ def build(self):
59
+ """Build relationship graph from HSF."""
60
+ if self._built:
61
+ return
62
+
63
+ self._relationship_graph.clear()
64
+ self._concept_index.clear()
65
+ self._parent_of.clear()
66
+
67
+ # Index concepts (elementary features)
68
+ for feat_id, feature in self.hsf.elementary_features.items():
69
+ # Index by value
70
+ self._concept_index[feature.value.lower()].add(feat_id)
71
+
72
+ # Index by type
73
+ self._concept_index[f"type:{feature.feature_type}"].add(feat_id)
74
+
75
+ # Build hierarchy relationships
76
+ for parent_id, children in self.hsf.hierarchy.items():
77
+ for child_id in children:
78
+ self._relationship_graph[parent_id].add(child_id)
79
+ self._relationship_graph[child_id].add(parent_id) # Bidirectional
80
+ self._parent_of[child_id] = parent_id
81
+
82
+ # Build semantic relationships from composite features
83
+ for feat_id, feature in self.hsf.composite_features.items():
84
+ # Children are related to this feature
85
+ for child in feature.children:
86
+ self._relationship_graph[feat_id].add(child.id)
87
+ self._relationship_graph[child.id].add(feat_id)
88
+
89
+ # Siblings are related
90
+ for child_id in feature.child_ids:
91
+ siblings = [c for c in feature.child_ids if c != child_id]
92
+ for sibling_id in siblings:
93
+ self._relationship_graph[child_id].add(sibling_id)
94
+
95
+ self._built = True
96
+
97
+ def find_related(self, feature_id: str, max_hops: int = 3,
98
+ relationship_type: str = None) -> List[Tuple[str, int, float]]:
99
+ """
100
+ Find features related to a given feature.
101
+
102
+ Args:
103
+ feature_id: Starting feature ID
104
+ max_hops: Maximum hops to traverse
105
+ relationship_type: Optional filter for relationship type
106
+
107
+ Returns:
108
+ List of (feature_id, hops, confidence) tuples
109
+ """
110
+ if not self._built:
111
+ self.build()
112
+
113
+ visited = {feature_id}
114
+ queue = deque([(feature_id, 0, 1.0)]) # (feature_id, hops, confidence)
115
+ results = []
116
+
117
+ while queue:
118
+ current_id, hops, confidence = queue.popleft()
119
+
120
+ if hops >= max_hops:
121
+ continue
122
+
123
+ # Get related features
124
+ related = self._relationship_graph.get(current_id, set())
125
+
126
+ for related_id in related:
127
+ if related_id in visited:
128
+ continue
129
+
130
+ visited.add(related_id)
131
+ new_confidence = confidence * 0.8 # Decay confidence with each hop
132
+
133
+ if related_id != feature_id:
134
+ results.append((related_id, hops + 1, new_confidence))
135
+
136
+ queue.append((related_id, hops + 1, new_confidence))
137
+
138
+ return sorted(results, key=lambda x: x[2], reverse=True)
139
+
140
+ def find_concept_locations(self, concept: str) -> List[Tuple[str, str]]:
141
+ """
142
+ Find all locations where a concept appears.
143
+
144
+ Args:
145
+ concept: The concept to search for
146
+
147
+ Returns:
148
+ List of (feature_id, feature_type) tuples
149
+ """
150
+ if not self._built:
151
+ self.build()
152
+
153
+ concept_lower = concept.lower()
154
+ locations = []
155
+
156
+ # Direct match
157
+ if concept_lower in self._concept_index:
158
+ for feat_id in self._concept_index[concept_lower]:
159
+ feat = self.hsf.get_feature(feat_id)
160
+ if feat:
161
+ feat_type = getattr(feat, 'feature_type', 'unknown')
162
+ locations.append((feat_id, feat_type))
163
+
164
+ # Fuzzy match (contains)
165
+ for concept_key, feat_ids in self._concept_index.items():
166
+ if concept_lower in concept_key or concept_key in concept_lower:
167
+ for feat_id in feat_ids:
168
+ feat = self.hsf.get_feature(feat_id)
169
+ if feat:
170
+ feat_type = getattr(feat, 'feature_type', 'unknown')
171
+ if (feat_id, feat_type) not in locations:
172
+ locations.append((feat_id, feat_type))
173
+
174
+ return locations
175
+
176
+ def reason_about(self, query: str, max_hops: int = 3) -> ReasoningResult:
177
+ """
178
+ Reason about a query using multi-hop traversal.
179
+
180
+ Args:
181
+ query: The query to reason about
182
+ max_hops: Maximum hops for reasoning
183
+
184
+ Returns:
185
+ ReasoningResult with evidence and explanation
186
+ """
187
+ if not self._built:
188
+ self.build()
189
+
190
+ # Tokenize query. Regex word tokens: str.split keeps punctuation
191
+ # attached, so 'scoring.' never matched the concept index.
192
+ query_terms = re.findall(r'\b\w+\b', query.lower())
193
+
194
+ # Find concept locations
195
+ all_locations = []
196
+ for term in query_terms:
197
+ if len(term) > 2: # Skip short words
198
+ locations = self.find_concept_locations(term)
199
+ all_locations.extend(locations)
200
+
201
+ if not all_locations:
202
+ return ReasoningResult(
203
+ query=query,
204
+ found=False,
205
+ evidence=[],
206
+ paths=[],
207
+ confidence=0.0,
208
+ explanation="No concepts found in knowledge base"
209
+ )
210
+
211
+ # Gather evidence through multi-hop reasoning
212
+ evidence = []
213
+ all_paths = []
214
+
215
+ for start_id, start_type in all_locations[:5]: # Limit to top 5 concepts
216
+ related = self.find_related(start_id, max_hops=max_hops)
217
+
218
+ for related_id, hops, confidence in related[:3]: # Top 3 per concept
219
+ related_feature = self.hsf.get_feature(related_id)
220
+ if related_feature:
221
+ # Get content
222
+ if isinstance(related_feature, ElementaryFeature):
223
+ content = related_feature.value
224
+ feat_type = related_feature.feature_type
225
+ else:
226
+ content = self._get_feature_text(related_feature)
227
+ feat_type = related_feature.feature_type
228
+
229
+ evidence.append({
230
+ 'feature_id': related_id,
231
+ 'type': feat_type,
232
+ 'content': content[:200],
233
+ 'hops': hops,
234
+ 'confidence': confidence
235
+ })
236
+
237
+ # Create path
238
+ path = ReasoningPath(
239
+ start_feature_id=start_id,
240
+ end_feature_id=related_id,
241
+ hops=[start_id, related_id],
242
+ relationship="related_to",
243
+ confidence=confidence
244
+ )
245
+ all_paths.append(path)
246
+
247
+ # Aggregate confidence
248
+ avg_confidence = sum(e['confidence'] for e in evidence) / len(evidence) if evidence else 0.0
249
+
250
+ return ReasoningResult(
251
+ query=query,
252
+ found=len(evidence) > 0,
253
+ evidence=evidence,
254
+ paths=all_paths,
255
+ confidence=avg_confidence,
256
+ explanation=f"Found {len(evidence)} related concepts through {max_hops}-hop reasoning"
257
+ )
258
+
259
+ def _get_feature_text(self, feature: CompositeFeature) -> str:
260
+ """Get text content of a feature."""
261
+ if feature.feature_type == 'sentence':
262
+ return " ".join(child.value for child in sorted(
263
+ feature.children, key=lambda c: c.position
264
+ ))
265
+ else:
266
+ parts = []
267
+ for child_id in feature.child_ids:
268
+ child = self.hsf.get_feature(child_id)
269
+ if child:
270
+ if isinstance(child, CompositeFeature):
271
+ parts.append(self._get_feature_text(child))
272
+ elif isinstance(child, ElementaryFeature):
273
+ parts.append(child.value)
274
+ return " ".join(parts)
275
+
276
+ def get_hierarchy_path(self, feature_id: str) -> List[str]:
277
+ """Get the full hierarchy path for a feature. O(depth), no scanning."""
278
+ if not self._built:
279
+ self.build()
280
+
281
+ path = [feature_id]
282
+ current_id = feature_id
283
+ seen = {current_id}
284
+
285
+ while True:
286
+ parent_id = self._parent_of.get(current_id)
287
+ if parent_id is None or parent_id in seen:
288
+ break
289
+ path.insert(0, parent_id)
290
+ seen.add(parent_id)
291
+ current_id = parent_id
292
+
293
+ return path
294
+
295
+ def get_statistics(self) -> Dict[str, Any]:
296
+ """Get reasoning statistics."""
297
+ return {
298
+ 'total_concepts': len(self._concept_index),
299
+ 'total_relationships': sum(len(rels) for rels in self._relationship_graph.values()) // 2,
300
+ 'hierarchy_levels': len(set(
301
+ len(self.get_hierarchy_path(fid))
302
+ for fid in self.hsf.composite_features.keys()
303
+ )),
304
+ 'built': self._built
305
+ }
@@ -0,0 +1,20 @@
1
+ """Grounding module for verification, citation, and reranking."""
2
+
3
+ from .retriever import StructureRetriever, SearchResult, InvertedIndex
4
+ from .verifier import GroundingVerifier, Claim, VerificationResult
5
+ from .citation import CitationEngine, Citation
6
+ from .reranker import Reranker, StructureReranker, CrossEncoderReranker
7
+
8
+ __all__ = [
9
+ "StructureRetriever",
10
+ "SearchResult",
11
+ "InvertedIndex",
12
+ "GroundingVerifier",
13
+ "Claim",
14
+ "VerificationResult",
15
+ "CitationEngine",
16
+ "Citation",
17
+ "Reranker",
18
+ "StructureReranker",
19
+ "CrossEncoderReranker",
20
+ ]
@@ -0,0 +1,173 @@
1
+ """
2
+ Citation Engine: Generate precise source citations for grounded answers.
3
+
4
+ Provides human-readable citations with exact locations in source documents.
5
+ """
6
+
7
+ from typing import List, Dict, Optional, Any
8
+ from dataclasses import dataclass
9
+ from ..core.hsf import HolisticStructuralForm
10
+ from .retriever import SearchResult
11
+
12
+
13
+ @dataclass
14
+ class Citation:
15
+ """A citation pointing to a specific location in a document."""
16
+ source_id: str
17
+ source_type: str # 'sentence', 'paragraph', 'section', 'document'
18
+ content_snippet: str
19
+ location: Dict[str, Any] # Page, section, position info
20
+ relevance_score: float
21
+ document_id: Optional[str] = None
22
+
23
+ def to_markdown(self) -> str:
24
+ """Format as markdown citation."""
25
+ return f"[^{self.source_id}]: {self.content_snippet[:100]}..."
26
+
27
+ def to_dict(self) -> Dict[str, Any]:
28
+ return {
29
+ 'source_id': self.source_id,
30
+ 'source_type': self.source_type,
31
+ 'content_snippet': self.content_snippet,
32
+ 'location': self.location,
33
+ 'relevance_score': self.relevance_score,
34
+ 'document_id': self.document_id
35
+ }
36
+
37
+
38
+ class CitationEngine:
39
+ """
40
+ Generates citations for grounded answers.
41
+
42
+ Capabilities:
43
+ - Convert SearchResult to human-readable citations
44
+ - Generate inline citation markers
45
+ - Create bibliography-style reference lists
46
+ - Support multiple citation formats (APA, MLA, custom)
47
+ """
48
+
49
+ def __init__(self, hsf: Optional[HolisticStructuralForm] = None):
50
+ # Kept for callers that construct the engine from a document. The
51
+ # methods here derive everything from the results they are given, so
52
+ # this is never read.
53
+ self.hsf = hsf
54
+
55
+ def create_citation(self, result: SearchResult,
56
+ citation_style: str = "default") -> Citation:
57
+ """
58
+ Create a citation from a search result.
59
+
60
+ Args:
61
+ result: The search result to cite
62
+ citation_style: Citation format ("default", "academic", "minimal")
63
+
64
+ Returns:
65
+ Citation object
66
+ """
67
+ # Build location info
68
+ location = {
69
+ 'path': result.path,
70
+ 'feature_type': result.feature_type,
71
+ 'document_id': result.metadata.get('document_id'),
72
+ }
73
+
74
+ # Truncate content for snippet
75
+ snippet = result.content
76
+ if len(snippet) > 200:
77
+ snippet = snippet[:197] + "..."
78
+
79
+ return Citation(
80
+ source_id=result.feature_id,
81
+ source_type=result.feature_type,
82
+ content_snippet=snippet,
83
+ location=location,
84
+ relevance_score=result.score,
85
+ document_id=result.metadata.get('document_id')
86
+ )
87
+
88
+ def generate_inline_citations(self, answer: str,
89
+ citations: List[Citation]) -> str:
90
+ """
91
+ Add inline citation markers to an answer.
92
+
93
+ Example: "The capital of France is Paris[^1]. It has a population of 2M[^2]."
94
+ """
95
+ for i, citation in enumerate(citations, 1):
96
+ marker = f"[^{citation.source_id}]"
97
+ # Insert marker at appropriate position
98
+ # This is simplified - real implementation would be smarter
99
+ answer = answer + f" {marker}"
100
+
101
+ return answer
102
+
103
+ def format_citations(self, citations: List[Citation],
104
+ style: str = "default") -> str:
105
+ """
106
+ Format a list of citations for display.
107
+
108
+ Args:
109
+ citations: List of citations to format
110
+ style: Output style ("markdown", "html", "text")
111
+
112
+ Returns:
113
+ Formatted citation list
114
+ """
115
+ if style == "markdown":
116
+ lines = ["## References\n"]
117
+ for i, citation in enumerate(citations, 1):
118
+ lines.append(f"^[{i}]: **{citation.source_type}** - {citation.content_snippet}\n")
119
+ lines.append(f" Source ID: {citation.source_id}\n")
120
+ lines.append(f" Relevance: {citation.relevance_score:.2f}\n\n")
121
+ return "\n".join(lines)
122
+
123
+ elif style == "html":
124
+ lines = ["<h3>References</h3>", "<ol>"]
125
+ for citation in citations:
126
+ lines.append(f"<li><strong>{citation.source_type}</strong>: {citation.content_snippet}")
127
+ lines.append(f"<br><small>Source: {citation.source_id} (relevance: {citation.relevance_score:.2f})</small></li>")
128
+ lines.append("</ol>")
129
+ return "\n".join(lines)
130
+
131
+ else: # default/text
132
+ lines = ["References:"]
133
+ for i, citation in enumerate(citations, 1):
134
+ lines.append(f" [{i}] {citation.source_type}: {citation.content_snippet[:100]}...")
135
+ lines.append(f" Source: {citation.source_id} (score: {citation.relevance_score:.2f})")
136
+ return "\n".join(lines)
137
+
138
+ def generate_full_citation_report(self,
139
+ query: str,
140
+ search_results: List[SearchResult]) -> str:
141
+ """
142
+ Generate a comprehensive citation report.
143
+
144
+ Includes:
145
+ - Query summary
146
+ - Top matching sources
147
+ - Relevance analysis
148
+ - Source hierarchy
149
+ """
150
+ citations = [self.create_citation(r) for r in search_results]
151
+
152
+ report = f"""
153
+ # Citation Report
154
+
155
+ **Query:** {query}
156
+
157
+ **Total Sources Found:** {len(citations)}
158
+
159
+ ## Top Sources
160
+
161
+ """
162
+ for i, citation in enumerate(citations[:5], 1):
163
+ report += f"""
164
+ ### Source {i}
165
+ - **Type:** {citation.source_type}
166
+ - **ID:** {citation.source_id}
167
+ - **Relevance Score:** {citation.relevance_score:.2f}
168
+ - **Snippet:** {citation.content_snippet}
169
+ - **Path:** {' → '.join(citation.location.get('path', []))}
170
+
171
+ """
172
+
173
+ return report
@@ -0,0 +1,160 @@
1
+ """
2
+ Reranking module for post-retrieval precision improvement.
3
+
4
+ Two built-in strategies:
5
+ - StructureReranker: rule-based, zero dependencies
6
+ - CrossEncoderReranker: uses sentence-transformers cross-encoder
7
+ """
8
+
9
+ import math
10
+ import re
11
+ from typing import Any, Dict, List, Protocol, runtime_checkable
12
+
13
+ from .retriever import SearchResult
14
+
15
+
16
+ @runtime_checkable
17
+ class Reranker(Protocol):
18
+ """Protocol for reranker implementations."""
19
+
20
+ def rerank(self, query: str, results: List[SearchResult],
21
+ top_k: int = 5) -> List[SearchResult]: ...
22
+
23
+
24
+ class StructureReranker:
25
+ """
26
+ Rule-based reranker using:
27
+ - Exact phrase overlap (highest weight)
28
+ - Ordered term proximity
29
+ - Unique query term coverage
30
+ - Original retrieval score carry-over
31
+ """
32
+
33
+ def rerank(self, query: str, results: List[SearchResult],
34
+ top_k: int = 5) -> List[SearchResult]:
35
+ if not results:
36
+ return []
37
+
38
+ query_lower = query.lower()
39
+ query_terms = re.findall(r'\b\w+\b', query_lower)
40
+ if not query_terms:
41
+ return results[:top_k]
42
+
43
+ scored: List[tuple[SearchResult, float]] = []
44
+ for result in results:
45
+ content_lower = result.content.lower()
46
+ content_terms = re.findall(r'\b\w+\b', content_lower)
47
+
48
+ # 1. Exact phrase match (0.0-0.4)
49
+ phrase_score = 0.0
50
+ if query_lower in content_lower:
51
+ phrase_score = 0.4
52
+ else:
53
+ # Check for longest contiguous sub-sequence of query terms
54
+ for length in range(len(query_terms), 1, -1):
55
+ for start in range(len(query_terms) - length + 1):
56
+ sub = " ".join(query_terms[start:start + length])
57
+ if sub in content_lower:
58
+ phrase_score = 0.4 * (length / len(query_terms))
59
+ break
60
+ if phrase_score > 0:
61
+ break
62
+
63
+ # 2. Term coverage (0.0-0.3)
64
+ content_term_set = set(content_terms)
65
+ matched = sum(1 for t in query_terms if t in content_term_set)
66
+ coverage_score = 0.3 * (matched / len(query_terms))
67
+
68
+ # 3. Term proximity (0.0-0.2)
69
+ # How close are query terms to each other in the content?
70
+ positions = []
71
+ for qt in query_terms:
72
+ for i, ct in enumerate(content_terms):
73
+ if ct == qt:
74
+ positions.append(i)
75
+ break
76
+ if len(positions) >= 2:
77
+ span = max(positions) - min(positions)
78
+ proximity_score = 0.2 * max(0, 1 - span / max(1, len(content_terms)))
79
+ else:
80
+ proximity_score = 0.0
81
+
82
+ # 4. Original retrieval score (0.0-0.1)
83
+ original_score = 0.1 * min(1.0, result.score)
84
+
85
+ rerank_score = phrase_score + coverage_score + proximity_score + original_score
86
+ scored.append((result, rerank_score))
87
+
88
+ scored.sort(key=lambda x: x[1], reverse=True)
89
+ return [
90
+ SearchResult(
91
+ feature_id=r.feature_id, feature_type=r.feature_type,
92
+ content=r.content, score=s,
93
+ path=r.path,
94
+ # Keep the retrieval score around: the verifier reads it so
95
+ # its thresholds stay on the BM25 scale.
96
+ metadata={**r.metadata, 'bm25_score': r.score}
97
+ )
98
+ for r, s in scored[:top_k]
99
+ ]
100
+
101
+
102
+ class CrossEncoderReranker:
103
+ """
104
+ Cross-encoder reranker using sentence-transformers.
105
+ Requires: pip install sentence-transformers
106
+ """
107
+
108
+ # Class-level model cache
109
+ _shared_models: Dict[str, Any] = {}
110
+
111
+ def __init__(self, model_name: str = "cross-encoder/ms-marco-MiniLM-L-6-v2"):
112
+ self.model_name = model_name
113
+ self._model: Any = None
114
+
115
+ @staticmethod
116
+ def is_available() -> bool:
117
+ from importlib.util import find_spec
118
+ return find_spec("sentence_transformers") is not None
119
+
120
+ def _load_model(self):
121
+ if self._model is None:
122
+ if self.model_name in CrossEncoderReranker._shared_models:
123
+ self._model = CrossEncoderReranker._shared_models[self.model_name]
124
+ else:
125
+ from sentence_transformers import CrossEncoder
126
+ self._model = CrossEncoder(self.model_name)
127
+ CrossEncoderReranker._shared_models[self.model_name] = self._model
128
+
129
+ def rerank(self, query: str, results: List[SearchResult],
130
+ top_k: int = 5) -> List[SearchResult]:
131
+ """
132
+ Score (query, passage) pairs and reorder.
133
+
134
+ A cross-encoder emits raw logits, which are unbounded and can be
135
+ negative. Callers compare ``SearchResult.score`` against absolute
136
+ relevance thresholds, so the logits are squashed to 0..1. Ranking is
137
+ unaffected because the sigmoid is monotonic.
138
+ """
139
+ if not results:
140
+ return []
141
+ self._load_model()
142
+ pairs = [(query, r.content) for r in results]
143
+ scores = self._model.predict(pairs)
144
+
145
+ scored = sorted(
146
+ zip(results, scores),
147
+ key=lambda x: float(x[1]),
148
+ reverse=True,
149
+ )
150
+ return [
151
+ SearchResult(
152
+ feature_id=r.feature_id, feature_type=r.feature_type,
153
+ content=r.content, score=1.0 / (1.0 + math.exp(-float(s))),
154
+ path=r.path,
155
+ # Keep the retrieval score around: the verifier reads it so
156
+ # its thresholds stay on the BM25 scale.
157
+ metadata={**r.metadata, 'bm25_score': r.score}
158
+ )
159
+ for r, s in scored[:top_k]
160
+ ]