fix(api): 修复记忆可视化中重复的边

在从内存管理器和文件加载图数据时,由于遍历所有记忆(memory)并收集其关联的边(edge)时没有进行去重处理,导致同一条边如果被多个记忆引用,会在最终的图谱中重复出现,造成前端可视化混乱。

为了解决这个问题,引入了一个集合(set)或字典(dict)来跟踪已经处理过的边的ID。在遍历边的过程中,只有当边的ID未被记录时,才会将其添加到最终的边列表中。这样可以确保每条边在图谱数据中只出现一次,保证了可视化结果的准确性。
This commit is contained in:
minecraft1024a
2025-11-08 09:53:44 +08:00
parent 9a8a3214a7
commit c22c6b7231

View File

@@ -102,16 +102,21 @@ def load_graph_data_from_file(file_path: Optional[Path] = None) -> Dict[str, Any
if node.get("id") if node.get("id")
} }
edges_list = [ edges_list = []
{ seen_edge_ids = set()
**edge, for edge in edges:
"from": edge.get("source", edge.get("source_id")), edge_id = edge.get("id")
"to": edge.get("target", edge.get("target_id")), if edge_id and edge_id not in seen_edge_ids:
"label": edge.get("relation", ""), edges_list.append(
"arrows": "to", {
} **edge,
for edge in edges "from": edge.get("source", edge.get("source_id")),
] "to": edge.get("target", edge.get("target_id")),
"label": edge.get("relation", ""),
"arrows": "to",
}
)
seen_edge_ids.add(edge_id)
stats = metadata.get("statistics", {}) stats = metadata.get("statistics", {})
total_memories = stats.get("total_memories", 0) total_memories = stats.get("total_memories", 0)
@@ -151,7 +156,7 @@ def _format_graph_data_from_manager(memory_manager) -> Dict[str, Any]:
all_memories = memory_manager.graph_store.get_all_memories() all_memories = memory_manager.graph_store.get_all_memories()
nodes_dict = {} nodes_dict = {}
edges_list = [] edges_dict = {}
memory_info = [] memory_info = []
for memory in all_memories: for memory in all_memories:
@@ -173,8 +178,8 @@ def _format_graph_data_from_manager(memory_manager) -> Dict[str, Any]:
"title": f"{node.node_type.value}: {node.content}", "title": f"{node.node_type.value}: {node.content}",
} }
for edge in memory.edges: for edge in memory.edges:
edges_list.append( # noqa: PERF401 if edge.id not in edges_dict:
{ edges_dict[edge.id] = {
"id": edge.id, "id": edge.id,
"from": edge.source_id, "from": edge.source_id,
"to": edge.target_id, "to": edge.target_id,
@@ -182,7 +187,8 @@ def _format_graph_data_from_manager(memory_manager) -> Dict[str, Any]:
"arrows": "to", "arrows": "to",
"memory_id": memory.id, "memory_id": memory.id,
} }
)
edges_list = list(edges_dict.values())
stats = memory_manager.get_statistics() stats = memory_manager.get_statistics()
return { return {