GraphAnalyzer error: TypeError: unhashable type: 'Entity' #159
|
Hi ! We are having trouble using the GraphAnalyzer module and can’t understand why it fails, even though the graph construction works correctly. We followed the official cookbook: https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb Graph construction works as expectedThe knowledge graph is successfully built, and the input data is valid. # ------------------------------------------------------------------------
# Graph construction
# ------------------------------------------------------------------------
# Initialize GraphBuilder with entity merging enabled
gb = GraphBuilder(merge_entities=True)
# Build knowledge graph from extraction results
logging.info("Building knowledge graph...")
kg = gb.build(sources=[combined_results])
logging.info("Initial graph statistics:")
logging.info(f" - Entities: {len(kg.get('entities', []))}")
logging.info(f" - Relationships: {len(kg.get('relationships', []))}")
logging.info(f" - Metadata: {kg.get('metadata', {})}")
The Entity Resolver works as expectedIt takes the knowledge graph and merge duplications nodes together perfectly from semantica.kg import EntityResolver
# Initialize EntityResolver
# similarity_threshold: Minimum similarity (0.85 = 85%) to consider entities as duplicates
resolver = EntityResolver(similarity_threshold=0.85)
logging.info("Resolving entities (deduplication)...")
logging.info(f" Method: Semantic similarity matching")
logging.info(f" Threshold: 0.85 (85% similarity)")
# Resolve entities using semantic method
resolved_entities = resolver.resolve_entities(
kg.get('entities', []),
)
# Create final graph with resolved entities
kg_final = {
**kg,
'entities': resolved_entities
}
logging.info(f"\nEntity resolution complete:")
logging.info(f" - Original entities: {len(kg.get('entities', []))}")
logging.info(f" - Resolved entities: {len(kg_final['entities'])}")
logging.info(f" - Entities merged: {len(kg.get('entities', [])) - len(kg_final['entities'])}")The Graph Analysis failsThe issue occurs when we try to analyze the graph: from semantica.kg import GraphAnalyzer
# Initialize GraphAnalyzer
analyzer = GraphAnalyzer()
logging.info("Analyzing graph structure...")
# Perform comprehensive graph analysis
analysis = analyzer.analyze_graph(kg_final)
# Extract metrics
metrics = analysis.get('metrics', {})
connectivity = analysis.get('connectivity', {})
logging.info("\nGraph structure metrics:")
logging.info(f" - Graph density: {metrics.get('density', 0):.4f}")
logging.info(f" - Connected components: {connectivity.get('connected_components', 0)}")
logging.info(f" - Average degree: {metrics.get('avg_degree', 0):.2f}")
logging.info(f" - Total nodes: {metrics.get('num_nodes', 0)}")
logging.info(f" - Total edges: {metrics.get('num_edges', 0)}")Error messageThe following error is raised during analysis (either for centrality measures or community detection): [RUNNING] | Module: kg | Submodule: CentralityCalculator | Message: Calculating degree centrality
[WARNING] NetworkX calculation failed: unhashable type: 'Entity', using basic implementation
[RUNNING] | Module: kg | Submodule: CentralityCalculator | Message: Building adjacency list...
[FAILED] | Module: kg | Submodule: CentralityCalculator | Message: unhashable type: 'Entity'
Traceback (most recent call last):
File "test_semantica/app.py", line 520, in <module>
analysis = analyzer.analyze_graph(kg_final)
File ".../semantica/kg/graph_analyzer.py", line 143, in analyze_graph
centrality = self.calculate_centrality(graph, **options)
File ".../semantica/kg/graph_analyzer.py", line 178, in calculate_centrality
return self.centrality_calculator.calculate_all_centrality(
File ".../semantica/kg/centrality_calculator.py", line 466, in calculate_all_centrality
results["degree"] = self.calculate_degree_centrality(graph)
File ".../centrality_calculator.py", line 178, in calculate_degree_centrality
adjacency = self._build_adjacency(graph)
File ".../centrality_calculator.py", line 502, in _build_adjacency
if target not in adjacency[source]:
TypeError: unhashable type: 'Entity'Do you know how we can fix this ? Are we missing a preprocessing step before calling the Graph Analyzer ? Thanks you in advance for your help and for all the work you do |
Replies: 1 comment
|
Hi @MoktarEls Thank you for the detailed bug report and for providing the logs. This was extremely helpful in identifying the root cause. The IssueYou're right—the graph construction and entity resolution steps were working perfectly, but the The FixWe have implemented a fix that makes the The changes include:
Code ExampleWith the latest fix on the from semantica.kg import GraphBuilder, EntityResolver, GraphAnalyzer
# 1. Build and Resolve
gb = GraphBuilder(merge_entities=True)
kg = gb.build(sources=[combined_results])
resolver = EntityResolver(similarity_threshold=0.85)
resolved_entities = resolver.resolve_entities(kg.get('entities', []))
kg_final = {
**kg,
'entities': resolved_entities
}
# 2. Analyze (This now works without TypeError)
analyzer = GraphAnalyzer()
analysis = analyzer.analyze_graph(kg_final)
# Access your metrics safely
metrics = analysis.get('metrics', {})
print(f"Graph Density: {metrics.get('density', 0):.4f}")
print(f"Nodes: {metrics.get('num_nodes', 0)}, Edges: {metrics.get('num_edges', 0)}")How to get the fixThe fix has been pushed to the git checkout kg
pip install -e .We've also added a new integration test suite ( Feel free to reach out if you encounter any other issues. Thanks for using Semantica! |
Hi @MoktarEls
Thank you for the detailed bug report and for providing the logs. This was extremely helpful in identifying the root cause.
The Issue
You're right—the graph construction and entity resolution steps were working perfectly, but the
GraphAnalyzerwas failing. The errorTypeError: unhashable type: 'Entity'occurred because the internal algorithms (Centrality, Community Detection, etc.) were attempting to use rawEntityobjects as dictionary keys when building the graph's adjacency list, rather than using their unique string IDs.The Fix
We have implemented a fix that makes the
GraphAnalyzermuch more robust. It now automatically detects and extracts the correct identifiers wheth…