Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
Add progress tracking to conflicts and context modules
KaifAhmad10f1c0ad5d033
diff --git a/semantica/conflicts/conflict_analyzer.py b/semantica/conflicts/conflict_analyzer.pyindex 68b4df23..97c63441 100644--- a/semantica/conflicts/conflict_analyzer.py+++ b/semantica/conflicts/conflict_analyzer.py@@ -72,6 +72,7 @@ class ConflictAnalyzer:self.logger = get_logger("conflict_analyzer")self.config = config or {}self.config.update(kwargs)+ self.progress_tracker = get_progress_tracker()def analyze_conflicts(self,@@ -86,18 +87,34 @@ class ConflictAnalyzer:Returns:Analysis results dictionary"""- analysis = {- "total_conflicts": len(conflicts),- "by_type": self._analyze_by_type(conflicts),- "by_severity": self._analyze_by_severity(conflicts),- "by_entity": self._analyze_by_entity(conflicts),- "by_property": self._analyze_by_property(conflicts),- "patterns": self._identify_patterns(conflicts),- "recommendations": self._generate_recommendations(conflicts),- "statistics": self._calculate_statistics(conflicts)- }-- return analysis+ # Track conflict analysis+ tracking_id = self.progress_tracker.start_tracking(+ file=None,+ module="conflicts",+ submodule="ConflictAnalyzer",+ message=f"Analyzing {len(conflicts)} conflicts"+ )++ try:+ self.progress_tracker.update_tracking(tracking_id, message="Analyzing conflict patterns...")+ analysis = {+ "total_conflicts": len(conflicts),+ "by_type": self._analyze_by_type(conflicts),+ "by_severity": self._analyze_by_severity(conflicts),+ "by_entity": self._analyze_by_entity(conflicts),+ "by_property": self._analyze_by_property(conflicts),+ "patterns": self._identify_patterns(conflicts),+ "recommendations": self._generate_recommendations(conflicts),+ "statistics": self._calculate_statistics(conflicts)+ }++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Analyzed {len(conflicts)} conflicts")+ return analysis++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef _analyze_by_type(self, conflicts: List[Conflict]) -> Dict[str, Any]:"""Analyze conflicts by type."""diff --git a/semantica/conflicts/conflict_detector.py b/semantica/conflicts/conflict_detector.pyindex 15ff33c8..9df25946 100644--- a/semantica/conflicts/conflict_detector.py+++ b/semantica/conflicts/conflict_detector.py@@ -37,6 +37,7 @@ from enum import Enumfrom .source_tracker import SourceTracker, SourceReferencefrom ..utils.exceptions import ValidationError, ProcessingErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_trackerclass ConflictType(str, Enum):@@ -97,6 +98,9 @@ class ConflictDetector:self.confidence_threshold = self.config.get("confidence_threshold", 0.7)self.auto_resolve = self.config.get("auto_resolve", False)+ # Initialize progress tracker+ self.progress_tracker = get_progress_tracker()+self.detected_conflicts: Dict[str, Conflict] = {}def detect_value_conflicts(@@ -116,81 +120,98 @@ class ConflictDetector:Returns:List of detected conflicts"""- conflicts = []+ # Track conflict detection+ tracking_id = self.progress_tracker.start_tracking(+ file=None,+ module="conflicts",+ submodule="ConflictDetector",+ message=f"Detecting value conflicts for property: {property_name}"+ )- # Group entities by ID (same entity from different sources)- entity_groups: Dict[str, List[Dict[str, Any]]] = {}-- for entity in entities:- entity_id = entity.get("id") or entity.get("entity_id")- if not entity_id:- continue+ try:+ conflicts = []- if entity_type and entity.get("type") != entity_type:- continue+ # Group entities by ID (same entity from different sources)+ entity_groups: Dict[str, List[Dict[str, Any]]] = {}- if entity_id not in entity_groups:- entity_groups[entity_id] = []- entity_groups[entity_id].append(entity)-- # Check each entity group for conflicts- for entity_id, entity_list in entity_groups.items():- if len(entity_list) < 2:- continue # Need at least 2 sources to have conflict+ self.progress_tracker.update_tracking(tracking_id, message=f"Analyzing {len(entities)} entities...")- values = []- sources = []+ for entity in entities:+ entity_id = entity.get("id") or entity.get("entity_id")+ if not entity_id:+ continue++ if entity_type and entity.get("type") != entity_type:+ continue++ if entity_id not in entity_groups:+ entity_groups[entity_id] = []+ entity_groups[entity_id].append(entity)- for entity in entity_list:- if property_name in entity:- value = entity[property_name]- values.append(value)+ # Check each entity group for conflicts+ for entity_id, entity_list in entity_groups.items():+ if len(entity_list) < 2:+ continue # Need at least 2 sources to have conflict++ values = []+ sources = []++ for entity in entity_list:+ if property_name in entity:+ value = entity[property_name]+ values.append(value)++ # Track source if available+ if self.track_provenance:+ source_ref = SourceReference(+ document=entity.get("source", "unknown"),+ page=entity.get("page"),+ section=entity.get("section"),+ confidence=entity.get("confidence", 1.0),+ metadata=entity.get("metadata", {})+ )+ self.source_tracker.track_property_source(+ entity_id,+ property_name,+ value,+ source_ref+ )+ sources.append({+ "document": source_ref.document,+ "page": source_ref.page,+ "confidence": source_ref.confidence+ })++ # Check for value conflicts+ unique_values = list(set(str(v) for v in values if v is not None))++ if len(unique_values) > 1:+ conflict = Conflict(+ conflict_id=f"{entity_id}_{property_name}_conflict",+ conflict_type=ConflictType.VALUE_CONFLICT,+ entity_id=entity_id,+ property_name=property_name,+ conflicting_values=values,+ sources=sources,+ confidence=self._calculate_conflict_confidence(values, sources),+ severity=self._calculate_severity(property_name, values),+ recommended_action=self._recommend_action(property_name, values)+ )+ conflicts.append(conflict)+ self.detected_conflicts[conflict.conflict_id] = conflict- # Track source if available- if self.track_provenance:- source_ref = SourceReference(- document=entity.get("source", "unknown"),- page=entity.get("page"),- section=entity.get("section"),- confidence=entity.get("confidence", 1.0),- metadata=entity.get("metadata", {})- )- self.source_tracker.track_property_source(- entity_id,- property_name,- value,- source_ref- )- sources.append({- "document": source_ref.document,- "page": source_ref.page,- "confidence": source_ref.confidence- })+ self.logger.warning(+ f"Value conflict detected: {entity_id}.{property_name} "+ f"has conflicting values: {unique_values}"+ )- # Check for value conflicts- unique_values = list(set(str(v) for v in values if v is not None))+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Detected {len(conflicts)} conflicts")+ return conflicts- if len(unique_values) > 1:- conflict = Conflict(- conflict_id=f"{entity_id}_{property_name}_conflict",- conflict_type=ConflictType.VALUE_CONFLICT,- entity_id=entity_id,- property_name=property_name,- conflicting_values=values,- sources=sources,- confidence=self._calculate_conflict_confidence(values, sources),- severity=self._calculate_severity(property_name, values),- recommended_action=self._recommend_action(property_name, values)- )- conflicts.append(conflict)- self.detected_conflicts[conflict.conflict_id] = conflict-- self.logger.warning(- f"Value conflict detected: {entity_id}.{property_name} "- f"has conflicting values: {unique_values}"- )-- return conflicts+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef detect_property_conflicts(self,diff --git a/semantica/conflicts/conflict_resolver.py b/semantica/conflicts/conflict_resolver.pyindex 3c5ed674..c9f0ee34 100644--- a/semantica/conflicts/conflict_resolver.py+++ b/semantica/conflicts/conflict_resolver.py@@ -38,6 +38,7 @@ from .conflict_detector import Conflict, ConflictTypefrom .source_tracker import SourceTrackerfrom ..utils.exceptions import ValidationError, ProcessingErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_trackerclass ResolutionStrategy(str, Enum):@@ -99,6 +100,9 @@ class ConflictResolver:"resolution_rules", {})+ # Initialize progress tracker+ self.progress_tracker = get_progress_tracker()+self.resolution_history: List[ResolutionResult] = []def resolve_conflict(@@ -116,42 +120,57 @@ class ConflictResolver:Returns:Resolution result"""- if not strategy:- # Check for property-specific rule- if conflict.property_name:- rule_key = f"{conflict.entity_id}.{conflict.property_name}"- if rule_key in self.resolution_rules:- strategy = self.resolution_rules[rule_key]+ # Track conflict resolution+ tracking_id = self.progress_tracker.start_tracking(+ file=None,+ module="conflicts",+ submodule="ConflictResolver",+ message=f"Resolving conflict: {conflict.conflict_id}"+ )++ try:+ if not strategy:+ # Check for property-specific rule+ if conflict.property_name:+ rule_key = f"{conflict.entity_id}.{conflict.property_name}"+ if rule_key in self.resolution_rules:+ strategy = self.resolution_rules[rule_key]+ else:+ strategy = self.default_strategyelse:strategy = self.default_strategy++ self.logger.info(+ f"Resolving conflict {conflict.conflict_id} using strategy: {strategy.value}"+ )++ if strategy == ResolutionStrategy.VOTING:+ result = self._resolve_by_voting(conflict)+ elif strategy == ResolutionStrategy.CREDIBILITY_WEIGHTED:+ result = self._resolve_by_credibility(conflict)+ elif strategy == ResolutionStrategy.MOST_RECENT:+ result = self._resolve_by_recency(conflict)+ elif strategy == ResolutionStrategy.FIRST_SEEN:+ result = self._resolve_by_first_seen(conflict)+ elif strategy == ResolutionStrategy.HIGHEST_CONFIDENCE:+ result = self._resolve_by_confidence(conflict)+ elif strategy == ResolutionStrategy.MANUAL_REVIEW:+ result = self._flag_for_manual_review(conflict)+ elif strategy == ResolutionStrategy.EXPERT_REVIEW:+ result = self._flag_for_expert_review(conflict)else:- strategy = self.default_strategy-- self.logger.info(- f"Resolving conflict {conflict.conflict_id} using strategy: {strategy.value}"- )-- if strategy == ResolutionStrategy.VOTING:- result = self._resolve_by_voting(conflict)- elif strategy == ResolutionStrategy.CREDIBILITY_WEIGHTED:- result = self._resolve_by_credibility(conflict)- elif strategy == ResolutionStrategy.MOST_RECENT:- result = self._resolve_by_recency(conflict)- elif strategy == ResolutionStrategy.FIRST_SEEN:- result = self._resolve_by_first_seen(conflict)- elif strategy == ResolutionStrategy.HIGHEST_CONFIDENCE:- result = self._resolve_by_confidence(conflict)- elif strategy == ResolutionStrategy.MANUAL_REVIEW:- result = self._flag_for_manual_review(conflict)- elif strategy == ResolutionStrategy.EXPERT_REVIEW:- result = self._flag_for_expert_review(conflict)- else:- result = self._resolve_by_voting(conflict)-- result.resolution_strategy = strategy.value- self.resolution_history.append(result)-- return result+ result = self._resolve_by_voting(conflict)++ result.resolution_strategy = strategy.value+ self.resolution_history.append(result)++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Resolved conflict using {strategy.value}")+ return result++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef resolve_conflicts(self,diff --git a/semantica/conflicts/investigation_guide.py b/semantica/conflicts/investigation_guide.pyindex 64d1c17b..0fc5a8a2 100644--- a/semantica/conflicts/investigation_guide.py+++ b/semantica/conflicts/investigation_guide.py@@ -37,6 +37,7 @@ from datetime import datetimefrom .conflict_detector import Conflict, ConflictTypefrom .source_tracker import SourceTrackerfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_tracker@dataclass@@ -90,6 +91,7 @@ class InvestigationGuideGenerator:self.source_tracker = self.config.get("source_tracker") or SourceTracker()self.include_traceability = self.config.get("include_traceability", True)+ self.progress_tracker = get_progress_tracker()def generate_guide(self,@@ -106,17 +108,32 @@ class InvestigationGuideGenerator:Returns:Investigation guide"""- guide = InvestigationGuide(- conflict_id=conflict.conflict_id,- conflict_summary=self._generate_summary(conflict),- severity=conflict.severity,- conflicting_sources=conflict.sources,- investigation_steps=self._generate_investigation_steps(conflict),- recommended_actions=self._generate_recommended_actions(conflict),- context=additional_context or {}+ # Track investigation guide generation+ tracking_id = self.progress_tracker.start_tracking(+ file=None,+ module="conflicts",+ submodule="InvestigationGuideGenerator",+ message=f"Generating guide for conflict: {conflict.conflict_id}")- return guide+ try:+ guide = InvestigationGuide(+ conflict_id=conflict.conflict_id,+ conflict_summary=self._generate_summary(conflict),+ severity=conflict.severity,+ conflicting_sources=conflict.sources,+ investigation_steps=self._generate_investigation_steps(conflict),+ recommended_actions=self._generate_recommended_actions(conflict),+ context=additional_context or {}+ )++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message="Investigation guide generated")+ return guide++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef generate_guides(self,diff --git a/semantica/conflicts/source_tracker.py b/semantica/conflicts/source_tracker.pyindex f853a9c0..fd607d57 100644--- a/semantica/conflicts/source_tracker.py+++ b/semantica/conflicts/source_tracker.py@@ -38,6 +38,7 @@ from collections import defaultdictfrom ..utils.exceptions import ValidationErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_tracker@dataclass@@ -86,6 +87,9 @@ class SourceTracker:self.config = config or {}self.config.update(kwargs)+ # Initialize progress tracker+ self.progress_tracker = get_progress_tracker()+# Entity -> Property -> PropertySourceself.entity_sources: Dict[str, Dict[str, PropertySource]] = defaultdict(dict)diff --git a/semantica/context/agent_memory.py b/semantica/context/agent_memory.pyindex 563b690b..9337f7f9 100644--- a/semantica/context/agent_memory.py+++ b/semantica/context/agent_memory.py@@ -91,6 +91,9 @@ class AgentMemory:self.memory_items: Dict[str, MemoryItem] = {}self.memory_index: deque = deque(maxlen=self.max_memory_size)+ # Initialize progress tracker+ self.progress_tracker = get_progress_tracker()+# Statisticsself.stats = {"total_items": 0,@@ -121,58 +124,75 @@ class AgentMemory:Returns:Memory ID"""- memory_id = options.get("memory_id") or self._generate_memory_id()- timestamp = options.get("timestamp") or datetime.now()-- # Create memory item- memory_item = MemoryItem(- content=content,- timestamp=timestamp,- metadata=metadata or {},- entities=entities or [],- relationships=relationships or [],- memory_id=memory_id+ # Track memory storage+ tracking_id = self.progress_tracker.start_tracking(+ file=None,+ module="context",+ submodule="AgentMemory",+ message=f"Storing memory: {content[:50]}...")- # Generate embedding if vector store available- if self.vector_store:- try:- embedding = self._generate_embedding(content)- memory_item.embedding = embedding-- # Store in vector store- if hasattr(self.vector_store, "add"):- self.vector_store.add(- id=memory_id,- vector=embedding,- metadata={- "content": content,- "timestamp": timestamp.isoformat(),- **metadata or {}- }- )- except Exception as e:- self.logger.warning(f"Failed to generate embedding: {e}")-- # Store in memory- self.memory_items[memory_id] = memory_item- self.memory_index.append(memory_id)-- # Update knowledge graph if available- if self.knowledge_graph and entities:- self._update_knowledge_graph(entities, relationships)-- # Update statistics- self.stats["total_items"] += 1- item_type = metadata.get("type", "general") if metadata else "general"- self.stats["items_by_type"][item_type] = self.stats["items_by_type"].get(item_type, 0) + 1-- self.logger.debug(f"Stored memory item: {memory_id}")-- # Apply retention policy- self._apply_retention_policy()-- return memory_id+ try:+ memory_id = options.get("memory_id") or self._generate_memory_id()+ timestamp = options.get("timestamp") or datetime.now()++ # Create memory item+ memory_item = MemoryItem(+ content=content,+ timestamp=timestamp,+ metadata=metadata or {},+ entities=entities or [],+ relationships=relationships or [],+ memory_id=memory_id+ )++ # Generate embedding if vector store available+ if self.vector_store:+ try:+ self.progress_tracker.update_tracking(tracking_id, message="Generating embedding...")+ embedding = self._generate_embedding(content)+ memory_item.embedding = embedding++ # Store in vector store+ if hasattr(self.vector_store, "add"):+ self.vector_store.add(+ id=memory_id,+ vector=embedding,+ metadata={+ "content": content,+ "timestamp": timestamp.isoformat(),+ **metadata or {}+ }+ )+ except Exception as e:+ self.logger.warning(f"Failed to generate embedding: {e}")++ # Store in memory+ self.memory_items[memory_id] = memory_item+ self.memory_index.append(memory_id)++ # Update knowledge graph if available+ if self.knowledge_graph and entities:+ self.progress_tracker.update_tracking(tracking_id, message="Updating knowledge graph...")+ self._update_knowledge_graph(entities, relationships)++ # Update statistics+ self.stats["total_items"] += 1+ item_type = metadata.get("type", "general") if metadata else "general"+ self.stats["items_by_type"][item_type] = self.stats["items_by_type"].get(item_type, 0) + 1++ self.logger.debug(f"Stored memory item: {memory_id}")++ # Apply retention policy+ self._apply_retention_policy()++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Stored memory: {memory_id}")+ return memory_id++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef retrieve(self,@@ -196,49 +216,67 @@ class AgentMemory:Returns:List of retrieved memory items"""- results = []-- # Vector-based retrieval- if self.vector_store:- try:- if hasattr(self.vector_store, "search"):- vector_results = self.vector_store.search(- query=query,- top_k=max_results * 2- )-- for result in vector_results:- memory_id = result.get("id")- if memory_id in self.memory_items:- memory_item = self.memory_items[memory_id]-- # Apply filters- if not self._matches_filters(memory_item, filters):- continue-- results.append({- "memory_id": memory_id,- "content": memory_item.content,- "score": result.get("score", 0.0),- "timestamp": memory_item.timestamp.isoformat(),- "metadata": memory_item.metadata,- "entities": memory_item.entities,- "relationships": memory_item.relationships- })- except Exception as e:- self.logger.warning(f"Vector retrieval failed: {e}")-- # Fallback to keyword search if no vector store- if not results:- results = self._keyword_search(query, max_results, filters)-- # Sort by score and return top results- results.sort(key=lambda x: x.get("score", 0.0), reverse=True)- filtered_results = [r for r in results if r.get("score", 0.0) >= min_score]-- self.stats["last_accessed"] = datetime.now().isoformat()+ # Track memory retrieval+ tracking_id = self.progress_tracker.start_tracking(+ file=None,+ module="context",+ submodule="AgentMemory",+ message=f"Retrieving memories for: {query[:50]}..."+ )- return filtered_results[:max_results]+ try:+ results = []++ # Vector-based retrieval+ if self.vector_store:+ self.progress_tracker.update_tracking(tracking_id, message="Searching vector store...")+ try:+ if hasattr(self.vector_store, "search"):+ vector_results = self.vector_store.search(+ query=query,+ top_k=max_results * 2+ )++ for result in vector_results:+ memory_id = result.get("id")+ if memory_id in self.memory_items:+ memory_item = self.memory_items[memory_id]++ # Apply filters+ if not self._matches_filters(memory_item, filters):+ continue++ results.append({+ "memory_id": memory_id,+ "content": memory_item.content,+ "score": result.get("score", 0.0),+ "timestamp": memory_item.timestamp.isoformat(),+ "metadata": memory_item.metadata,+ "entities": memory_item.entities,+ "relationships": memory_item.relationships+ })+ except Exception as e:+ self.logger.warning(f"Vector retrieval failed: {e}")++ # Fallback to keyword search if no vector store+ if not results:+ self.progress_tracker.update_tracking(tracking_id, message="Performing keyword search...")+ results = self._keyword_search(query, max_results, filters)++ # Sort by score and return top results+ self.progress_tracker.update_tracking(tracking_id, message="Ranking results...")+ results.sort(key=lambda x: x.get("score", 0.0), reverse=True)+ filtered_results = [r for r in results if r.get("score", 0.0) >= min_score]++ self.stats["last_accessed"] = datetime.now().isoformat()++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Retrieved {len(filtered_results[:max_results])} memories")+ return filtered_results[:max_results]++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef get_memory(self, memory_id: str) -> Optional[Dict[str, Any]]:"""diff --git a/semantica/context/context_graph.py b/semantica/context/context_graph.pyindex ca58b906..f669a13a 100644--- a/semantica/context/context_graph.py+++ b/semantica/context/context_graph.py@@ -101,6 +101,9 @@ class ContextGraphBuilder:self.nodes: Dict[str, ContextNode] = {}self.edges: List[ContextEdge] = []+ # Initialize progress tracker+ self.progress_tracker = get_progress_tracker()+# Indexesself.node_type_index: Dict[str, Set[str]] = defaultdict(set)self.edge_type_index: Dict[str, List[ContextEdge]] = defaultdict(list)@@ -126,34 +129,52 @@ class ContextGraphBuilder:Returns:Context graph dictionary"""- self.logger.info(f"Building context graph from {len(conversations)} conversations")-- # Process each conversation- for conv in conversations:- if isinstance(conv, str):- # Load conversation from file- conv_data = self._load_conversation(conv)- else:- conv_data = conv-- self._process_conversation(- conv_data,- extract_intents=extract_intents,- extract_sentiments=extract_sentiments- )-- # Link entities if requested- if link_entities:- self._link_entities()-- # Build graph structure- graph = self._build_graph_structure()-- self.logger.info(- f"Built context graph: {len(self.nodes)} nodes, {len(self.edges)} edges"+ # Track context graph building+ tracking_id = self.progress_tracker.start_tracking(+ file=None,+ module="context",+ submodule="ContextGraphBuilder",+ message=f"Building graph from {len(conversations)} conversations")- return graph+ try:+ self.logger.info(f"Building context graph from {len(conversations)} conversations")++ self.progress_tracker.update_tracking(tracking_id, message="Processing conversations...")+ # Process each conversation+ for conv in conversations:+ if isinstance(conv, str):+ # Load conversation from file+ conv_data = self._load_conversation(conv)+ else:+ conv_data = conv++ self._process_conversation(+ conv_data,+ extract_intents=extract_intents,+ extract_sentiments=extract_sentiments+ )++ # Link entities if requested+ if link_entities:+ self.progress_tracker.update_tracking(tracking_id, message="Linking entities...")+ self._link_entities()++ # Build graph structure+ self.progress_tracker.update_tracking(tracking_id, message="Building graph structure...")+ graph = self._build_graph_structure()++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Built graph with {len(self.nodes)} nodes, {len(self.edges)} edges")+ self.logger.info(+ f"Built context graph: {len(self.nodes)} nodes, {len(self.edges)} edges"+ )++ return graph++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef build_from_entities_and_relationships(self,@@ -172,70 +193,91 @@ class ContextGraphBuilder:Returns:Context graph dictionary"""- # Add entities as nodes- for entity in entities:- entity_id = entity.get("id") or entity.get("entity_id")- if not entity_id:- continue-- node = ContextNode(- node_id=entity_id,- node_type="entity",- content=entity.get("text") or entity.get("label") or entity.get("name", ""),- metadata={- "type": entity.get("type") or entity.get("entity_type"),- "confidence": entity.get("confidence", 1.0),- **entity.get("metadata", {})- },- properties=entity.get("properties", {})- )-- self.nodes[entity_id] = node- self.node_type_index["entity"].add(entity_id)-- # Assign URI if entity linker available- if self.entity_linker:- self.entity_linker.assign_uri(- entity_id,- node.content,- node.metadata.get("type")- )+ # Track context graph building+ tracking_id = self.progress_tracker.start_tracking(+ file=None,+ module="context",+ submodule="ContextGraphBuilder",+ message=f"Building graph from {len(entities)} entities, {len(relationships)} relationships"+ )- # Add relationships as edges- for rel in relationships:- source_id = rel.get("source_id")- target_id = rel.get("target_id")-- if not source_id or not target_id:- continue-- # Ensure source and target nodes exist- if source_id not in self.nodes:- self.nodes[source_id] = ContextNode(- node_id=source_id,+ try:+ self.progress_tracker.update_tracking(tracking_id, message="Adding entities as nodes...")+ # Add entities as nodes+ for entity in entities:+ entity_id = entity.get("id") or entity.get("entity_id")+ if not entity_id:+ continue++ node = ContextNode(+ node_id=entity_id,node_type="entity",- content=source_id+ content=entity.get("text") or entity.get("label") or entity.get("name", ""),+ metadata={+ "type": entity.get("type") or entity.get("entity_type"),+ "confidence": entity.get("confidence", 1.0),+ **entity.get("metadata", {})+ },+ properties=entity.get("properties", {}))++ self.nodes[entity_id] = node+ self.node_type_index["entity"].add(entity_id)++ # Assign URI if entity linker available+ if self.entity_linker:+ self.entity_linker.assign_uri(+ entity_id,+ node.content,+ node.metadata.get("type")+ )- if target_id not in self.nodes:- self.nodes[target_id] = ContextNode(- node_id=target_id,- node_type="entity",- content=target_id+ # Add relationships as edges+ self.progress_tracker.update_tracking(tracking_id, message="Adding relationships as edges...")+ for rel in relationships:+ source_id = rel.get("source_id")+ target_id = rel.get("target_id")++ if not source_id or not target_id:+ continue++ # Ensure source and target nodes exist+ if source_id not in self.nodes:+ self.nodes[source_id] = ContextNode(+ node_id=source_id,+ node_type="entity",+ content=source_id+ )++ if target_id not in self.nodes:+ self.nodes[target_id] = ContextNode(+ node_id=target_id,+ node_type="entity",+ content=target_id+ )++ edge = ContextEdge(+ source_id=source_id,+ target_id=target_id,+ edge_type=rel.get("type") or rel.get("relationship_type", "related_to"),+ weight=rel.get("confidence", 1.0),+ metadata=rel.get("metadata", {}))++ self.edges.append(edge)+ self.edge_type_index[edge.edge_type].append(edge)- edge = ContextEdge(- source_id=source_id,- target_id=target_id,- edge_type=rel.get("type") or rel.get("relationship_type", "related_to"),- weight=rel.get("confidence", 1.0),- metadata=rel.get("metadata", {})- )+ # Build graph structure+ self.progress_tracker.update_tracking(tracking_id, message="Building graph structure...")+ graph = self._build_graph_structure()- self.edges.append(edge)- self.edge_type_index[edge.edge_type].append(edge)-- return self._build_graph_structure()+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Built graph with {len(self.nodes)} nodes, {len(self.edges)} edges")+ return graph++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef add_node(self,diff --git a/semantica/context/context_retriever.py b/semantica/context/context_retriever.pyindex 7690889d..d5e49dc8 100644--- a/semantica/context/context_retriever.py+++ b/semantica/context/context_retriever.py@@ -36,6 +36,7 @@ from dataclasses import dataclass, fieldfrom ..utils.exceptions import ValidationError, ProcessingErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_tracker@dataclass@@ -86,6 +87,9 @@ class ContextRetriever:self.use_graph_expansion = self.config.get("use_graph_expansion", True)self.max_expansion_hops = self.config.get("max_expansion_hops", 2)self.hybrid_alpha = self.config.get("hybrid_alpha", 0.5)++ # Initialize progress tracker+ self.progress_tracker = get_progress_tracker()def retrieve(self,@@ -111,39 +115,58 @@ class ContextRetriever:Returns:List of retrieved context items"""- use_expansion = use_graph_expansion if use_graph_expansion is not None else self.use_graph_expansion-- all_results = []-- # Vector-based retrieval- vector_results = self._retrieve_from_vector(query, max_results * 2)- all_results.extend(vector_results)-- # Graph-based retrieval- if self.knowledge_graph and use_expansion:- graph_results = self._retrieve_from_graph(- query,- max_results * 2,- max_hops=options.get("max_hops", self.max_expansion_hops)- )- all_results.extend(graph_results)-- # Memory-based retrieval- if self.memory_store:- memory_results = self._retrieve_from_memory(query, max_results * 2)- all_results.extend(memory_results)+ # Track context retrieval+ tracking_id = self.progress_tracker.start_tracking(+ file=None,+ module="context",+ submodule="ContextRetriever",+ message=f"Retrieving context for: {query[:50]}..."+ )- # Combine and rank results- ranked_results = self._rank_and_merge(all_results, query)-- # Filter by minimum score- filtered_results = [- r for r in ranked_results- if r.score >= min_relevance_score- ]-- # Return top results- return filtered_results[:max_results]+ try:+ use_expansion = use_graph_expansion if use_graph_expansion is not None else self.use_graph_expansion++ all_results = []++ # Vector-based retrieval+ self.progress_tracker.update_tracking(tracking_id, message="Retrieving from vector store...")+ vector_results = self._retrieve_from_vector(query, max_results * 2)+ all_results.extend(vector_results)++ # Graph-based retrieval+ if self.knowledge_graph and use_expansion:+ self.progress_tracker.update_tracking(tracking_id, message="Retrieving from knowledge graph...")+ graph_results = self._retrieve_from_graph(+ query,+ max_results * 2,+ max_hops=options.get("max_hops", self.max_expansion_hops)+ )+ all_results.extend(graph_results)++ # Memory-based retrieval+ if self.memory_store:+ self.progress_tracker.update_tracking(tracking_id, message="Retrieving from memory...")+ memory_results = self._retrieve_from_memory(query, max_results * 2)+ all_results.extend(memory_results)++ # Combine and rank results+ self.progress_tracker.update_tracking(tracking_id, message="Ranking and merging results...")+ ranked_results = self._rank_and_merge(all_results, query)++ # Filter by minimum score+ filtered_results = [+ r for r in ranked_results+ if r.score >= min_relevance_score+ ]++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Retrieved {len(filtered_results[:max_results])} results")+ # Return top results+ return filtered_results[:max_results]++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef _retrieve_from_vector(self,diff --git a/semantica/context/entity_linker.py b/semantica/context/entity_linker.pyindex edc5ba98..bf543f9b 100644--- a/semantica/context/entity_linker.py+++ b/semantica/context/entity_linker.py@@ -39,6 +39,7 @@ import hashlibfrom ..utils.exceptions import ValidationError, ProcessingErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_trackerfrom ..utils.types import EntityDict@@ -98,6 +99,9 @@ class EntityLinker:self.base_uri = self.config.get("base_uri", "https://semantica.dev/entity/")self.enable_cross_document_linking = self.config.get("enable_cross_document_linking", True)+ # Initialize progress tracker+ self.progress_tracker = get_progress_tracker()+# Entity registry: entity_id -> URIself.entity_registry: Dict[str, str] = {}@@ -160,48 +164,59 @@ class EntityLinker:Returns:List of linked entities"""- if not entities:- entities = []-- linked_entities = []+ # Track entity linking+ tracking_id = self.progress_tracker.start_tracking(+ file=None,+ module="context",+ submodule="EntityLinker",+ message=f"Linking entities in text"+ )- for entity in entities:- entity_id = entity.get("id") or entity.get("entity_id")- entity_text = entity.get("text") or entity.get("label") or entity.get("name", "")- entity_type = entity.get("type") or entity.get("entity_type", "UNKNOWN")-- if not entity_id:- # Generate entity_id if not present- entity_id = self._generate_entity_id(entity_text, entity_type)+ try:+ if not entities:+ entities = []- # Assign URI- uri = self.assign_uri(entity_id, entity_text, entity_type)-- # Find linked entities- linked_entity_links = self._find_linked_entities(- entity_id,- entity_text,- entity_type,- entities,- context- )-- linked_entity = LinkedEntity(- entity_id=entity_id,- uri=uri,- text=entity_text,- type=entity_type,- linked_entities=linked_entity_links,- context=entity.get("metadata", {}),- confidence=entity.get("confidence", 1.0)- )+ linked_entities = []- linked_entities.append(linked_entity)+ self.progress_tracker.update_tracking(tracking_id, message=f"Linking {len(entities)} entities...")- # Store links- if entity_id not in self.entity_links:- self.entity_links[entity_id] = []- self.entity_links[entity_id].extend(linked_entity_links)+ for entity in entities:+ entity_id = entity.get("id") or entity.get("entity_id")+ entity_text = entity.get("text") or entity.get("label") or entity.get("name", "")+ entity_type = entity.get("type") or entity.get("entity_type", "UNKNOWN")++ if not entity_id:+ # Generate entity_id if not present+ entity_id = self._generate_entity_id(entity_text, entity_type)++ # Assign URI+ uri = self.assign_uri(entity_id, entity_text, entity_type)++ # Find linked entities+ linked_entity_links = self._find_linked_entities(+ entity_id,+ entity_text,+ entity_type,+ entities,+ context+ )++ linked_entity = LinkedEntity(+ entity_id=entity_id,+ uri=uri,+ text=entity_text,+ type=entity_type,+ linked_entities=linked_entity_links,+ context=entity.get("metadata", {}),+ confidence=entity.get("confidence", 1.0)+ )++ linked_entities.append(linked_entity)++ # Store links+ if entity_id not in self.entity_links:+ self.entity_links[entity_id] = []+ self.entity_links[entity_id].extend(linked_entity_links)return linked_entities@@ -228,37 +243,53 @@ class EntityLinker:Returns:True if link created successfully"""- link = EntityLink(- source_entity_id=entity1_id,- target_entity_id=entity2_id,- link_type=link_type,- confidence=confidence,- source=source,- metadata=metadata+ # Track entity linking+ tracking_id = self.progress_tracker.start_tracking(+ file=None,+ module="context",+ submodule="EntityLinker",+ message=f"Linking {entity1_id} -> {entity2_id}")- if entity1_id not in self.entity_links:- self.entity_links[entity1_id] = []-- self.entity_links[entity1_id].append(link)-- # Create bidirectional link if appropriate- if link_type in ["related_to", "same_as"]:- reverse_link = EntityLink(- source_entity_id=entity2_id,- target_entity_id=entity1_id,+ try:+ link = EntityLink(+ source_entity_id=entity1_id,+ target_entity_id=entity2_id,link_type=link_type,confidence=confidence,source=source,metadata=metadata)- if entity2_id not in self.entity_links:- self.entity_links[entity2_id] = []- self.entity_links[entity2_id].append(reverse_link)-- self.logger.debug(f"Linked {entity1_id} --{link_type}--> {entity2_id}")- return True+ if entity1_id not in self.entity_links:+ self.entity_links[entity1_id] = []++ self.entity_links[entity1_id].append(link)++ # Create bidirectional link if appropriate+ if link_type in ["related_to", "same_as"]:+ reverse_link = EntityLink(+ source_entity_id=entity2_id,+ target_entity_id=entity1_id,+ link_type=link_type,+ confidence=confidence,+ source=source,+ metadata=metadata+ )++ if entity2_id not in self.entity_links:+ self.entity_links[entity2_id] = []+ self.entity_links[entity2_id].append(reverse_link)++ self.logger.debug(f"Linked {entity1_id} --{link_type}--> {entity2_id}")++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Linked {entity1_id} -> {entity2_id}")+ return True++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef get_entity_links(self, entity_id: str) -> List[EntityLink]:"""