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.
Python ai-agentsai-memoryknowledge-graphknowledge-managementknowledge-representationreccomendation-system
feat
Christianee656da46e3e
diff --git a/src/core/agents/kg_agent.py b/src/core/agents/kg_agent.pyindex 13461d8..16c48b5 100644--- a/src/core/agents/kg_agent.py+++ b/src/core/agents/kg_agent.py@@ -8,7 +8,7 @@ Modified By: the developer formerly known as Christian Nonis at <alch.infoemail@-----"""-from typing import List, Optional+from typing import Iterable, List, Optional, Unionfrom langchain.agents import create_agentfrom langchain.tools import BaseToolfrom pydantic import BaseModel@@ -204,21 +204,13 @@ class KGAgent:return responsedef retrieve_neighbors(- self, node: Node, looking_for: Optional[str], limit: int+ self, node: Node, looking_for: Optional[Union[str, Iterable[str]]], limit: int) -> RetrieveNeighborsOutputSchema:"""- Retrieve neighbors and related information for a given node using the KG agent.-- Parameters:- node (Node): The main node for which neighbors should be retrieved.- looking_for (Optional[str or Iterable[str]]): One or more reasons or search hints the agent should prioritize when selecting neighbors. When provided as a sequence, each element is treated as a separate reason.- limit (int): Maximum number of neighbor results the agent should return.-- Returns:- RetrieveNeighborsOutputSchema: The agent-produced structured neighbor information and associated metadata.+ Retrieve the neighbors of a node."""- graph_db_prop_keys = self.kg.get_graph_node_properties()+ graph_db_prop_keys = self.kg.get_graph_property_keys()graph_db_relationships = self.kg.get_graph_relationships()graph_db_entities = self.kg.get_graph_entities()@@ -245,9 +237,14 @@ class KGAgent:extra_system_prompt=extra_system_prompt_str,)+ if isinstance(looking_for, str):+ looking_for_items = [looking_for]+ else:+ looking_for_items = list(looking_for) if looking_for else []+looking_for_prompt = f"""You must look for neighbors for the main node considering this reasons:- {" ".join([f"- {reason}" for reason in looking_for])}+ {" ".join([f"- {reason}" for reason in looking_for_items])}"""_response = self.agent.invoke(@@ -267,4 +264,4 @@ class KGAgent:response = _response.get("structured_response")- return response\ No newline at end of file+ return responsediff --git a/src/lib/mongo/client.py b/src/lib/mongo/client.pyindex fd9b661..9a0ec58 100644--- a/src/lib/mongo/client.py+++ b/src/lib/mongo/client.py@@ -274,10 +274,10 @@ class MongoClient(DataClient):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."""@@ -290,110 +290,112 @@ class MongoClient(DataClient):]results = collection.aggregate(pipeline)return [result["_id"] for result in results]-- def get_changelog_by_id(- self, id: str, brain_id: str- ) -> KGChanges:++ 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,+ self,+ brain_id: str,+ limit: int = 10,+ skip: int = 0,types: list[str] = None,- query_text: 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"}}+ {"change.subject.name": {"$regex": query_text, "$options": "i"}},+ {"change.object.name": {"$regex": query_text, "$options": "i"}},+ {"change.predicate.name": {"$regex": query_text, "$options": "i"}},+ {"change.node.name": {"$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["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 changelogsdef 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}}- ]+ pipeline = [{"$group": {"_id": "$type"}}, {"$sort": {"_id": 1}}]results = collection.aggregate(pipeline)return [result["_id"] for result in results]-_mongo_client = MongoClient()\ No newline at end of file+_mongo_client = MongoClient()diff --git a/src/lib/neo4j/client.py b/src/lib/neo4j/client.pyindex d27e03e..c938e27 100644--- a/src/lib/neo4j/client.py+++ b/src/lib/neo4j/client.py@@ -429,12 +429,14 @@ class Neo4jClient(GraphClient):"""Get a node by its UUID."""- cypher_query = f"""- MATCH (n) WHERE n.uuid = '{uuid}'+ cypher_query = """+ MATCH (n) WHERE n.uuid = $uuidRETURN 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, database_=brain_id)+ result = self.driver.execute_query(+ cypher_query, parameters_={"uuid": uuid}, database_=brain_id+ )if not result.records or len(result.records) == 0:return Nonereturn Node(@@ -474,12 +476,12 @@ class Neo4jClient(GraphClient):) -> Node:"""Finds a node matching the provided identification parameters and optional entity types.-+Parameters:identification_params (IdentificationParams): Identification fields used to locate the node (model_dump is used to build WHERE clauses).brain_id (str): Target database identifier to query.entity_types (list[str], optional): Node labels to restrict the match; when provided, the search matches nodes with any of these labels.-+Returns:Node or None: The matching Node populated with uuid, name, labels, description, and properties, or `None` if no node is found."""@@ -489,19 +491,27 @@ class Neo4jClient(GraphClient):)where_clauses = []+ query_params = {}- for key, value in params_dict.items():- where_clauses.append(- f"n.{self._format_property_key(key)} = {self._format_value(value)}"- )+ for idx, (key, value) in enumerate(params_dict.items()):+ param_name = f"param_{idx}"+ where_clauses.append(f"n.{self._format_property_key(key)} = ${param_name}")+ query_params[param_name] = value++ labels_str = (+ (":" + ":".join(self._clean_labels(entity_types))) if entity_types else ""+ )+ where_str = ("WHERE " + " AND ".join(where_clauses)) if where_clauses else ""cypher_query = f"""- MATCH (n{(":" + ":".join(self._clean_labels(entity_types))) if entity_types else ""}) {("WHERE " + " AND ".join(where_clauses)) if where_clauses else ""}+ MATCH (n{labels_str}) {where_str}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, database_=brain_id)+ result = self.driver.execute_query(+ cypher_query, parameters_=query_params, database_=brain_id+ )if not result.records or len(result.records) == 0:return Nonereturn Node(@@ -522,7 +532,7 @@ class Neo4jClient(GraphClient):) -> Dict[str, List[Tuple[Predicate, 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),@@ -1023,16 +1033,16 @@ class Neo4jClient(GraphClient):) -> Node | Predicate | None:"""Update properties on a node or relationship identified by UUID.-+Sets and/or removes properties on the matched entity and returns the updated representation.-+Parameters:uuid (str): UUID of the node or relationship to update.updating (Literal["node", "relationship"]): Whether to update a node or a relationship.brain_id (str): Target database identifier.new_properties (dict): Mapping of property keys to values to set or update on the entity.properties_to_remove (list[str]): List of property keys to remove from the entity.-+Returns:Node | Predicate | None: A `Node` when a node was updated, a `Predicate` when a relationship was updated, or `None` if no matching entity was found."""@@ -1061,21 +1071,23 @@ 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"""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"""self.ensure_database(brain_id)- result = self.driver.execute_query(cypher_query, database_=brain_id)+ result = self.driver.execute_query(+ cypher_query, parameters_={"uuid": uuid}, database_=brain_id+ )if result.records:if updating == "node":@@ -1093,14 +1105,14 @@ class Neo4jClient(GraphClient):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."""@@ -1115,10 +1127,10 @@ class Neo4jClient(GraphClient):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."""@@ -1129,11 +1141,11 @@ class Neo4jClient(GraphClient):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."""@@ -1159,9 +1171,9 @@ class Neo4jClient(GraphClient):) -> 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.@@ -1170,31 +1182,34 @@ class Neo4jClient(GraphClient):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 = Noneif 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:++ 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}")@@ -1203,31 +1218,33 @@ class Neo4jClient(GraphClient):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+ 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 []+ node_for_labels = existing_node+ if not node_for_labels:+ node_for_labels = self.get_by_uuid(uuid, brain_id)+ if node_for_labels:+ current_labels = node_for_labels.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"+ remove_labels = ":".join(cleaned_current)+ labels_clause = f"REMOVE n:{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@@ -1237,14 +1254,12 @@ class Neo4jClient(GraphClient):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+ cypher_query, parameters_={"uuid": uuid}, database_=brain_id)-+if result.records:return Node(uuid=result.records[0].get("uuid", "") or "",@@ -1253,7 +1268,7 @@ class Neo4jClient(GraphClient):description=result.records[0].get("description", "") or "",properties=result.records[0].get("properties", {}) or {},)-+return Nonedef get_schema(self, brain_id: str) -> dict:@@ -1292,4 +1307,4 @@ class Neo4jClient(GraphClient):)-_neo4j_client = Neo4jClient()\ No newline at end of file+_neo4j_client = Neo4jClient()diff --git a/src/services/api/controllers/model.py b/src/services/api/controllers/model.pyindex 35a8aa0..9ae79d7 100644--- a/src/services/api/controllers/model.py+++ b/src/services/api/controllers/model.py@@ -13,6 +13,7 @@ from typing import Optionalfrom src.services.kg_agent.main import graph_adapterfrom src.constants.kg import Node, Predicate+async def add_nodes(nodes: list[dict],brain_id: str,@@ -21,31 +22,41 @@ async def add_nodes() -> list[Node] | str:"""Create and add multiple Node objects to the graph.-+Each input dict is converted into a Node (a new UUID is generated for each) and then added to the graph via the graph adapter.-+Parameters:nodes (list[dict]): List of node data dicts. Expected keys include `name`, optional `labels` (list), optional `description`, and optional `properties` (dict).brain_id (str): Identifier for the target brain/graph.identification_params (dict, optional): Parameters used to identify existing nodes for deduplication or matching; passed through to the graph adapter.metadata (dict, optional): Additional metadata forwarded to the graph adapter.-+Returns:list[Node] | str: The list of added Node objects, or a string result as returned by the graph adapter."""from src.constants.kg import Nodeimport uuid as uuid_lib-+node_objects = []for node_data in nodes:- node_objects.append(Node(- uuid=str(uuid_lib.uuid4()),- name=node_data.get("name"),- labels=node_data.get("labels", []),- description=node_data.get("description"),- properties=node_data.get("properties"),- ))-+ name = node_data.get("name")+ if not name:+ raise ValueError("Node name is required and cannot be empty")++ properties = node_data.get("properties")+ if properties is None:+ properties = {}++ node_objects.append(+ Node(+ uuid=str(uuid_lib.uuid4()),+ name=name,+ labels=node_data.get("labels", []),+ description=node_data.get("description"),+ properties=properties,+ )+ )+result = await asyncio.to_thread(graph_adapter.add_nodes,nodes=node_objects,@@ -53,9 +64,10 @@ async def add_nodes(identification_params=identification_params,metadata=metadata,)-+return result+async def update_node(uuid: str,brain_id: str,@@ -67,9 +79,9 @@ async def update_node() -> Node | None:"""Update fields of a node in the graph.-+Only the provided parameters will be applied to the node; omitted optional parameters are left unchanged.-+Parameters:uuid (str): UUID of the node to update.brain_id (str): Identifier of the brain/graph where the node resides.@@ -78,7 +90,7 @@ async def update_node(new_labels (Optional[list[str]]): Labels to assign to the node.new_properties (Optional[dict]): Properties to set or update on the node.properties_to_remove (Optional[list[str]]): List of property keys to remove from the node.-+Returns:Node | None: The updated Node if it exists, `None` if no node with the given UUID was found."""@@ -104,14 +116,14 @@ async def add_relationship() -> str:"""Create a predicate relationship between two nodes identified by UUIDs within the specified brain.-+Parameters:subject_uuid (str): UUID of the subject node.predicate_name (str): Name of the predicate (relationship).predicate_description (str): Description for the predicate.object_uuid (str): UUID of the object node.brain_id (str): Identifier of the brain/graph where the relationship will be created.-+Returns:str: Adapter result for the created relationship (typically the relationship identifier)."""@@ -120,26 +132,27 @@ async def add_relationship(uuid=subject_uuid,brain_id=brain_id,)-+object_node = await asyncio.to_thread(graph_adapter.get_by_uuid,uuid=object_uuid,brain_id=brain_id,)-+if not subject_node:raise ValueError(f"Subject node with UUID {subject_uuid} not found")-+if not object_node:raise ValueError(f"Object node with UUID {object_uuid} not found")-+import uuid as uuid_lib+predicate = Predicate(uuid=str(uuid_lib.uuid4()),name=predicate_name,description=predicate_description,)-+result = await asyncio.to_thread(graph_adapter.add_relationship,subject=subject_node,@@ -147,7 +160,7 @@ async def add_relationship(to_object=object_node,brain_id=brain_id,)-+return result@@ -159,13 +172,13 @@ async def update_relationship() -> Predicate | None:"""Update properties of an existing relationship identified by its UUID.-+Parameters:uuid (str): UUID of the relationship to update.brain_id (str): Identifier of the brain/graph scope where the relationship exists.new_properties (dict): Properties to add or update on the relationship.properties_to_remove (list[str]): List of property names to remove from the relationship.-+Returns:Predicate | None: The updated Predicate object if the relationship was found and updated, `None` otherwise."""@@ -177,4 +190,4 @@ async def update_relationship(new_properties=new_properties,properties_to_remove=properties_to_remove,)- return result\ No newline at end of file+ return resultdiff --git a/src/services/api/routes/model.py b/src/services/api/routes/model.pyindex 5961526..d2bf2fb 100644--- a/src/services/api/routes/model.py+++ b/src/services/api/routes/model.py@@ -1,4 +1,31 @@"""+File: /model.py+Created Date: Saturday December 27th 2025+Author: Christian Nonis <[email protected]>+-----+Last Modified: Sunday January 12th 2026+Modified By: the developer formerly known as Christian Nonis at <[email protected]>+-----+"""++from fastapi import APIRouter++from src.services.api.constants.requests import (+ AddEntityRequest,+ UpdateEntityRequest,+ AddRelationshipRequest,+ UpdateRelationshipRequest,+)+from src.services.api.controllers.model import (+ add_nodes as add_nodes_controller,+ update_node as update_node_controller,+ add_relationship as add_relationship_controller,+ update_relationship as update_relationship_controller,+)++model_router = APIRouter(prefix="/model", tags=["model"])++@model_router.post(path="/entity")async def add_entity(request: AddEntityRequest):"""@@ -7,18 +34,21 @@ async def add_entity(request: AddEntityRequest):Returns:Response payload containing details of the created node."""+ properties = request.properties or {}+return await add_nodes_controller(nodes=[{"name": request.name,"labels": request.labels,"description": request.description,- "properties": request.properties or {},+ "properties": properties,}],brain_id=request.brain_id,identification_params=request.identification_params,metadata=request.metadata,)+@model_router.put(path="/entity")async def update_entity(request: UpdateEntityRequest):"""@@ -53,50 +83,13 @@ async def add_relationship(request: AddRelationshipRequest):brain_id=request.brain_id,)+@model_router.put(path="/relationship")async def update_relationship(request: UpdateRelationshipRequest):"""Update properties of an existing relationship.Uses the following fields from `request`: `uuid`, `brain_id`, `new_properties` (defaults to an empty dict if missing), and `properties_to_remove` (defaults to an empty list if missing).-@model_router.post(path="/entity")-async def add_entity(request: AddEntityRequest):- """- Create a new entity (node) in the knowledge graph.-- Returns:- Response payload containing details of the created node.- """- return await add_nodes_controller(- nodes=[{- "name": request.name,- "labels": request.labels,- "description": request.description,- "properties": request.properties or {},- }],- brain_id=request.brain_id,- identification_params=request.identification_params,- metadata=request.metadata,- )-@model_router.post(path="/entity")-async def add_entity(request: AddEntityRequest):- """- Create a new entity (node) in the knowledge graph.-- Returns:- Response payload containing details of the created node.- """- return await add_nodes_controller(- nodes=[{- "name": request.name,- "labels": request.labels,- "description": request.description,- "properties": request.properties or {},- }],- brain_id=request.brain_id,- identification_params=request.identification_params,- metadata=request.metadata,- )Returns:The updated relationship representation or a result object describing the outcome of the update.@@ -106,4 +99,4 @@ async def add_entity(request: AddEntityRequest):brain_id=request.brain_id,new_properties=request.new_properties or {},properties_to_remove=request.properties_to_remove or [],- )\ No newline at end of file+ )