-
Notifications
You must be signed in to change notification settings - Fork 89
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: deletes on the fly embeddings and uses edge collections #436
Merged
hajdul88
merged 3 commits into
dev
from
feature/cog-762-deleting-in-memory-embeddings-from-bruteforce-search-and
Jan 13, 2025
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -8,7 +8,7 @@ | |
from cognee.modules.graph.cognee_graph.CogneeGraphElements import Node, Edge | ||
from cognee.modules.graph.cognee_graph.CogneeAbstractGraph import CogneeAbstractGraph | ||
import heapq | ||
from graphistry import edges | ||
import asyncio | ||
|
||
|
||
class CogneeGraph(CogneeAbstractGraph): | ||
|
@@ -127,51 +127,25 @@ async def map_vector_distances_to_graph_nodes(self, node_distances) -> None: | |
else: | ||
print(f"Node with id {node_id} not found in the graph.") | ||
|
||
async def map_vector_distances_to_graph_edges( | ||
self, vector_engine, query | ||
) -> None: # :TODO: When we calculate edge embeddings in vector db change this similarly to node mapping | ||
async def map_vector_distances_to_graph_edges(self, vector_engine, query) -> None: | ||
try: | ||
# Step 1: Generate the query embedding | ||
query_vector = await vector_engine.embed_data([query]) | ||
query_vector = query_vector[0] | ||
if query_vector is None or len(query_vector) == 0: | ||
raise ValueError("Failed to generate query embedding.") | ||
|
||
# Step 2: Collect all unique relationship types | ||
unique_relationship_types = set() | ||
for edge in self.edges: | ||
relationship_type = edge.attributes.get("relationship_type") | ||
if relationship_type: | ||
unique_relationship_types.add(relationship_type) | ||
|
||
# Step 3: Embed all unique relationship types | ||
unique_relationship_types = list(unique_relationship_types) | ||
relationship_type_embeddings = await vector_engine.embed_data(unique_relationship_types) | ||
|
||
# Step 4: Map relationship types to their embeddings and calculate distances | ||
embedding_map = {} | ||
for relationship_type, embedding in zip( | ||
unique_relationship_types, relationship_type_embeddings | ||
): | ||
edge_vector = np.array(embedding) | ||
|
||
# Calculate cosine similarity | ||
similarity = np.dot(query_vector, edge_vector) / ( | ||
np.linalg.norm(query_vector) * np.linalg.norm(edge_vector) | ||
) | ||
distance = 1 - similarity | ||
edge_distances = await vector_engine.get_distance_from_collection_elements( | ||
"edge_type_relationship_name", query_text=query | ||
) | ||
|
||
# Round the distance to 4 decimal places and store it | ||
embedding_map[relationship_type] = round(distance, 4) | ||
embedding_map = {result.payload["text"]: result.score for result in edge_distances} | ||
|
||
# Step 4: Assign precomputed distances to edges | ||
for edge in self.edges: | ||
relationship_type = edge.attributes.get("relationship_type") | ||
if not relationship_type or relationship_type not in embedding_map: | ||
print(f"Edge {edge} has an unknown or missing relationship type.") | ||
continue | ||
|
||
# Assign the precomputed distance | ||
edge.attributes["vector_distance"] = embedding_map[relationship_type] | ||
Comment on lines
+141
to
149
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion Improve edge distance mapping robustness The current implementation has potential issues:
Consider this improvement: - embedding_map = {result.payload["text"]: result.score for result in edge_distances}
+ embedding_map = {}
+ for result in edge_distances:
+ if "text" not in result.payload:
+ raise InvalidValueError(f"Missing 'text' in payload: {result.payload}")
+ if not isinstance(result.score, (int, float)):
+ raise InvalidValueError(f"Invalid score type: {type(result.score)}")
+ embedding_map[result.payload["text"]] = result.score
for edge in self.edges:
relationship_type = edge.attributes.get("relationship_type")
if not relationship_type or relationship_type not in embedding_map:
- print(f"Edge {edge} has an unknown or missing relationship type.")
+ logging.warning("Edge %s has an unknown or missing relationship type", edge)
continue
edge.attributes["vector_distance"] = embedding_map[relationship_type]
|
||
|
||
except Exception as ex: | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Enhance error handling and logging
The method has several areas that could benefit from improved error handling:
Consider this improvement: