Skip to content

BrainAPI is a knowledge graph–powered AI memory layer that transforms unstructured data into structured knowledge, enabling intelligent search, recommendations, and contextual memory for AI agents and applications.

wip(synergies): improved retrieval

Christian871c40a56cc8
diff --git a/src/adapters/graph.py b/src/adapters/graph.py
index 9fbf2ac..137646a 100644
--- a/src/adapters/graph.py
+++ b/src/adapters/graph.py
@@ -9,7 +9,7 @@ Modified By: Christian Nonis <[email protected]>
"""
from typing import Dict, List, Literal, Optional, Tuple
-from src.adapters.interfaces.graph import GraphClient
+from src.adapters.interfaces.graph import GraphClient, PredicateWithFlowKey
from src.constants.embeddings import Vector
from src.constants.kg import (
IdentificationParams,
@@ -627,21 +627,22 @@ class GraphAdapter:
"""
return self.graph.get_neighborhood(node, depth, brain_id)
- def get_next_by_flow_key(
- self, predicate_uuid: str, flow_key: str, brain_id: str = "default"
- ) -> List[Tuple[Node, Predicate, Node]]:
+ def get_nexts_by_flow_key(
+ self,
+ predicates: list[PredicateWithFlowKey],
+ brain_id: str = "default",
+ ) -> Dict[str, List[Tuple[Node, Predicate, Node]]]:
"""
- Retrieve the next connected node tuple(s) for a relationship identified by a flow key.
+ Retrieve the next connected node tuple(s) for a relationship identified by a flow key, grouped by the predicate UUID.
Parameters:
- predicate_uuid (str): UUID of the predicate (relationship) to search from.
- flow_key (str): Flow key value used to select the next relationship target.
+ predicates (list[PredicateWithFlowKey]): A list of predicates with their flow keys.
brain_id (str): Identifier of the brain/graph namespace to query.
Returns:
- List[Tuple[Node, Predicate, Node]]: A list of (subject node, predicate, object node) tuples that are the next nodes matching the provided flow key; empty list if none are found.
+ Dict[str, List[Tuple[Node, Predicate, Node]]]: A dictionary mapping predicate UUIDs to lists of (subject node, predicate, object node) tuples that are the next nodes matching the provided flow key; empty dictionary if none are found for any predicate UUID.
"""
- return self.graph.get_next_by_flow_key(predicate_uuid, flow_key, brain_id)
+ return self.graph.get_nexts_by_flow_key(predicates, brain_id)
def get_triples_by_uuid(
self, uuids: list[str], brain_id: str
diff --git a/src/adapters/interfaces/graph.py b/src/adapters/interfaces/graph.py
index ede2268..a18bf23 100644
--- a/src/adapters/interfaces/graph.py
+++ b/src/adapters/interfaces/graph.py
@@ -9,7 +9,7 @@ Modified By: Christian Nonis <[email protected]>
"""
from abc import ABC, abstractmethod
-from typing import Dict, List, Literal, Optional, Tuple
+from typing import Dict, List, Literal, Optional, Tuple, TypedDict
from src.constants.kg import (
IdentificationParams,
@@ -23,6 +23,11 @@ from src.constants.kg import (
from src.adapters.interfaces.embeddings import VectorStoreClient
+class PredicateWithFlowKey(TypedDict):
+ predicate_uuid: str
+ flow_key: str
+
+
class GraphClient(ABC):
"""
Abstract base class for graph clients.
@@ -434,16 +439,20 @@ class GraphClient(ABC):
raise NotImplementedError("get_neighborhood method not implemented")
@abstractmethod
- def get_next_by_flow_key(
- self, predicate_uuid: str, flow_key: str, brain_id: str
- ) -> List[Tuple[Node, Predicate, Node]]:
+ def get_nexts_by_flow_key(
+ self, predicates: list[PredicateWithFlowKey], brain_id: str
+ ) -> Dict[str, List[Tuple[Node, Predicate, Node]]]:
"""
- Retrieve the next connected node and the relationship identified by a flow key for a given predicate.
+ Retrieve the next connected node tuple(s) for a relationship identified by a flow key, grouped by the predicate UUID.
+
+ Parameters:
+ predicates: list[PredicateWithFlowKey]: A list of predicates with their flow keys.
+ brain_id (str): Identifier of the brain/graph to query.
Returns:
- List[Tuple[Node, Predicate, Node]]: A list of triples where each triple is (connected node to the predicate, relationship that matches the provided flow_key, next node reached via that relationship).
+ Dict[str, List[Tuple[Node, Predicate, Node]]]: A dictionary mapping predicate UUIDs to lists of (subject node, predicate, object node) tuples that are the next nodes matching the provided flow key; empty dictionary if none are found for any predicate UUID.
"""
- raise NotImplementedError("get_next_by_flow_key method not implemented")
+ raise NotImplementedError("get_nexts_by_flow_key method not implemented")
@abstractmethod
def get_triples_by_uuid(
diff --git a/src/constants/kg.py b/src/constants/kg.py
index a117040..01d965a 100644
--- a/src/constants/kg.py
+++ b/src/constants/kg.py
@@ -9,7 +9,7 @@ Modified By: Christian Nonis <[email protected]>
"""
from datetime import datetime
-from typing import List, Literal, Optional, Tuple, TypedDict
+from typing import List, Literal, Optional, Tuple, TypedDict, Union
import uuid
from pydantic import BaseModel, ConfigDict, Extra, Field
@@ -181,7 +181,8 @@ class EntitySynergy(BaseModel):
"""
node: Node
- connected_by: Tuple[Node, Node]
+ connected_by: List[Node]
+ association_score: float
class NodeDict(TypedDict, total=False):
diff --git a/src/core/agents/tools/kg_agent/KGAgentRemoveRelationshipTool.py b/src/core/agents/tools/kg_agent/KGAgentRemoveRelationshipTool.py
index 31deeaa..049c728 100644
--- a/src/core/agents/tools/kg_agent/KGAgentRemoveRelationshipTool.py
+++ b/src/core/agents/tools/kg_agent/KGAgentRemoveRelationshipTool.py
@@ -133,6 +133,8 @@ class KGAgentRemoveRelationshipTool(BaseTool):
if "tail" in args_uuid and "head" in args_uuid:
_tail = args_uuid.get("tail", {})
_head = args_uuid.get("head", {})
+ if "relationship_name" in args_uuid:
+ _relationship_name = args_uuid.get("relationship_name", "")
elif isinstance(args_uuid, list) and len(args_uuid) > 0:
first_arg = args_uuid[0]
if isinstance(first_arg, dict):
diff --git a/src/core/saving/auto_kg.py b/src/core/saving/auto_kg.py
index b3c6794..7ba752b 100644
--- a/src/core/saving/auto_kg.py
+++ b/src/core/saving/auto_kg.py
@@ -107,7 +107,7 @@ def _enrich_kg_impl(input: str, targeting, brain_id: str, ingestion_session_id:
entities.entities,
targeting=targeting,
brain_id=brain_id,
- timeout=360 * len(input),
+ timeout=20000,
ingestion_session_id=ingestion_session_id,
)
token_details.append(
diff --git a/src/core/search/entity_sibilings.py b/src/core/search/entity_sibilings.py
index c7a2d04..3d83bfb 100644
--- a/src/core/search/entity_sibilings.py
+++ b/src/core/search/entity_sibilings.py
@@ -3,27 +3,33 @@ File: /entity_sibilings.py
Created Date: Monday January 12th 2026
Author: Christian Nonis <[email protected]>
-----
-Last Modified: Monday January 12th 2026 9:48:46 pm
+Last Modified: Thursday January 29th 2026 8:43:59 pm
Modified By: Christian Nonis <[email protected]>
-----
"""
from dataclasses import dataclass
from typing import List, Literal, Tuple
+import numpy as np
+from src.adapters.interfaces.graph import PredicateWithFlowKey
from src.constants.kg import EntitySynergy, Node
from src.services.kg_agent.main import (
embeddings_adapter,
graph_adapter,
vector_store_adapter,
)
+from src.utils.similarity.vectors import cosine_similarity
+
+DIRECT_MULTIPLIER = 1.30
+REMOTE_MULTIPLIER = 0.70
class EntitySinergyRetriever:
def __init__(self, brain_id: str = "default"):
"""
Initialize the retriever with the identifier of the brain (knowledge graph) to operate against.
-
+
Parameters:
brain_id (str): Identifier of the brain/knowledge graph to use for adapter calls. Defaults to "default".
"""
@@ -31,18 +37,18 @@ class EntitySinergyRetriever:
def retrieve_sibilings(
self, target: str, polarity: Literal["same", "opposite"]
- ) -> Tuple[Node, List[EntitySynergy]]:
+ ) -> Tuple[Node, List[EntitySynergy], List[Node], List[Node]]:
"""
Find related entities ("siblings") for a given target text by locating the target node and assembling EntitySynergy connections from its neighbors and embedding-based similarity.
-
+
This returns the resolved target graph node (or None if no matching node is found) and a list of EntitySynergy objects that represent related nodes discovered via neighbor relationships and vector-similarity matches. The method may return early with an empty list when required intermediate data (target node, similarity seeds, or similar nodes) is missing.
-
+
Parameters:
target: The text used to locate the target entity in the node store.
polarity: A directive indicating the type of relation to retrieve; expected values are "same" or "opposite".
-
+
Returns:
- (target_node, connections):
+ (target_node, connections):
- target_node (Node or None): the graph node matching the provided target text, or `None` if not found.
- connections (List[EntitySynergy]): a list of EntitySynergy entries representing related entities; may be empty.
"""
@@ -51,11 +57,11 @@ class EntitySinergyRetriever:
target_embedding.embeddings, store="nodes", brain_id=self.brain_id
)
if not target_node_vs:
- return None, []
+ return None, [], []
target_node_id = target_node_vs[0].metadata.get("uuid")
target_node = graph_adapter.get_by_uuid(target_node_id, brain_id=self.brain_id)
if not target_node:
- return None, []
+ return None, [], []
_neighbors = graph_adapter.get_neighbors(
[target_node_id], brain_id=self.brain_id
@@ -65,120 +71,264 @@ class EntitySinergyRetriever:
positivep_connections: List[EntitySynergy] = []
seen_set = set([target_node.uuid])
- similarity_seed_nodes = []
- neighbor_map = {}
+ all_seed_nodes: List[Node] = []
+ all_similar_seeds: List[Node] = []
+
+ target_vid = target_node.properties.get("v_id")
+ target_embedding = None
+ if target_vid:
+ _target_embedding = vector_store_adapter.get_by_ids(
+ [target_vid],
+ store="nodes",
+ brain_id=self.brain_id,
+ )
+ if _target_embedding:
+ target_embedding = _target_embedding[0].embeddings
for neighbor in neighbors:
seed_nodes_for_neighbor = []
-
+ target_embeddings = []
+ _neighbor_embeddings = vector_store_adapter.get_by_ids(
+ [neighbor[0].properties.get("v_id")],
+ store="relationships",
+ brain_id=self.brain_id,
+ )
+ if not _neighbor_embeddings:
+ continue
+ neighbor_embeddings = _neighbor_embeddings[0].embeddings
if "EVENT" in neighbor[1].labels:
flow_key = neighbor[0].flow_key or neighbor[0].properties.get(
"flow_key"
)
if not flow_key:
continue
- next_rels = graph_adapter.get_next_by_flow_key(
- neighbor[0].uuid, flow_key, brain_id=self.brain_id
+ next_rels = graph_adapter.get_nexts_by_flow_key(
+ [
+ PredicateWithFlowKey(
+ predicate_uuid=neighbor[0].uuid,
+ flow_key=flow_key,
+ )
+ ],
+ brain_id=self.brain_id,
)
- seed_nodes_for_neighbor = [t[2] for t in next_rels]
- else:
- seed_nodes_for_neighbor = [neighbor[1]]
-
- for seed_node in seed_nodes_for_neighbor:
- similarity_seed_nodes.append(seed_node)
- if seed_node.uuid not in neighbor_map:
- neighbor_map[seed_node.uuid] = []
- neighbor_map[seed_node.uuid].append(neighbor[1])
-
- if not similarity_seed_nodes:
- return target_node, positivep_connections
-
- for similarity_seed_node in similarity_seed_nodes:
- if any(
- label in similarity_seed_node.labels for label in target_node.labels
- ):
- for connected_by_node in neighbor_map[similarity_seed_node.uuid]:
- positivep_connections.append(
- EntitySynergy(
- node=similarity_seed_node,
- connected_by=(connected_by_node, connected_by_node),
+ for t in next_rels[neighbor[0].uuid]:
+ if target_node.uuid in [t[2].uuid, t[0].uuid]:
+ continue
+ v_id = t[1].properties.get("v_id")
+ if not v_id:
+ continue
+ _target_embedding = vector_store_adapter.get_by_ids(
+ [v_id],
+ store="relationships",
+ brain_id=self.brain_id,
+ )
+ if not _target_embedding:
+ continue
+ target_embedding = _target_embedding[0].embeddings
+ target_embeddings.append(
+ np.mean(
+ [target_embedding, neighbor_embeddings],
+ axis=0,
)
)
- seen_set.add(similarity_seed_node.uuid)
-
- v_ids_to_search = [
- seed_node.properties.get("v_id")
- for seed_node in similarity_seed_nodes
- if seed_node.properties.get("v_id")
- ]
-
- if not v_ids_to_search:
- return target_node, positivep_connections
-
- all_similar_dict = vector_store_adapter.search_similar_by_ids(
- v_ids_to_search,
- brain_id=self.brain_id,
- store="nodes",
- min_similarity=0.5,
- limit=10,
- )
+ seed_nodes_for_neighbor.append(t[2])
+ else:
+ seed_nodes_for_neighbor = [neighbor[1]]
+ target_embeddings = neighbor_embeddings
- similar_node_uuids = set()
- v_id_to_seed_node = {
- seed_node.properties.get("v_id"): seed_node
- for seed_node in similarity_seed_nodes
- if seed_node.properties.get("v_id")
- }
+ all_seed_nodes.extend(seed_nodes_for_neighbor)
- for v_id, similar_vectors in all_similar_dict.items():
- for similar_node_v in similar_vectors:
- similar_uuid = similar_node_v.metadata.get("uuid")
- if similar_uuid:
- similar_node_uuids.add(similar_uuid)
+ print(
+ f"[SEED NODES] {[n.name for n in seed_nodes_for_neighbor]}"
+ ) # PERFECT
- if not similar_node_uuids:
- return target_node, positivep_connections
+ def _process_seed(seed_node: Node, direct: bool):
+ _neighbors_direct = graph_adapter.get_neighbors(
+ [seed_node.uuid],
+ of_types=target_node.labels,
+ brain_id=self.brain_id,
+ )
- similar_nodes = graph_adapter.get_by_uuids(
- list(similar_node_uuids), brain_id=self.brain_id
- )
- similar_nodes_by_uuid = {node.uuid: node for node in similar_nodes if node}
+ _neighbors_event_edges = graph_adapter.get_neighbors(
+ [seed_node.uuid],
+ of_types=["EVENT"],
+ brain_id=self.brain_id,
+ )
+ edges_map = {
+ edge[0].uuid: edge[0]
+ for edge in _neighbors_event_edges[seed_node.uuid]
+ }
+ _neighbors_event = graph_adapter.get_nexts_by_flow_key(
+ [
+ PredicateWithFlowKey(
+ predicate_uuid=edge_uuid,
+ flow_key=edges_map[edge_uuid].flow_key,
+ )
+ for edge_uuid in edges_map.keys()
+ ],
+ brain_id=self.brain_id,
+ )
- if not similar_nodes_by_uuid:
- return target_node, positivep_connections
+ _neighbors = []
+ for edge_uuid, n in _neighbors_event.items():
+ for e in n:
+ if e[2].uuid != target_node.uuid:
+ if e[2].uuid in seen_set:
+ continue
+ if not set(e[2].labels).intersection(target_node.labels):
+ continue
+ edge_vid = edges_map[edge_uuid].properties.get("v_id")
+ if not edge_vid:
+ continue
+ _edge_embedding = vector_store_adapter.get_by_ids(
+ [edge_vid],
+ store="relationships",
+ brain_id=self.brain_id,
+ )
+ if not _edge_embedding:
+ continue
+ edge_embedding = _edge_embedding[0].embeddings
+ _en_embedding = vector_store_adapter.get_by_ids(
+ [e[1].properties.get("v_id")],
+ store="relationships",
+ brain_id=self.brain_id,
+ )
+ if not _en_embedding:
+ continue
+ en_embedding = _en_embedding[0].embeddings
+ found_embeddings = np.mean(
+ [
+ en_embedding,
+ edge_embedding,
+ ],
+ axis=0,
+ )
+ neighbor_vid = e[1].properties.get("v_id")
+ if not neighbor_vid:
+ continue
+ _neighbor_embedding = vector_store_adapter.get_by_ids(
+ [neighbor_vid],
+ store="relationships",
+ brain_id=self.brain_id,
+ )
+ if not _neighbor_embedding:
+ continue
+ neighbor_embedding = _neighbor_embedding[0].embeddings
+ tn_score = cosine_similarity(
+ neighbor_embedding, target_embedding
+ )
+ rel_score = cosine_similarity(
+ found_embeddings, target_embedding
+ )
+ print(
+ f"[{e[2].name}] tn_score: {tn_score}, rel_score: {rel_score}, {DIRECT_MULTIPLIER if direct else REMOTE_MULTIPLIER}"
+ )
+ _neighbors.append(
+ (
+ (
+ np.mean([tn_score, rel_score], axis=0)
+ * (
+ DIRECT_MULTIPLIER
+ if direct
+ else REMOTE_MULTIPLIER
+ )
+ ),
+ e[2],
+ )
+ )
- all_neighbors = graph_adapter.get_neighbors(
- list(similar_nodes_by_uuid.keys()),
- brain_id=self.brain_id,
- of_types=list(set(target_node.labels)),
- )
+ for dn in _neighbors_direct[seed_node.uuid]:
+ if dn[1].uuid != target_node.uuid:
+ if dn[1].uuid in seen_set:
+ continue
+ n_vid = dn[0].properties.get("v_id")
+ if not n_vid:
+ continue
+ _n_embedding = vector_store_adapter.get_by_ids(
+ [n_vid],
+ store="relationships",
+ brain_id=self.brain_id,
+ )
+ if not _n_embedding:
+ continue
+ n_embedding = _n_embedding[0].embeddings
+ tn_score = cosine_similarity(n_embedding, target_embedding)
+ rel_vid = dn[0].properties.get("v_id")
+ if not rel_vid:
+ continue
+ _rel_embedding = vector_store_adapter.get_by_ids(
+ [rel_vid],
+ store="relationships",
+ brain_id=self.brain_id,
+ )
+ if not _rel_embedding:
+ continue
+ rel_embedding = _rel_embedding[0].embeddings
+ rel_score = cosine_similarity(rel_embedding, target_embedding)
+ _neighbors.append(
+ (
+ (
+ np.mean([tn_score, rel_score], axis=0)
+ * (
+ DIRECT_MULTIPLIER
+ if direct
+ else REMOTE_MULTIPLIER
+ )
+ ),
+ dn[1],
+ )
+ )
- for v_id, similar_vectors in all_similar_dict.items():
- seed_node = v_id_to_seed_node.get(v_id)
- if not seed_node:
- continue
+ if not _neighbors or len(_neighbors) == 0:
+ return
- for similar_node_v in similar_vectors:
- similar_uuid = similar_node_v.metadata.get("uuid")
- similar_node_1 = similar_nodes_by_uuid.get(similar_uuid)
+ for neighbor in _neighbors:
+ positivep_connections.append(
+ EntitySynergy(
+ node=neighbor[1],
+ connected_by=seed_node,
+ association_score=neighbor[0],
+ )
+ )
+ seen_set.add(neighbor[1].uuid)
- if not similar_node_1:
+ for seed_node in seed_nodes_for_neighbor:
+ seed_vid = seed_node.properties.get("v_id")
+ if not seed_vid:
+ continue
+ _seed_embedding = vector_store_adapter.get_by_ids(
+ [seed_vid],
+ store="nodes",
+ brain_id=self.brain_id,
+ )
+ if not _seed_embedding:
continue
+ seed_embedding = _seed_embedding[0].embeddings
- neighbors_of_similar = all_neighbors.get(similar_node_1.uuid, [])
+ similar_seed_vs = vector_store_adapter.search_vectors(
+ seed_embedding,
+ store="nodes",
+ brain_id=self.brain_id,
+ )
- for final_connection_tuple in neighbors_of_similar:
- final_node_uuid = final_connection_tuple[1].uuid
- if final_node_uuid in seen_set:
- continue
+ similar_seeds = graph_adapter.get_by_uuids(
+ [vs.metadata.get("uuid") for vs in similar_seed_vs],
+ brain_id=self.brain_id,
+ )
- seen_set.add(final_node_uuid)
+ _process_seed(seed_node, direct=True)
- positivep_connections.append(
- EntitySynergy(
- node=final_connection_tuple[1],
- connected_by=(seed_node, similar_node_1),
- )
- )
+ all_similar_seeds.extend(similar_seeds)
+
+ for similar_seed in similar_seeds:
+ _process_seed(similar_seed, direct=False)
- return target_node, positivep_connections
\ No newline at end of file
+ unique_seeds = {n.uuid: n for n in all_seed_nodes}
+ return (
+ target_node,
+ sorted(
+ positivep_connections, key=lambda x: x.association_score, reverse=True
+ ),
+ list(unique_seeds.values()),
+ all_similar_seeds,
+ )
diff --git a/src/lib/neo4j/client.py b/src/lib/neo4j/client.py
index 4f3026e..485fec1 100644
--- a/src/lib/neo4j/client.py
+++ b/src/lib/neo4j/client.py
@@ -3,7 +3,7 @@ File: /client.py
Created Date: Sunday October 19th 2025
Author: Christian Nonis <[email protected]>
-----
-Last Modified: Thursday January 29th 2026 8:44:06 pm
+Last Modified: Monday February 2nd 2026 10:02:37 pm
Modified By: Christian Nonis <[email protected]>
-----
"""
@@ -15,7 +15,7 @@ from typing import Any, Dict, List, Literal, Optional, Tuple, TypedDict
from neo4j import GraphDatabase
from neo4j.exceptions import ClientError
from src.adapters.interfaces.embeddings import VectorStoreClient
-from src.adapters.interfaces.graph import GraphClient
+from src.adapters.interfaces.graph import GraphClient, PredicateWithFlowKey
from src.config import config
from src.constants.kg import (
IdentificationParams,
@@ -42,6 +42,8 @@ class Neo4jClient(GraphClient):
connection_timeout=30,
max_connection_lifetime=300,
connection_acquisition_timeout=60,
+ warn_notification_severity="OFF",
+ notifications_min_severity="OFF",
)
def execute_operation(self, operation: str, brain_id: str) -> str:
@@ -264,7 +266,7 @@ class Neo4jClient(GraphClient):
escaped_value = self._format_value(value)
property_assignments.append(f"n.{cypher_key} = {escaped_value}")
- property_assignments.append(f"n.uuid = '{node.uuid}'")
+ property_assignments.append(f"n['uuid'] = '{node.uuid}'")
properties_set = f"{', '.join(property_assignments)}"
@@ -331,18 +333,18 @@ class Neo4jClient(GraphClient):
value = getattr(obj, attr, None)
if value:
extra_ops += f"""
- SET r.{attr} = {self._format_value(value)}
+ SET r['{attr}'] = {self._format_value(value)}
"""
cypher_query = f"""
- MATCH (a:{":".join(self._clean_labels(subject.labels))}) WHERE a.name = {self._format_value(subject.name)}
- MATCH (b:{":".join(self._clean_labels(to_object.labels))}) WHERE b.name = {self._format_value(to_object.name)}
+ MATCH (a:{":".join(self._clean_labels(subject.labels))}) WHERE a['name'] = {self._format_value(subject.name)}
+ MATCH (b:{":".join(self._clean_labels(to_object.labels))}) WHERE b['name'] = {self._format_value(to_object.name)}
MERGE (a)-[r:{":".join(self._clean_labels([predicate.name]))}]->(b)
ON CREATE
- SET r.description = {self._format_value(predicate.description)},
- r.uuid = {self._format_value(predicate.uuid)},
- r.v_id = {self._format_value(predicate.properties.get("v_id"))},
- r.flow_key = {self._format_value(predicate.flow_key)}
+ SET r['description'] = {self._format_value(predicate.description)},
+ r['uuid'] = {self._format_value(predicate.uuid)},
+ r['v_id'] = {self._format_value(predicate.properties.get("v_id"))},
+ r['flow_key'] = {self._format_value(predicate.flow_key)}
{extra_ops}
RETURN a, b
"""
@@ -360,7 +362,7 @@ class Neo4jClient(GraphClient):
queries = []
for node in nodes:
- query = f"""MATCH (n:{":".join(self._clean_labels(node.labels))}) WHERE n.name = {self._format_value(node.name)}
+ query = f"""MATCH (n:{":".join(self._clean_labels(node.labels))}) WHERE n['name'] = {self._format_value(node.name)}
OPTIONAL MATCH (n)-[r*1]-(m)
RETURN n, r, m"""
queries.append(query)
@@ -376,7 +378,7 @@ class Neo4jClient(GraphClient):
"""
cypher_query = f"""
MATCH (n)
- WHERE toLower(n.name) CONTAINS toLower({self._format_value(text)})
+ WHERE toLower(n['name']) CONTAINS toLower({self._format_value(text)})
RETURN n
"""
self.ensure_database(brain_id)
@@ -405,7 +407,7 @@ class Neo4jClient(GraphClient):
Get nodes by their UUIDs with optional relationships.
"""
cypher_query = f"""
- MATCH (n) WHERE n.uuid IN ["{'","'.join(uuids)}"]
+ MATCH (n) WHERE n['uuid'] IN ["{'","'.join(uuids)}"]
"""
if with_relationships:
@@ -429,11 +431,11 @@ class Neo4jClient(GraphClient):
cypher_query += """
RETURN
- n.uuid as uuid, n.name as name, labels(n) as labels, n.description as description, properties(n) as properties
+ n['uuid'] as uuid, n['name'] as name, labels(n) as labels, n['description'] as description, properties(n) as properties
"""
if with_relationships:
- cypher_query += ", r, m.uuid as m_uuid, m.name as m_name, labels(m) as m_labels, m.description as m_description, properties(m) as m_properties"
+ cypher_query += ", r, m['uuid'] as m_uuid, m['name'] as m_name, labels(m) as m_labels, m['description'] as m_description, properties(m) as m_properties"
self.ensure_database(brain_id)
result = self.driver.execute_query(cypher_query, database_=brain_id)
@@ -513,11 +515,11 @@ class Neo4jClient(GraphClient):
Node or None: The matching node, or `None` if no node with the given UUID exists.
"""
cypher_query = """
- MATCH (n) WHERE n.uuid = $uuid
- RETURN n.uuid as uuid, n.name as name, labels(n) as labels, n.description as description,
+ MATCH (n) WHERE n['uuid'] = $uuid
+ RETURN n['uuid'] as uuid, n['name'] as name, labels(n) as labels, n['description'] as description,
properties(n) as properties,
- n.polarity as polarity, n.happened_at as happened_at, n.last_updated as last_updated,
- n.observations as observations, n.metadata as metadata
+ n['polarity'] as polarity, n['happened_at'] as happened_at, n['last_updated'] as last_updated,
+ n['observations'] as observations, n['metadata'] as metadata
"""
self.ensure_database(brain_id)
result = self.driver.execute_query(
@@ -545,11 +547,11 @@ class Neo4jClient(GraphClient):
list[Node]: Nodes with identifiers, names, labels, descriptions, and properties; includes, when available, polarity, happened_at, last_updated, observations, and metadata.
"""
cypher_query = f"""
- MATCH (n) WHERE n.uuid IN ["{'","'.join(uuids)}"]
- RETURN n.uuid as uuid, n.name as name, labels(n) as labels, n.description as description,
+ MATCH (n) WHERE n['uuid'] IN ["{'","'.join(uuids)}"]
+ RETURN n['uuid'] as uuid, n['name'] as name, labels(n) as labels, n['description'] as description,
properties(n) as properties,
- n.polarity as polarity, n.happened_at as happened_at, n.last_updated as last_updated,
- n.observations as observations, n.metadata as metadata
+ n['polarity'] as polarity, n['happened_at'] as happened_at, n['last_updated'] as last_updated,
+ n['observations'] as observations, n['metadata'] as metadata
"""
self.ensure_database(brain_id)
result = self.driver.execute_query(cypher_query, database_=brain_id)
@@ -627,10 +629,10 @@ class Neo4jClient(GraphClient):
cypher_query = f"""
MATCH (n{labels_str}) {where_str}
- RETURN n.uuid as uuid, n.name as name, labels(n) as labels, n.description as description,
+ RETURN n['uuid'] as uuid, n['name'] as name, labels(n) as labels, n['description'] as description,
properties(n) as properties,
- n.polarity as polarity, n.happened_at as happened_at, n.last_updated as last_updated,
- n.observations as observations, n.metadata as metadata
+ n['polarity'] as polarity, n['happened_at'] as happened_at, n['last_updated'] as last_updated,
+ n['observations'] as observations, n['metadata'] as metadata
"""
self.ensure_database(brain_id)
@@ -681,7 +683,7 @@ class Neo4jClient(GraphClient):
uuids_list = '", "'.join(node_uuids)
cypher_query = f"""
MATCH (n)-[r]-(c)
- WHERE n.uuid IN ["{uuids_list}"]
+ WHERE n['uuid'] IN ["{uuids_list}"]
"""
if same_type_only:
@@ -695,13 +697,13 @@ class Neo4jClient(GraphClient):
)
cypher_query += """
- RETURN n.uuid as uuid, n.name as name, labels(n) as labels, n.description as description,
+ RETURN n['uuid'] as uuid, n['name'] as name, labels(n) as labels, n['description'] as description,
properties(n) as properties,
- n.polarity as polarity, n.happened_at as happened_at, n.last_updated as last_updated,
- n.observations as observations, n.metadata as metadata, r AS rel,
+ n['polarity'] as polarity, n['happened_at'] as happened_at, n['last_updated'] as last_updated,
+ n['observations'] as observations, n['metadata'] as metadata, r AS rel,
CASE WHEN startNode(r) = n THEN 'out' ELSE 'in' END AS direction,
- type(r) AS rel_type, r.description AS rel_description, properties(r) AS rel_properties, r.flow_key as rel_flowkey, r.uuid as rel_uuid,
- c.uuid AS c_uuid, c.name AS c_name, labels(c) AS c_labels, c.description AS c_description, properties(c) AS c_properties
+ type(r) AS rel_type, r['description'] AS rel_description, properties(r) AS rel_properties, r['flow_key'] as rel_flowkey, r['uuid'] as rel_uuid,
+ c['uuid'] AS c_uuid, c['name'] AS c_name, labels(c) AS c_labels, c['description'] AS c_description, properties(c) AS c_properties
"""
if limit:
cypher_query += f" LIMIT {limit}"
@@ -753,12 +755,12 @@ class Neo4jClient(GraphClient):
b_uuids_str = ",".join([f'"{nid}"' for nid in b_uuids])
cypher_query = f"""
MATCH (n)-[r]-(m)
- WHERE n.uuid = '{a_uuid}' AND m.uuid IN [{b_uuids_str}]
+ WHERE n['uuid'] = '{a_uuid}' AND m['uuid'] IN [{b_uuids_str}]
RETURN
- n.uuid as n_uuid, n.name as n_name, labels(n) as n_labels,
- n.description as n_description, properties(n) as n_properties,
- m.uuid as m_uuid, m.name as m_name, labels(m) as m_labels,
- m.description as m_description, properties(m) as m_properties, r as rel
+ n['uuid'] as n_uuid, n['name'] as n_name, labels(n) as n_labels,
+ n['description'] as n_description, properties(n) as n_properties,
+ m['uuid'] as m_uuid, m['name'] as m_name, labels(m) as m_labels,
+ m['description'] as m_description, properties(m) as m_properties, r as rel
"""
self.ensure_database(brain_id)
result = self.driver.execute_query(cypher_query, database_=brain_id)
@@ -841,18 +843,18 @@ class Neo4jClient(GraphClient):
labels_str = f"AND ANY(l IN labels(m) WHERE l IN [{labels_list}])"
identification_str = ""
if node:
- identification_str = f"WHERE n.uuid = '{node.uuid}'"
+ identification_str = f"WHERE n['uuid'] = '{node.uuid}'"
elif uuids:
uuids_str = ",".join([f'"{uuid}"' for uuid in uuids])
- identification_str = f"WHERE n.uuid IN [{uuids_str}]"
+ identification_str = f"WHERE n['uuid'] IN [{uuids_str}]"
cypher_query = f"""
MATCH (n)-[r]-(m)
{identification_str}
{labels_str}
RETURN
- m.uuid as uuid, m.name as name, labels(m) as labels, m.description as description, properties(m) as properties,
- r as rel, type(r) as rel_type, r.description as rel_description,
- n.uuid as n_uuid, n.name as n_name, labels(n) as n_labels, n.description as n_description, properties(n) as n_properties,
+ m['uuid'] as uuid, m['name'] as name, labels(m) as labels, m['description'] as description, properties(m) as properties,
+ r as rel, type(r) as rel_type, r['description'] as rel_description,
+ n['uuid'] as n_uuid, n['name'] as n_name, labels(n) as n_labels, n['description'] as n_description, properties(n) as n_properties,
CASE WHEN startNode(r) = n THEN 'out' ELSE 'in' END AS direction
"""
self.ensure_database(brain_id)
@@ -918,31 +920,31 @@ class Neo4jClient(GraphClient):
)
if relationship_uuids:
filters.append(
- "r.uuid IN [" + ",".join(f"'{u}'" for u in relationship_uuids) + "]"
+ "r['uuid'] IN [" + ",".join(f"'{u}'" for u in relationship_uuids) + "]"
)
if query_text:
if query_search_target == "all":
filters.append(
- f"(toLower(coalesce(n.name, n.name, '')) CONTAINS toLower('{query_text}') OR "
- f"toLower(coalesce(m.name, m.name, '')) CONTAINS toLower('{query_text}') OR "
- f"toLower(coalesce(r.description, r.description, '')) CONTAINS toLower('{query_text}'))"
+ f"(toLower(coalesce(n['name'], n['name'], '')) CONTAINS toLower('{query_text}') OR "
+ f"toLower(coalesce(m['name'], m['name'], '')) CONTAINS toLower('{query_text}') OR "
+ f"toLower(coalesce(r['description'], r['description'], '')) CONTAINS toLower('{query_text}'))"
)
elif query_search_target == "node_name":
- filters.append(f"toLower(n.name) CONTAINS toLower('{query_text}')")
+ filters.append(f"toLower(n['name']) CONTAINS toLower('{query_text}')")
elif query_search_target == "relationship_description":
filters.append(
- f"toLower(r.description) CONTAINS toLower('{query_text}')"
+ f"toLower(r['description']) CONTAINS toLower('{query_text}')"
)
elif query_search_target == "relationship_name":
- filters.append(f"toLower(r.name) CONTAINS toLower('{query_text}')")
+ filters.append(f"toLower(r['name']) CONTAINS toLower('{query_text}')")
cypher_query = f"""
MATCH (n)-[r]->(m)
{"WHERE " + " AND ".join(filters) if filters else ""}
- RETURN n.uuid AS n_uuid, n.name AS n_name, labels(n) AS n_labels,
- n.description AS n_description, properties(n) AS n_properties,
- r AS rel, type(r) AS rel_type, r.description AS rel_description,
- m.uuid AS m_uuid, m.name AS m_name, labels(m) AS m_labels,
- m.description AS m_description, properties(m) AS m_properties
+ RETURN n['uuid'] AS n_uuid, n['name'] AS n_name, labels(n) AS n_labels,
+ n['description'] AS n_description, properties(n) AS n_properties,
+ r AS rel, type(r) AS rel_type, r['description'] AS rel_description,
+ m['uuid'] AS m_uuid, m['name'] AS m_name, labels(m) AS m_labels,
+ m['description'] AS m_description, properties(m) AS m_properties
SKIP {skip}
LIMIT {limit}
"""
@@ -1062,18 +1064,18 @@ class Neo4jClient(GraphClient):
+ "])"
)
if node_uuids:
- filters.append(f"n.uuid IN [{','.join(node_uuids)}]")
+ filters.append(f"n['uuid'] IN [{','.join(node_uuids)}]")
if query_text:
filters.append(
- f"(toLower(coalesce(n.name, n.name, '')) CONTAINS toLower({self._format_value(query_text)}))"
+ f"(toLower(coalesce(n['name'], n['name'], '')) CONTAINS toLower({self._format_value(query_text)}))"
)
cypher_query = f"""
MATCH (n)
{"WHERE " + " AND ".join(filters) if filters else ""}
- RETURN n.uuid as uuid, n.name as name, labels(n) as labels, n.description as description,
+ RETURN n['uuid'] as uuid, n['name'] as name, labels(n) as labels, n['description'] as description,
properties(n) as properties,
- n.polarity as polarity, n.happened_at as happened_at, n.last_updated as last_updated,
- n.observations as observations, n.metadata as metadata
+ n['polarity'] as polarity, n['happened_at'] as happened_at, n['last_updated'] as last_updated,
+ n['observations'] as observations, n['metadata'] as metadata
SKIP {skip}
LIMIT {limit}
"""
@@ -1128,13 +1130,13 @@ class Neo4jClient(GraphClient):
Deprecate a relationship from the graph.
"""
cypher_query = f"""
- MATCH (a:{":".join(self._clean_labels(subject.labels))}) WHERE a.name = '{subject.name}'
- MATCH (b:{":".join(self._clean_labels(object.labels))}) WHERE b.name = '{object.name}'
+ MATCH (a:{":".join(self._clean_labels(subject.labels))}) WHERE a['name'] = '{subject.name}'
+ MATCH (b:{":".join(self._clean_labels(object.labels))}) WHERE b['name'] = '{object.name}'
MATCH (a)-[r:{":".join(self._clean_labels([predicate.name]))}]->(b)
- SET r.deprecated = true
- RETURN a.uuid as a_uuid, a.name as a_name, labels(a) as a_labels, a.description as a_description, properties(a) as a_properties,
- b.uuid as b_uuid, b.name as b_name, labels(b) as b_labels, b.description as b_description, properties(b) as b_properties,
- r.uuid as r_uuid, type(r) as r_type, r.description as r_description, properties(r) as r_properties
+ SET r['deprecated'] = true
+ RETURN a['uuid'] as a_uuid, a['name'] as a_name, labels(a) as a_labels, a['description'] as a_description, properties(a) as a_properties,
+ b['uuid'] as b_uuid, b['name'] as b_name, labels(b) as b_labels, b['description'] as b_description, properties(b) as b_properties,
+ r['uuid'] as r_uuid, type(r) as r_type, r['description'] as r_description, properties(r) as r_properties
"""
self.ensure_database(brain_id)
result = self.driver.execute_query(cypher_query, database_=brain_id)
@@ -1189,13 +1191,15 @@ class Neo4jClient(GraphClient):
property_set_operations = []
for property, value in new_properties.items():
cypher_key = self._format_property_key(property)
+ key_str = cypher_key.strip("`")
formatted_value = self._format_value(value)
- property_set_operations.append(f"t.{cypher_key} = {formatted_value}")
+ property_set_operations.append(f"t['{key_str}'] = {formatted_value}")
property_remove_operations = []
for property in properties_to_remove:
cypher_key = self._format_property_key(property)
- property_remove_operations.append(f"t.{cypher_key}")
+ key_str = cypher_key.strip("`")
+ property_remove_operations.append(f"t['{key_str}']")
properties_set_op = (
f"SET {', '.join(property_set_operations)}"
@@ -1210,17 +1214,17 @@ class Neo4jClient(GraphClient):
if updating == "node":
cypher_query = f"""
- MATCH (t) WHERE t.uuid = $uuid
+ MATCH (t) WHERE t['uuid'] = $uuid
{properties_set_op}
{properties_remove_op}
- RETURN t.uuid as uuid, t.name as name, labels(t) as labels, t.description as description, properties(t) as properties
+ RETURN t['uuid'] as uuid, t['name'] as name, labels(t) as labels, t['description'] as description, properties(t) as properties
"""
elif updating == "relationship":
cypher_query = f"""
- MATCH ()-[t]->() WHERE t.uuid = $uuid
+ MATCH ()-[t]->() WHERE t['uuid'] = $uuid
{properties_set_op}
{properties_remove_op}
- RETURN t, type(t) AS rel_type, t.description AS rel_description, properties(t) as properties
+ RETURN t, type(t) AS rel_type, t['description'] AS rel_description, properties(t) as properties
"""
self.ensure_database(brain_id)
@@ -1334,10 +1338,12 @@ class Neo4jClient(GraphClient):
return None
if new_name:
- operations.append(f"n.name = {self._format_value(new_name)}")
+ operations.append(f"n['name'] = {self._format_value(new_name)}")
if new_description:
- operations.append(f"n.description = {self._format_value(new_description)}")
+ operations.append(
+ f"n['description'] = {self._format_value(new_description)}"
+ )
if new_properties and existing_node:
existing_properties = existing_node.properties or {}
@@ -1349,21 +1355,22 @@ class Neo4jClient(GraphClient):
property_key not in existing_properties
or existing_value != new_value
):
- cypher_key = self._format_property_key(property_key)
+ key_str = self._clean_property_key(property_key)
formatted_value = self._format_value(new_value)
- operations.append(f"n.{cypher_key} = {formatted_value}")
+ operations.append(f"n['{key_str}'] = {formatted_value}")
elif new_properties:
for property_key, value in new_properties.items():
- cypher_key = self._format_property_key(property_key)
+ key_str = self._clean_property_key(property_key)
formatted_value = self._format_value(value)
- operations.append(f"n.{cypher_key} = {formatted_value}")
+ operations.append(f"n['{key_str}'] = {formatted_value}")
set_clause = f"SET {', '.join(operations)}" if operations else ""
remove_clause = ""
if properties_to_remove:
remove_operations = [
- f"n.{self._format_property_key(prop)}" for prop in properties_to_remove
+ f"n['{self._clean_property_key(prop)}']"
+ for prop in properties_to_remove
]
remove_clause = f"REMOVE {', '.join(remove_operations)}"
@@ -1386,12 +1393,12 @@ class Neo4jClient(GraphClient):
cypher_query = f"""
MATCH (n)
- WHERE n.uuid = $uuid
+ WHERE n['uuid'] = $uuid
{set_clause}
{remove_clause}
{labels_clause}
- RETURN n.uuid as uuid, n.name as name, labels(n) as labels,
- n.description as description, properties(n) as properties
+ RETURN n['uuid'] as uuid, n['name'] as name, labels(n) as labels,
+ n['description'] as description, properties(n) as properties
"""
self.ensure_database(brain_id)
@@ -1496,8 +1503,8 @@ class Neo4jClient(GraphClient):
"""
cypher_query = f"""
MATCH (n:{":".join(self._clean_labels(labels))})
- WHERE n.name = $name
- AND n.uuid = $uuid
+ WHERE n['name'] = $name
+ AND n['uuid'] = $uuid
RETURN n
"""
self.ensure_database(brain_id)
@@ -1554,17 +1561,17 @@ class Neo4jClient(GraphClient):
cypher_query = """
MATCH (n)-[r]-(m)
- WHERE n.uuid = $uuid
+ WHERE n['uuid'] = $uuid
RETURN
r as rel,
type(r) as rel_type,
- r.description as rel_description,
+ r['description'] as rel_description,
properties(r) as rel_properties,
CASE WHEN startNode(r) = n THEN 'out' ELSE 'in' END AS direction,
- m.uuid as m_uuid,
- m.name as m_name,
+ m['uuid'] as m_uuid,
+ m['name'] as m_name,
labels(m) as m_labels,
- m.description as m_description,
+ m['description'] as m_description,
properties(m) as m_properties
"""
@@ -1610,62 +1617,81 @@ class Neo4jClient(GraphClient):
return neighbors
- def get_next_by_flow_key(
- self, predicate_uuid: str, flow_key: str, brain_id: str
+ def get_nexts_by_flow_key(
+ self, predicates: list[PredicateWithFlowKey], brain_id: str
) -> List[Tuple[Node, Predicate, Node]]:
"""
- Finds subsequent nodes in a flow that follow a relationship identified by a predicate UUID and share the given flow key.
+ Retrieve the next connected node tuple(s) for a relationship identified by a flow key, grouped by the predicate UUID.
Parameters:
- predicate_uuid (str): UUID of the reference relationship whose adjacent segment is the starting point.
- flow_key (str): Flow key used to match the subsequent relationship.
+ predicates (list[PredicateWithFlowKey]): A list of predicates with their flow keys.
brain_id (str): Database name (brain) to execute the query against.
Returns:
- List[Tuple[Node, Predicate, Node]]: A list of tuples each containing the middle node, the matching relationship (predicate) that has the flow_key, and the connected target node. Each tuple represents a directed hop from the middle node through the matched predicate to the target node; the predicate includes its direction and properties.
+ Dict[str, List[Tuple[Node, Predicate, Node]]]: A dictionary mapping predicate UUIDs to lists of (subject node, predicate, object node) tuples that are the next nodes matching the provided flow key; empty dictionary if none are found for any predicate UUID.
"""
- cypher_query = f"""
- MATCH ()-[r]-(m)-[r2]-(b)
- WHERE r.uuid = $predicate_uuid
- AND r2.flow_key = $flow_key
- RETURN
- m.uuid as m_uuid, m.name as m_name, labels(m) as m_labels,
- type(r2) as r2_type, r2.description as r2_description, properties(r2) as r2_properties,
- CASE WHEN startNode(r2) = m THEN 'out' ELSE 'in' END AS r2_direction,
- b.uuid as b_uuid, b.name as b_name, labels(b) as b_labels, b.description as b_description, properties(b) as b_properties
- """
- self.ensure_database(brain_id)
- result = self.driver.execute_query(
- cypher_query,
- parameters_={
- "predicate_uuid": predicate_uuid,
- "flow_key": flow_key,
- },
- database_=brain_id,
- )
- return [
- (
- Node(
- uuid=record.get("m_uuid", "") or "",
- name=record.get("m_name", "") or "",
- labels=record.get("m_labels", []) or [],
- ),
- Predicate(
- name=record.get("r2_type", "") or "",
- description=record.get("r2_description", "") or "",
- direction=record.get("r2_direction", "neutral"),
- properties=record.get("r2_properties", {}) or {},
- ),
- Node(
- uuid=record.get("b_uuid", "") or "",
- name=record.get("b_name", "") or "",
- labels=record.get("b_labels", []) or [],
- description=record.get("b_description", "") or "",
- properties=record.get("b_properties", {}) or {},
- ),
+ res = {}
+ for predicate in predicates:
+ cypher_query = f"""
+ MATCH ()-[r]-(m)-[r2]-(b)
+ WHERE r['uuid'] = $predicate_uuid
+ AND r2['flow_key'] = $flow_key
+ RETURN
+ m['uuid'] as m_uuid, m['name'] as m_name, labels(m) as m_labels, m['description'] as m_description, properties(m) as m_properties, m['polarity'] as m_polarity, m['metadata'] as m_metadata, m['happened_at'] as m_happened_at, m['last_updated'] as m_last_updated, m['observations'] as m_observations,
+ r2['uuid'] as r2_uuid, type(r2) as r2_type, r2['description'] as r2_description, properties(r2) as r2_properties, r2['flow_key'] as r2_flow_key, r2['last_updated'] as r2_last_updated, r2['observations'] as r2_observations, r2['amount'] as r2_amount,
+ CASE WHEN startNode(r2) = m THEN 'out' ELSE 'in' END AS r2_direction,
+ b['uuid'] as b_uuid, b['name'] as b_name, labels(b) as b_labels, b['description'] as b_description, properties(b) as b_properties, b['polarity'] as b_polarity, b['metadata'] as b_metadata, b['happened_at'] as b_happened_at, b['last_updated'] as b_last_updated, b['observations'] as b_observations
+ """
+ self.ensure_database(brain_id)
+ result = self.driver.execute_query(
+ cypher_query,
+ parameters_={
+ "predicate_uuid": predicate["predicate_uuid"],
+ "flow_key": predicate["flow_key"],
+ },
+ database_=brain_id,
)
- for record in result.records
- ]
+ res[predicate["predicate_uuid"]] = [
+ (
+ Node(
+ uuid=record.get("m_uuid", "") or "",
+ name=record.get("m_name", "") or "",
+ labels=record.get("m_labels", []) or [],
+ description=record.get("m_description", "") or "",
+ properties=record.get("m_properties", {}) or {},
+ polarity=record.get("m_polarity", "neutral"),
+ metadata=record.get("m_metadata", {}) or {},
+ happened_at=record.get("m_happened_at", "") or "",
+ last_updated=record.get("m_last_updated", "") or "",
+ observations=record.get("m_observations", []) or [],
+ ),
+ Predicate(
+ uuid=record.get("r2_uuid", "") or "",
+ name=record.get("r2_type", "") or "",
+ description=record.get("r2_description", "") or "",
+ direction=record.get("r2_direction", "neutral"),
+ properties=record.get("r2_properties", {}) or {},
+ flow_key=record.get("r2_flow_key", "") or "",
+ last_updated=record.get("r2_last_updated", "") or "",
+ observations=record.get("r2_observations", []) or [],
+ amount=record.get("r2_amount"),
+ ),
+ Node(
+ uuid=record.get("b_uuid", "") or "",
+ name=record.get("b_name", "") or "",
+ labels=record.get("b_labels", []) or [],
+ description=record.get("b_description", "") or "",
+ properties=record.get("b_properties", {}) or {},
+ polarity=record.get("b_polarity", "neutral"),
+ metadata=record.get("b_metadata", {}) or {},
+ happened_at=record.get("b_happened_at", "") or "",
+ last_updated=record.get("b_last_updated", "") or "",
+ observations=record.get("b_observations", []) or [],
+ ),
+ )
+ for record in result.records
+ ]
+ return res
def get_triples_by_uuid(
self, uuids: list[str], brain_id: str
@@ -1674,11 +1700,11 @@ class Neo4jClient(GraphClient):
Get triples by its UUID.
"""
cypher_query = f"""
- MATCH (n)-[r]-(m) WHERE r.uuid IN [{",".join([f'"{uuid}"' for uuid in uuids])}]
+ MATCH (n)-[r]-(m) WHERE r['uuid'] IN [{",".join([f'"{uuid}"' for uuid in uuids])}]
RETURN
- n.uuid as n_uuid, n.name as n_name, labels(n) as n_labels, n.description as n_description, properties(n) as n_properties,
- r.uuid as r_uuid, type(r) as r_type, r.description as r_description, properties(r) as r_properties,
- m.uuid as m_uuid, m.name as m_name, labels(m) as m_labels, m.description as m_description, properties(m) as m_properties
+ n['uuid'] as n_uuid, n['name'] as n_name, labels(n) as n_labels, n['description'] as n_description, properties(n) as n_properties,
+ r['uuid'] as r_uuid, type(r) as r_type, r['description'] as r_description, properties(r) as r_properties,
+ m['uuid'] as m_uuid, m['name'] as m_name, labels(m) as m_labels, m['description'] as m_description, properties(m) as m_properties
"""
self.ensure_database(brain_id)
result = self.driver.execute_query(
@@ -1716,18 +1742,18 @@ class Neo4jClient(GraphClient):
Remove nodes from the graph.
"""
cypher_query = f"""
- MATCH (n) WHERE n.uuid IN [{",".join([f'"{uuid}"' for uuid in uuids])}]
+ MATCH (n) WHERE n['uuid'] IN [{",".join([f'"{uuid}"' for uuid in uuids])}]
WITH n, {{
- uuid: n.uuid,
- name: n.name,
+ uuid: n['uuid'],
+ name: n['name'],
labels: labels(n),
- description: n.description,
+ description: n['description'],
properties: properties(n),
- polarity: n.polarity,
- metadata: n.metadata,
- happened_at: n.happened_at,
- last_updated: n.last_updated,
- observations: n.observations
+ polarity: n['polarity'],
+ metadata: n['metadata'],
+ happened_at: n['happened_at'],
+ last_updated: n['last_updated'],
+ observations: n['observations']
}} AS node
DELETE n
RETURN node
@@ -1759,14 +1785,14 @@ class Neo4jClient(GraphClient):
else:
by_tip_tail.append((tail, pred, head))
with_fields = """
- n.uuid AS n_uuid, n.name AS n_name, labels(n) AS n_labels, n.description AS n_description, properties(n) AS n_properties,
- r.uuid AS r_uuid, type(r) AS r_type, r.description AS r_description, properties(r) AS r_properties,
- m.uuid AS m_uuid, m.name AS m_name, labels(m) AS m_labels, m.description AS m_description, properties(m) AS m_properties
+ n['uuid'] AS n_uuid, n['name'] AS n_name, labels(n) AS n_labels, n['description'] AS n_description, properties(n) AS n_properties,
+ r['uuid'] AS r_uuid, type(r) AS r_type, r['description'] AS r_description, properties(r) AS r_properties,
+ m['uuid'] AS m_uuid, m['name'] AS m_name, labels(m) AS m_labels, m['description'] AS m_description, properties(m) AS m_properties
"""
return_list = "n_uuid, n_name, n_labels, n_description, n_properties, r_uuid, r_type, r_description, r_properties, m_uuid, m_name, m_labels, m_description, m_properties"
if by_rel_uuid:
cypher = f"""
- MATCH (n)-[r]-(m) WHERE r.uuid IN [{",".join([self._format_value(u) for u in by_rel_uuid])}]
+ MATCH (n)-[r]-(m) WHERE r['uuid'] IN [{",".join([self._format_value(u) for u in by_rel_uuid])}]
WITH n, r, m, {with_fields.strip()}
DELETE r
RETURN {return_list}
@@ -1824,14 +1850,16 @@ class Neo4jClient(GraphClient):
if not node:
return f"({alias})"
if node.get("uuid"):
- return f"({alias}) WHERE {alias}.uuid = {self._format_value(node['uuid'])}"
+ return (
+ f"({alias}) WHERE {alias}['uuid'] = {self._format_value(node['uuid'])}"
+ )
labels = node.get("labels") or []
name = node.get("name") or ""
if labels:
labels_part = ":".join(self._clean_labels(labels))
- return f"({alias}:{labels_part}) WHERE {alias}.name = {self._format_value(name)}"
+ return f"({alias}:{labels_part}) WHERE {alias}['name'] = {self._format_value(name)}"
if name:
- return f"({alias}) WHERE {alias}.name = {self._format_value(name)}"
+ return f"({alias}) WHERE {alias}['name'] = {self._format_value(name)}"
return f"({alias})"
def list_relationships(
@@ -1841,10 +1869,10 @@ class Neo4jClient(GraphClient):
List the relationships between the subject and object.
"""
cypher_query = f"""
- MATCH (n)-[r]-(m) WHERE n.uuid = {self._format_value(subject)} AND m.uuid = {self._format_value(object)}
- RETURN n.uuid as n_uuid, n.name as n_name, labels(n) as n_labels, n.description as n_description, properties(n) as n_properties, n.polarity as n_polarity, n.metadata as n_metadata, n.happened_at as n_happened_at, n.last_updated as n_last_updated, n.observations as n_observations,
- r.uuid as r_uuid, type(r) as r_type, r.description as r_description, properties(r) as r_properties, r.flow_key as r_flow_key, r.last_updated as r_last_updated, r.observations as r_observations, r.amount as r_amount,
- m.uuid as m_uuid, m.name as m_name, labels(m) as m_labels, m.description as m_description, properties(m) as m_properties, m.polarity as m_polarity, m.metadata as m_metadata, m.happened_at as m_happened_at, m.last_updated as m_last_updated, m.observations as m_observations
+ MATCH (n)-[r]-(m) WHERE n['uuid'] = {self._format_value(subject)} AND m['uuid'] = {self._format_value(object)}
+ RETURN n['uuid'] as n_uuid, n['name'] as n_name, labels(n) as n_labels, n['description'] as n_description, properties(n) as n_properties, n['polarity'] as n_polarity, n['metadata'] as n_metadata, n['happened_at'] as n_happened_at, n['last_updated'] as n_last_updated, n['observations'] as n_observations,
+ r['uuid'] as r_uuid, type(r) as r_type, r['description'] as r_description, properties(r) as r_properties, r['flow_key'] as r_flow_key, r['last_updated'] as r_last_updated, r['observations'] as r_observations, r['amount'] as r_amount,
+ m['uuid'] as m_uuid, m['name'] as m_name, labels(m) as m_labels, m['description'] as m_description, properties(m) as m_properties, m['polarity'] as m_polarity, m['metadata'] as m_metadata, m['happened_at'] as m_happened_at, m['last_updated'] as m_last_updated, m['observations'] as m_observations
"""
self.ensure_database(brain_id)
result = self.driver.execute_query(cypher_query, database_=brain_id)
diff --git a/src/services/api/constants/requests.py b/src/services/api/constants/requests.py
index ef1cb16..d32a145 100644
--- a/src/services/api/constants/requests.py
+++ b/src/services/api/constants/requests.py
@@ -140,6 +140,9 @@ class RetrievedNeighborNode(BaseModel):
neighbor: Node
relationship: Predicate
most_common: Node
+ similarity_score: float = Field(
+ 0.0, description="The similarity score of the neighbor to the main node."
+ )
class RetrieveNeighborsRequestResponse(BaseModel):
@@ -261,6 +264,8 @@ class GetEntitySibilingsResponse(BaseModel):
target_node: Node
synergies: List[EntitySynergy]
+ anchors: List[Node]
+ potential_anchors: List[Node]
class GetEntityStatusResponse(BaseModel):
diff --git a/src/services/api/controllers/entities.py b/src/services/api/controllers/entities.py
index 0991315..deaaf9f 100644
--- a/src/services/api/controllers/entities.py
+++ b/src/services/api/controllers/entities.py
@@ -4,7 +4,7 @@ Project: controllers
Created Date: Sunday January 18th 2026
Author: Christian Nonis <[email protected]>
-----
-Last Modified: Sunday January 18th 2026 9:38:31 pm
+Last Modified: Thursday January 29th 2026 8:43:59 pm
Modified By: Christian Nonis <[email protected]>
-----
"""
@@ -29,13 +29,13 @@ async def get_entity_info(
) -> GetEntityInfoResponse:
"""
Retrieve matching event paths for a target and query up to a specified traversal depth.
-
+
Parameters:
target (str): The entity identifier or text to locate.
query (str): The query text used to find relevant event matches.
max_depth (int): Maximum path traversal depth to consider when retrieving matches.
brain_id (str): Brain/workspace identifier to scope the retrieval.
-
+
Returns:
GetEntityInfoResponse: Contains the located target node (`target_node`) and the retrieved paths (`path`).
"""
@@ -50,12 +50,12 @@ async def get_entity_context(
) -> GetEntityContextResponse:
"""
Retrieve contextual information for the specified entity target.
-
+
Parameters:
target (str): The entity identifier or text to retrieve context for.
context_depth (int): Maximum graph depth (number of hops) to include in the neighborhood.
brain_id (str): Identifier of the brain/workspace to query.
-
+
Returns:
GetEntityContextResponse: Response with the following fields:
target_node: The node representing the target entity.
@@ -82,18 +82,22 @@ async def get_entity_sibilings(
) -> GetEntitySibilingsResponse:
"""
Retrieve sibling entities (synergies) for a target entity.
-
+
Parameters:
polarity (Literal["same", "opposite"]): Which polarity of siblings to return — "same" for similar entities, "opposite" for contrasted entities.
-
+
Returns:
GetEntitySibilingsResponse: Object containing the resolved target node and its list of synergies.
"""
entity_sibilings = EntitySinergyRetriever(brain_id)
- target_node, synergies = entity_sibilings.retrieve_sibilings(target, polarity)
+ target_node, synergies, seed_nodes, potential_anchors = (
+ entity_sibilings.retrieve_sibilings(target, polarity)
+ )
return GetEntitySibilingsResponse(
target_node=target_node,
synergies=synergies,
+ anchors=seed_nodes,
+ potential_anchors=potential_anchors,
)
@@ -104,12 +108,12 @@ async def get_entity_status(
) -> GetEntityStatusResponse:
"""
Retrieve status information for an entity matching the provided target text.
-
+
Parameters:
target (str): Text used to locate the entity.
types (List[str]): Optional list of node label types to filter matches; if provided, the first matching node whose labels intersect `types` is chosen.
brain_id (str): Identifier of the brain/workspace to query.
-
+
Returns:
GetEntityStatusResponse: Response containing the matched node (or `None` if not found), `exists` indicating presence, `has_relationships` indicating whether the node has neighbors, `relationships` listing neighbor tuples, and `observations` associated with the node. When no matching node is found, `exists` is `False` and `relationships` and `observations` are empty.
"""
@@ -152,4 +156,4 @@ async def get_entity_status(
has_relationships=len(rel_tuples[target_node.uuid]) > 0,
relationships=rel_tuples[target_node.uuid],
observations=observations,
- )
\ No newline at end of file
+ )