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.

Merge branch 'main' into dev

Christian4110bf98eb85
diff --cc src/adapters/data.py
index 9d1a9d8,1bb6bdf..d8340d9
--- a/src/adapters/data.py
+++ b/src/adapters/data.py
@@@ -137,66 -146,17 +146,73 @@@ class DataAdapter
"""
Get a list of observations.
"""
- return self.data.get_observations_list(brain_id=brain_id, limit=limit, skip=skip, resource_id=resource_id, labels=labels, query_text=query_text)
-
+ return self.data.get_observations_list(
+ brain_id=brain_id,
+ limit=limit,
+ skip=skip,
+ resource_id=resource_id,
+ labels=labels,
+ query_text=query_text,
+ )
+
def get_observation_labels(self, brain_id: str = "default") -> list[str]:
"""
- Get all unique labels from observations.
+ Retrieve all unique observation labels for the specified brain.
+
+ Parameters:
+ brain_id (str): Identifier of the brain to query labels from.
+
+ Returns:
+ list[str]: All unique labels present in observations for the specified brain.
"""
return self.data.get_observation_labels(brain_id=brain_id)
+
+ def get_changelog_by_id(
+ self, id: str, brain_id: str = "default"
+ ) -> KGChanges:
+ """
+ Retrieve a changelog entry by its identifier.
+
+ Parameters:
+ id (str): Identifier of the changelog entry to retrieve.
+ brain_id (str): Brain namespace key to query; defaults to "default".
+
+ Returns:
+ KGChanges: The changelog entry matching the given `id`.
+ """
+ return self.data.get_changelog_by_id(id=id, brain_id=brain_id)
+
+ def get_changelogs_list(
+ self,
+ brain_id: str = "default",
+ limit: int = 10,
+ skip: int = 0,
+ types: list[str] = None,
+ query_text: str = None
+ ) -> list[KGChanges]:
+ """
+ Retrieve a paginated list of knowledge-graph changelogs for a brain.
+
+ Parameters:
+ brain_id (str): Identifier of the brain to query.
+ limit (int): Maximum number of changelogs to return.
+ skip (int): Number of changelogs to skip (offset).
+ types (list[str] | None): If provided, restrict results to these changelog types.
+ query_text (str | None): If provided, filter changelogs by matching text.
+
+ Returns:
+ list[KGChanges]: Changelogs matching the filters and pagination parameters.
+ """
+ return self.data.get_changelogs_list(brain_id=brain_id, limit=limit, skip=skip, types=types, query_text=query_text)
+
+ def get_changelog_types(self, brain_id: str = "default") -> list[str]:
+ """
+ Retrieve distinct changelog types for a brain.
+
+ Parameters:
+ brain_id (str): Identifier of the brain to query; defaults to "default".
+
+ Returns:
+ list[str]: List of changelog type names.
+ """
- return self.data.get_changelog_types(brain_id=brain_id)
++ return self.data.get_changelog_types(brain_id=brain_id)
diff --cc src/adapters/graph.py
index 725c6d5,9ceae6f..e800bf3
--- a/src/adapters/graph.py
+++ b/src/adapters/graph.py
@@@ -286,70 -284,153 +297,217 @@@ class GraphAdapter
return self.graph.update_properties(
uuid, updating, brain_id, new_properties, properties_to_remove
)
+
+ def get_graph_relationship_types(self, brain_id: str = "default") -> list[str]:
+ """
+ Retrieve all relationship type names present in the graph.
+
+ Parameters:
+ brain_id (str): Identifier of the graph (brain) to query. Defaults to "default".
+
+ Returns:
+ list[str]: List of unique relationship type names found in the graph.
+ """
+ return self.graph.get_graph_relationship_types(brain_id)
+
+ def get_graph_node_types(self, brain_id: str = "default") -> list[str]:
+ """
+ Get all unique node types from the graph.
+
+ @returns:
+ A list of node type names available in the graph.
+ """
+ return self.graph.get_graph_node_types(brain_id)
+
+ def get_graph_node_properties(self, brain_id: str = "default") -> list[str]:
+ """
+ Retrieve all unique node property keys present in the graph.
+
+ @returns
+ list[str]: A list of unique property key names present on nodes for the specified brain.
+ """
+ return self.graph.get_graph_node_properties(brain_id)
+
+ def update_node(
+ self,
+ uuid: str,
+ brain_id: str = "default",
+ new_name: Optional[str] = None,
+ new_description: Optional[str] = None,
+ new_labels: Optional[list[str]] = None,
+ new_properties: Optional[dict] = None,
+ properties_to_remove: Optional[list[str]] = None,
+ ) -> Node | None:
+ """
+ Update an existing node's identifying fields, labels, and properties in the graph.
+
+ Parameters:
+ uuid (str): UUID of the node to update.
+ brain_id (str): Identifier of the brain/graph where the node resides.
+ new_name (Optional[str]): New name for the node; leave None to keep the current name.
+ new_description (Optional[str]): New description for the node; leave None to keep the current description.
+ new_labels (Optional[list[str]]): New set of labels for the node; provide to replace the node's labels.
+ new_properties (Optional[dict]): Properties to add or update on the node; keys are property names and values are their new values.
+ properties_to_remove (Optional[list[str]]): List of property names to remove from the node.
+
+ Returns:
+ Node | None: The updated node if the update succeeded, or `None` if the node was not found.
+ """
+ return self.graph.update_node(
+ uuid,
+ brain_id,
+ new_name,
+ new_description,
+ new_labels,
+ new_properties,
+ properties_to_remove,
+ )
+ def get_schema(self, brain_id: str = "default") -> dict:
+ """
+ Get the schema/ontology of the graph.
+ """
+ return self.graph.get_schema(brain_id)
+
+ def get_2nd_degree_hops(
+ self,
+ from_uuids: List[str],
+ flattened: bool,
+ vector_store_adapter: VectorStoreClient,
+ brain_id: str = "default",
+ ) -> List[Tuple[Node, List[Tuple[Predicate, Node, List[Tuple[Predicate, Node]]]]]]:
+
+ def flatten_node(n):
+ return (
+ {"uuid": n.uuid, "labels": n.labels, "name": n.name} if flattened else n
+ )
+
+ def flatten_pred(p):
+ return (
+ {"uuid": p.uuid, "name": p.name, "direction": p.direction}
+ if flattened
+ else p
+ )
+
+ nodes = self.get_by_uuids(from_uuids, brain_id)
+ nodes_by_uuid = {n.uuid: n for n in nodes}
+
+ vs = vector_store_adapter.get_by_ids(
+ [n.properties["v_id"] for n in nodes], brain_id=brain_id, store="nodes"
+ )
+ averaged_vector = [
+ sum(v.embeddings[i] for v in vs) / len(vs)
+ for i in range(len(vs[0].embeddings))
+ ]
+
+ all_fd_nodes = self.get_neighbors(list(nodes_by_uuid.keys()), brain_id=brain_id)
+
+ all_fd_v_ids = [
+ fd[1].properties["v_id"] for fds in all_fd_nodes.values() for fd in fds
+ ]
+ all_fd_vs = vector_store_adapter.get_by_ids(
+ all_fd_v_ids, brain_id=brain_id, store="nodes"
+ )
+ fd_vs_by_uuid = {v.metadata["uuid"]: v for v in all_fd_vs}
+
+ all_filtered_fd_uuids = []
+ filtered_fd_by_origin = {}
+
+ for node_uuid, fd_list in all_fd_nodes.items():
+ fd_nodes_by_uuid = {fd[1].uuid: fd[1] for fd in fd_list}
+ fd_vs_with_desc = [
+ {
+ "embeddings": fd_vs_by_uuid[fd[1].uuid].embeddings,
+ "metadata": fd_vs_by_uuid[fd[1].uuid].metadata,
+ "description": (
+ fd_nodes_by_uuid.get(fd[1].uuid, {}).description
+ if fd_nodes_by_uuid.get(fd[1].uuid)
+ else None
+ ),
+ }
+ for fd in fd_list
+ if fd[1].uuid in fd_vs_by_uuid
+ ]
+ from_node = nodes_by_uuid[node_uuid]
+ filtered = reduce_list(
+ fd_vs_with_desc,
+ access_key="embeddings",
+ similarity_threshold=0.5,
+ by_vector=averaged_vector,
+ rerank={
+ "local": "description",
+ "with_": from_node.description,
+ },
+ )
+ filtered_uuids = {v["metadata"]["uuid"] for v in filtered}
+ filtered_fd_by_origin[node_uuid] = [
+ fd for fd in fd_list if fd[1].uuid in filtered_uuids
+ ]
+ all_filtered_fd_uuids.extend(filtered_uuids)
+
+ all_sd_nodes = self.get_neighbors(all_filtered_fd_uuids, brain_id=brain_id)
+
+ all_sd_v_ids = [
+ sd[1].properties["v_id"] for sds in all_sd_nodes.values() for sd in sds
+ ]
+ all_sd_vs = vector_store_adapter.get_by_ids(
+ all_sd_v_ids, brain_id=brain_id, store="nodes"
+ )
+ sd_vs_by_uuid = {v.metadata["uuid"]: v for v in all_sd_vs}
+
+ hops = []
+ exclude_set = set(from_uuids)
+
+ for from_uuid in from_uuids:
+ if from_uuid not in nodes_by_uuid:
+ continue
+ from_node = nodes_by_uuid[from_uuid]
+ node_hops = []
+
+ for fd_pred, fd_node in filtered_fd_by_origin.get(from_uuid, []):
+ sd_list = all_sd_nodes.get(fd_node.uuid, [])
+ sd_nodes_by_uuid = {sd[1].uuid: sd[1] for sd in sd_list}
+
+ sd_vs_with_desc = [
+ {
+ "embeddings": sd_vs_by_uuid[sd[1].uuid].embeddings,
+ "metadata": sd_vs_by_uuid[sd[1].uuid].metadata,
+ "description": (
+ sd_nodes_by_uuid.get(sd[1].uuid, {}).description
+ if sd_nodes_by_uuid.get(sd[1].uuid)
+ else None
+ ),
+ }
+ for sd in sd_list
+ if sd[1].uuid in sd_vs_by_uuid
+ ]
+
+ reduced = reduce_list(
+ sd_vs_with_desc,
+ access_key="embeddings",
+ similarity_threshold=0.5,
+ by_vector=averaged_vector,
+ rerank={
+ "local": "description",
+ "with_": from_node.description,
+ },
+ )
+ reduced_uuids = {v["metadata"]["uuid"] for v in reduced}
+
+ second_degree = [
+ (flatten_pred(sd[0]), flatten_node(sd[1]))
+ for sd in sd_list
+ if sd[1].uuid in reduced_uuids
+ and sd[1].uuid not in exclude_set
+ and sd[1].uuid != from_uuid
+ ]
+
+ node_hops.append(
+ (flatten_pred(fd_pred), flatten_node(fd_node), second_degree)
+ )
+
+ hops.append((flatten_node(from_node), node_hops))
+
+ return hops
+
-
-_graph_adapter = GraphAdapter()
+_graph_adapter = GraphAdapter()
diff --cc src/adapters/interfaces/graph.py
index b459542,fff1638..34da15f
--- a/src/adapters/interfaces/graph.py
+++ b/src/adapters/interfaces/graph.py
@@@ -290,68 -277,31 +293,97 @@@ class GraphClient(ABC)
raise NotImplementedError("update_properties method not implemented")
@abstractmethod
+ def get_graph_relationship_types(self, brain_id: str) -> list[str]:
+ """
+ List unique relationship types present in the specified graph.
+
+ Parameters:
+ brain_id (str): Identifier of the graph/brain to query.
+
+ Returns:
+ relationship_types (list[str]): Relationship type names present in the graph.
+ """
+ raise NotImplementedError("get_graph_relationship_types method not implemented")
+
+ @abstractmethod
+ def get_graph_node_types(self, brain_id: str) -> list[str]:
+ """
+ Return all unique node types (labels) present in the graph for the given brain.
+
+ Parameters:
+ brain_id (str): Identifier of the brain/graph to query.
+
+ Returns:
+ list[str]: A list of node type names (labels) present in the specified graph.
+ """
+ raise NotImplementedError("get_graph_node_types method not implemented")
+
+ @abstractmethod
+ def get_graph_node_properties(self, brain_id: str) -> list[str]:
+ """
+ Retrieve all unique node property keys present in the graph for the given brain.
+
+ Parameters:
+ brain_id (str): Identifier of the graph/brain to query.
+
+ Returns:
+ list[str]: Unique property key names found on nodes in the specified graph.
+ """
+ raise NotImplementedError("get_graph_node_properties method not implemented")
+
+ @abstractmethod
+ def update_node(
+ self,
+ uuid: str,
+ brain_id: str,
+ new_name: Optional[str] = None,
+ new_description: Optional[str] = None,
+ new_labels: Optional[list[str]] = None,
+ new_properties: Optional[dict] = None,
+ properties_to_remove: Optional[list[str]] = None,
+ ) -> Node | None:
+ """
+ Update a node's identifying fields, labels, and properties in the graph.
+
+ Parameters:
+ uuid (str): UUID of the node to update.
+ brain_id (str): Identifier of the graph/brain where the node resides.
+ new_name (Optional[str]): New name for the node; if omitted, name is unchanged.
+ new_description (Optional[str]): New description for the node; if omitted, description is unchanged.
+ new_labels (Optional[list[str]]): New set of labels for the node; if provided, replaces existing labels.
+ new_properties (Optional[dict]): Properties to add or update on the node; keys with values will be set or overwritten.
+ properties_to_remove (Optional[list[str]]): List of property keys to remove from the node.
+
+ Returns:
+ Node | None: The updated Node if the node was found and modified, `None` if no matching node exists.
+ """
- raise NotImplementedError("update_node method not implemented")
++ raise NotImplementedError("update_node method not implemented")
++
+ def get_schema(self, brain_id: str) -> dict:
+ """
+ Get the schema/ontology of the graph.
+ """
+ raise NotImplementedError("get_schema method not implemented")
+
+ @abstractmethod
+ def get_2nd_degree_hops(
+ self,
+ from_: List[str],
+ flattened: bool,
+ vector_store_adapter: VectorStoreClient,
+ brain_id: str,
+ ) -> Dict[str, List[Tuple[Predicate, Node, List[Tuple[Predicate, Node]]]]]:
+ """
+ Gets the 2nd degree hops for each node in a list of things to search for.
+
+ from_ is the node to start from.
+ flattened is a boolean to indicate if the result should be lightweighted (removed metadata, etc).
+ brain_id is the brain id to search in.
+
+ Returns:
+ A dictionary with the from_ string as the key and a list of tuples as the value.
+ The tuples are the node and their relationships.
+ The node is the 1st degree hop.
+ The relationships are the 2nd degree hops.
+ """
+ raise NotImplementedError("get_2nd_degree_hops not implemented")
diff --cc src/lib/mongo/client.py
index 97d819f,8dedab6..fd9b661
--- a/src/lib/mongo/client.py
+++ b/src/lib/mongo/client.py
@@@ -269,17 -270,8 +270,17 @@@ class MongoClient(DataClient)
)
for result in results
]
-
+
def get_observation_labels(self, brain_id: str) -> list[str]:
+ """
+ Return the list of unique observation labels for the specified brain, sorted lexicographically.
+
+ Parameters:
+ brain_id (str): Name/key of the brain used as the MongoDB database to query.
+
+ Returns:
+ list[str]: Sorted list of distinct label strings found in observations' metadata.labels.
+ """
collection = self.get_collection("observations", database=brain_id)
pipeline = [
{"$match": {"metadata.labels": {"$exists": True}}},
@@@ -289,109 -281,6 +290,110 @@@
]
results = collection.aggregate(pipeline)
return [result["_id"] for result in results]
+
+ def get_changelog_by_id(
+ self, id: str, brain_id: str
+ ) -> KGChanges:
+ """
+ Retrieve a changelog entry by id from the specified brain's kg_changes collection.
+
+ If a document is found, convert string values of the nested `change.type` and the top-level `type`
+ fields to the `KGChangesType` enum when present, then validate and return a `KGChanges` model.
+ Returns `None` if no matching document exists.
+
+ Parameters:
+ id (str): The changelog document id to retrieve.
+ brain_id (str): The brain (database) name where the kg_changes collection resides.
+
+ Returns:
+ KGChanges or None: The validated `KGChanges` model for the found document, or `None` if not found.
+ """
+ from src.constants.data import KGChangesType
+
+ collection = self.get_collection("kg_changes", database=brain_id)
+ result = collection.find_one({"id": id})
+ if not result:
+ return None
+
+ if "change" in result and isinstance(result["change"], dict):
+ if "type" in result["change"] and isinstance(result["change"]["type"], str):
+ result["change"]["type"] = KGChangesType(result["change"]["type"])
+
+ if "type" in result and isinstance(result["type"], str):
+ result["type"] = KGChangesType(result["type"])
+
+ return KGChanges.model_validate(result)
+
+ def get_changelogs_list(
+ self,
+ brain_id: str,
+ limit: int = 10,
+ skip: int = 0,
+ types: list[str] = None,
+ query_text: str = None
+ ) -> list[KGChanges]:
+ """
+ Retrieve changelog entries for a brain with optional type filtering and text search.
+
+ Parameters:
+ brain_id (str): Identifier of the brain (database) to query.
+ limit (int): Maximum number of changelogs to return.
+ skip (int): Number of changelogs to skip (offset).
+ types (list[str] | None): If provided, restrict results to changelogs whose top-level `type` is in this list.
+ query_text (str | None): If provided, perform a case-insensitive substring search on the `change` and `type` fields.
+
+ Returns:
+ list[KGChanges]: Changelogs validated into `KGChanges` models, sorted by `timestamp` descending. Entries that fail model validation are skipped (an error message is printed). String values in nested `change.type` and top-level `type` are converted to `KGChangesType` when applicable.
+ """
+ from src.constants.data import KGChangesType
+
+ collection = self.get_collection("kg_changes", database=brain_id)
+ query = {}
+ if types:
+ query["type"] = {"$in": types}
+
+ if query_text:
+ query["$or"] = [
+ {"change": {"$regex": query_text, "$options": "i"}},
+ {"type": {"$regex": query_text, "$options": "i"}}
+ ]
+
+ results = collection.find(query).skip(skip).limit(limit).sort("timestamp", -1)
+ changelogs = []
+ for result in results:
+ try:
+ if "change" in result and isinstance(result["change"], dict):
+ if "type" in result["change"] and isinstance(result["change"]["type"], str):
+ result["change"]["type"] = KGChangesType(result["change"]["type"])
+
+ if "type" in result and isinstance(result["type"], str):
+ result["type"] = KGChangesType(result["type"])
+
+ changelog = KGChanges.model_validate(result)
+ changelogs.append(changelog)
+ except Exception as e:
+ print(f"Error parsing changelog {result.get('id')}: {e}")
+ continue
+
+ return changelogs
+
+ def get_changelog_types(self, brain_id: str) -> list[str]:
+ """
+ Retrieve the sorted list of distinct changelog types for a brain.
+
+ Parameters:
+ brain_id (str): Identifier of the brain (database name) to query.
+
+ Returns:
+ list[str]: Changelog type strings sorted in ascending order.
+ """
+ collection = self.get_collection("kg_changes", database=brain_id)
+ pipeline = [
+ {"$group": {"_id": "$type"}},
+ {"$sort": {"_id": 1}}
+ ]
+ results = collection.aggregate(pipeline)
+ return [result["_id"] for result in results]
+
-_mongo_client = MongoClient()
+_mongo_client = MongoClient()
diff --cc src/lib/neo4j/client.py
index b1f259e,5e4a441..d27e03e
--- a/src/lib/neo4j/client.py
+++ b/src/lib/neo4j/client.py
@@@ -471,26 -504,63 +512,57 @@@ class Neo4jClient(GraphClient)
properties=result.records[0].get("properties", {}) or {},
)
- def get_graph_property_keys(self, brain_id: str) -> list[str]:
- """
- Get the property keys of the graph.
- """
- cypher_query = """
- CALL db.propertyKeys() YIELD propertyKey
- RETURN propertyKey
- """
- self.ensure_database(brain_id)
- result = self.driver.execute_query(cypher_query, database_=brain_id)
- return [record["propertyKey"] for record in result.records]
-
def get_neighbors(
- self, node: Node, limit: int, brain_id: str
- ) -> list[Tuple[Node, Predicate, Node]]:
+ self,
+ nodes: list[Node | str],
+ brain_id: str,
+ same_type_only: bool = False,
+ limit: int | None = None,
+ of_types: Optional[list[str]] = None,
+ ) -> Dict[str, List[Tuple[Predicate, Node]]]:
"""
- Get the neighbors of a node.
+ Retrieve neighbor triples for the given node where the neighbor shares at least one label with the source node.
+
+ Returns:
+ list[Tuple[Node, Predicate, Node]]: A list of tuples (neighbor_node, predicate, intermediate_node) where
+ - neighbor_node is the matched neighbor (node m),
+ - predicate describes the relationship r2 between the intermediate node and the neighbor (including direction),
+ - intermediate_node is the connector node (c) through which the neighbor is reached.
"""
+ if len(nodes) == 0:
+ return {}
+ if isinstance(nodes[0], str):
+ node_uuids = nodes
+ else:
+ node_uuids = [node.uuid for node in nodes]
+
+ uuids_list = '", "'.join(node_uuids)
cypher_query = f"""
- MATCH (n {{uuid: '{node.uuid}'}})-[r]-(c)-[r2]-(m)
- WHERE size([l IN labels(n) WHERE l IN labels(m)]) > 0
- RETURN m.uuid AS uuid, m.name AS name, labels(m) AS labels, m.description AS description, properties(m) AS properties, r2 AS rel,
- CASE WHEN startNode(r2) = c THEN 'out' ELSE 'in' END AS direction,
+ MATCH (n)-[r]-(c)
+ WHERE n.uuid IN ["{uuids_list}"]
+ """
+
+ if same_type_only:
+ cypher_query += " AND size([l IN labels(n) WHERE l IN labels(c)]) > 0"
+
+ if of_types:
+ cypher_query += (
+ " AND ANY(l IN labels(c) WHERE l IN ["
+ + ",".join(f"'{t}'" for t in self._clean_labels(of_types))
+ + "])"
+ )
+
+ cypher_query += """
+ RETURN n.uuid AS uuid, n.name AS name, labels(n) AS labels, n.description AS description, properties(n) AS properties, 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,
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}"
+
self.ensure_database(brain_id)
result = self.driver.execute_query(cypher_query, database_=brain_id)
@@@ -1035,168 -1079,41 +1093,203 @@@
direction=result.records[0].get("direction", "neutral"),
)
return None
+
+ def get_graph_relationship_types(self, brain_id: str) -> list[str]:
+ """
+ Return all relationship type names present in the specified brain (database).
+
+ Parameters:
+ brain_id (str): Target database name to query for relationship types.
+
+ Returns:
+ list[str]: A list of relationship type names found in the graph.
+ """
+ cypher_query = """
+ CALL db.relationshipTypes() YIELD relationshipType
+ RETURN relationshipType
+ """
+ self.ensure_database(brain_id)
+ result = self.driver.execute_query(cypher_query, database_=brain_id)
+ return [record["relationshipType"] for record in result.records]
+
+ def get_graph_node_types(self, brain_id: str) -> list[str]:
+ """
+ Return the set of node label types present in the specified graph database.
+
+ Parameters:
+ brain_id (str): The target database/graph identifier to query.
+
+ Returns:
+ list[str]: A list of node label strings found in the database.
+ """
+ cypher_query = """
+ CALL db.labels() YIELD label
+ RETURN label
+ """
+ self.ensure_database(brain_id)
+ result = self.driver.execute_query(cypher_query, database_=brain_id)
+ return [record["label"] for record in result.records]
+
+ def get_graph_node_properties(self, brain_id: str) -> list[str]:
+ """
+ Return all distinct node property keys present in the database, ordered alphabetically.
+
+ Returns:
+ properties (list[str]): Sorted list of distinct property key names used on nodes.
+ """
+ cypher_query = """
+ MATCH (n)
+ UNWIND keys(n) AS property
+ RETURN DISTINCT property
+ ORDER BY property
+ """
+ self.ensure_database(brain_id)
+ result = self.driver.execute_query(cypher_query, database_=brain_id)
+ return [record["property"] for record in result.records]
+
+ def update_node(
+ self,
+ uuid: str,
+ brain_id: str,
+ new_name: Optional[str] = None,
+ new_description: Optional[str] = None,
+ new_labels: Optional[list[str]] = None,
+ new_properties: Optional[dict] = None,
+ properties_to_remove: Optional[list[str]] = None,
+ ) -> Node | None:
+ """
+ Update the node identified by `uuid` with the provided name, description, labels, and property changes.
+
+ If `new_properties` is provided, only properties that are new or whose values differ from the existing node are set; existing properties not mentioned are left unchanged. If `properties_to_remove` is provided, those properties are removed. If `new_labels` is provided, existing labels are removed (if the node was loaded) and replaced with the cleaned `new_labels`. If no changes are specified, the function returns the existing node (or None if not found) without executing an update.
+
+ Parameters:
+ uuid (str): UUID of the node to update.
+ brain_id (str): Target database/brain identifier.
+ new_name (Optional[str]): New value for the node's `name` property.
+ new_description (Optional[str]): New value for the node's `description` property.
+ new_labels (Optional[list[str]]): New labels to assign to the node; labels will be cleaned and applied.
+ new_properties (Optional[dict]): Properties to add or update; only keys that are new or changed are applied when the existing node can be loaded.
+ properties_to_remove (Optional[list[str]]): Property keys to remove from the node.
+
+ Returns:
+ Node or None: The updated Node when the update succeeds, the existing Node if no changes were requested, or `None` if the node does not exist or no update occurred.
+ """
+ operations = []
+
+ existing_node = None
+ if new_properties:
+ existing_node = self.get_by_uuid(uuid, brain_id)
+ if not existing_node:
+ return None
+
+ if 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)}")
+
+ if new_properties and existing_node:
+ existing_properties = existing_node.properties or {}
+
+ for property_key, new_value in new_properties.items():
+ existing_value = existing_properties.get(property_key)
+
+ if property_key not in existing_properties or existing_value != new_value:
+ cypher_key = self._format_property_key(property_key)
+ formatted_value = self._format_value(new_value)
+ operations.append(f"n.{cypher_key} = {formatted_value}")
+ elif new_properties:
+ for property_key, value in new_properties.items():
+ cypher_key = self._format_property_key(property_key)
+ formatted_value = self._format_value(value)
+ operations.append(f"n.{cypher_key} = {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
+ ]
+ remove_clause = f"REMOVE {', '.join(remove_operations)}"
+
+ labels_clause = ""
+ if new_labels:
+ cleaned_labels = self._clean_labels(new_labels)
+ if existing_node:
+ current_labels = existing_node.labels or []
+ if current_labels:
+ cleaned_current = self._clean_labels(current_labels)
+ remove_labels = ", ".join([f"n:{label}" for label in cleaned_current])
+ labels_clause = f"REMOVE {remove_labels}\n"
+ labels_clause += f"SET n:{':'.join(cleaned_labels)}"
+
+ if not set_clause and not remove_clause and not labels_clause:
+ return existing_node if existing_node else self.get_by_uuid(uuid, brain_id)
+
+ cypher_query = f"""
+ MATCH (n)
+ 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
+ """
+
+ self.ensure_database(brain_id)
+ result = self.driver.execute_query(
+ cypher_query,
+ parameters_={"uuid": uuid},
+ database_=brain_id
+ )
+
+ if result.records:
+ return Node(
+ uuid=result.records[0].get("uuid", "") or "",
+ name=result.records[0].get("name", "") or "",
+ labels=result.records[0].get("labels", []) or [],
+ description=result.records[0].get("description", "") or "",
+ properties=result.records[0].get("properties", {}) or {},
+ )
+
+ return None
+ def get_schema(self, brain_id: str) -> dict:
+ """
+ Get the schema/ontology of the graph.
+ Returns all node labels and relationship types in JSON format.
+ """
+ self.ensure_database(brain_id)
+
+ labels_query = "CALL db.labels() YIELD label RETURN label"
+ relationships_query = (
+ "CALL db.relationshipTypes() YIELD relationshipType RETURN relationshipType"
+ )
+
+ labels_result = self.driver.execute_query(labels_query, database_=brain_id)
+ relationships_result = self.driver.execute_query(
+ relationships_query, database_=brain_id
+ )
+
+ labels = [record["label"] for record in labels_result.records]
+ relationships = [
+ record["relationshipType"] for record in relationships_result.records
+ ]
+
+ return {"labels": labels, "relationships": relationships}
+
+ def get_2nd_degree_hops(
+ self,
+ from_: List[str],
+ flattened: bool,
+ vector_store_adapter: VectorStoreClient,
+ brain_id: str,
+ ) -> Dict[str, List[Tuple[Predicate, Node, List[Tuple[Predicate, Node]]]]]:
+ return super().get_2nd_degree_hops(
+ from_, flattened, vector_store_adapter, brain_id
+ )
+
-_neo4j_client = Neo4jClient()
+_neo4j_client = Neo4jClient()
diff --cc src/services/api/routes/retrieve.py
index 94d4d59,e4ba530..2865978
--- a/src/services/api/routes/retrieve.py
+++ b/src/services/api/routes/retrieve.py
@@@ -22,8 -22,9 +22,9 @@@ from src.services.api.controllers.retri
get_relationships as retrieve_get_relationships_controller,
get_entities as retrieve_get_entities_controller,
)
+ from src.services.api.controllers.kg import get_hops as get_hops_controller
from src.services.api.controllers.retrieve import (
- retrieve_data as retrieve_data_controller,
+ retrieve_data as retrieve_data_controller
)
from src.services.api.controllers.structured_data import (
get_structured_data_by_id as get_structured_data_by_id_controller,
@@@ -262,58 -238,19 +276,72 @@@ async def get_observations_list
"""
if labels:
labels = labels.split(",")
- return await get_observations_list_controller(
- limit, skip, resource_id, labels, query_text, brain_id
- )
++
+ return await get_observations_list_controller(limit, skip, resource_id, labels, query_text, brain_id)
+
+@retrieve_router.get(path="/changelogs/types")
+async def get_changelog_types(
+ brain_id: str = "default",
+):
+ """
+ Retrieve all unique changelog types for the specified brain.
+
+ Parameters:
+ brain_id (str): Identifier of the brain to query; defaults to "default".
+
+ Returns:
+ list[str]: List of unique changelog type names.
+ """
+ return await get_changelog_types_controller(brain_id)
+
+@retrieve_router.get(path="/changelogs/{id}")
+async def get_changelog_by_id(
+ id: str,
+ brain_id: str = "default",
+):
+ """
+ Retrieve a changelog record by its identifier.
+
+ Parameters:
+ id (str): The changelog's unique identifier.
+ brain_id (str): Identifier of the brain to query; defaults to "default".
+
+ Returns:
+ The changelog record matching `id`.
+ """
+ return await get_changelog_by_id_controller(id, brain_id)
+
+@retrieve_router.get(path="/changelogs")
+async def get_changelogs_list(
+ limit: int = 10,
+ skip: int = 0,
+ types: Optional[str] = None,
+ query_text: Optional[str] = None,
+ brain_id: str = "default",
+):
+ """
+ Retrieve a paginated list of changelogs.
+
+ Parameters:
+ types (Optional[str]): Optional comma-separated changelog types to filter by; each type will be applied as a filter.
+ query_text (Optional[str]): Optional text used to filter changelogs by content or metadata.
+
+ Returns:
+ list: Changelog records matching the provided filters, constrained by `limit` and `skip`.
+ """
+ if types:
+ types = types.split(",")
- return await get_changelogs_list_controller(limit, skip, types, query_text, brain_id)
++ return await get_changelogs_list_controller(limit, skip, types, query_text, brain_id)
+
+
+ @retrieve_router.get(path="/hops")
+ async def get_hops(
+ query: str,
+ degrees: Literal[2] = 2,
+ flattened: bool = True,
+ brain_id: str = "default",
+ ): # noqa: F821
+ """
+ Get the hops in the graph for a given query.
+ """
+ return await get_hops_controller(query, degrees, flattened, brain_id)