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: added changelogs and improvements
marcorasera5404e3b88797d7
diff --git a/src/adapters/data.py b/src/adapters/data.pyindex f4f7f6d..ac4cb96 100644--- a/src/adapters/data.py+++ b/src/adapters/data.py@@ -143,4 +143,31 @@ class DataAdapter:"""Get all unique labels from observations."""- return self.data.get_observation_labels(brain_id=brain_id)\ No newline at end of file+ return self.data.get_observation_labels(brain_id=brain_id)++ def get_changelog_by_id(+ self, id: str, brain_id: str = "default"+ ) -> KGChanges:+ """+ Get changelog by 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]:+ """+ Get a list of changelogs.+ """+ 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]:+ """+ Get all unique types from changelogs.+ """+ return self.data.get_changelog_types(brain_id=brain_id)\ No newline at end of filediff --git a/src/adapters/graph.py b/src/adapters/graph.pyindex 0690328..11e4842 100644--- a/src/adapters/graph.py+++ b/src/adapters/graph.py@@ -286,30 +286,7 @@ class GraphAdapter:"""return self.graph.get_graph_node_properties(brain_id)- def add_entity(- self,- name: str,- brain_id: str = "default",- labels: list[str] = [],- description: Optional[str] = None,- properties: Optional[dict] = None,- identification_params: Optional[dict] = None,- metadata: Optional[dict] = None,- ) -> Node | None:- """- Add a single entity (node) to the graph.- """- return self.graph.add_entity(- name,- brain_id,- labels,- description,- properties,- identification_params,- metadata,- )-- def update_entity(+ def update_node(self,uuid: str,brain_id: str = "default",@@ -322,7 +299,7 @@ class GraphAdapter:"""Update an entity (node) in the graph."""- return self.graph.update_entity(+ return self.graph.update_node(uuid,brain_id,new_name,diff --git a/src/adapters/interfaces/data.py b/src/adapters/interfaces/data.pyindex fd741eb..d541035 100644--- a/src/adapters/interfaces/data.py+++ b/src/adapters/interfaces/data.py@@ -149,4 +149,32 @@ class DataClient(ABC):"""Get all unique labels from observations."""- raise NotImplementedError("get_observation_labels method not implemented")\ No newline at end of file+ raise NotImplementedError("get_observation_labels method not implemented")++ @abstractmethod+ def get_changelog_by_id(self, id: str, brain_id: str) -> KGChanges:+ """+ Get changelog by ID.+ """+ raise NotImplementedError("get_changelog_by_id method not implemented")++ @abstractmethod+ def get_changelogs_list(+ self,+ brain_id: str,+ limit: int = 10,+ skip: int = 0,+ types: list[str] = None,+ query_text: str = None+ ) -> list[KGChanges]:+ """+ Get a list of changelogs.+ """+ raise NotImplementedError("get_changelogs_list method not implemented")++ @abstractmethod+ def get_changelog_types(self, brain_id: str) -> list[str]:+ """+ Get all unique types from changelogs.+ """+ raise NotImplementedError("get_changelog_types method not implemented")\ No newline at end of filediff --git a/src/adapters/interfaces/graph.py b/src/adapters/interfaces/graph.pyindex 1eeed11..49d21e8 100644--- a/src/adapters/interfaces/graph.py+++ b/src/adapters/interfaces/graph.py@@ -288,23 +288,7 @@ class GraphClient(ABC):raise NotImplementedError("get_graph_node_properties method not implemented")@abstractmethod- def add_entity(- self,- name: str,- brain_id: str,- labels: list[str],- description: Optional[str] = None,- properties: Optional[dict] = None,- identification_params: Optional[dict] = None,- metadata: Optional[dict] = None,- ) -> Node | None:- """- Add a single entity (node) to the graph.- """- raise NotImplementedError("add_entity method not implemented")-- @abstractmethod- def update_entity(+ def update_node(self,uuid: str,brain_id: str,diff --git a/src/lib/mongo/client.py b/src/lib/mongo/client.pyindex a7a985d..0a3eaf4 100644--- a/src/lib/mongo/client.py+++ b/src/lib/mongo/client.py@@ -280,5 +280,73 @@ 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:+ 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]:+ 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]:+ 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()diff --git a/src/lib/neo4j/client.py b/src/lib/neo4j/client.pyindex 8c052b0..9ed1941 100644--- a/src/lib/neo4j/client.py+++ b/src/lib/neo4j/client.py@@ -1047,42 +1047,8 @@ class Neo4jClient(GraphClient):self.ensure_database(brain_id)result = self.driver.execute_query(cypher_query, database_=brain_id)return [record["property"] for record in result.records]-- def add_entity(- self,- name: str,- brain_id: str,- labels: list[str],- description: Optional[str] = None,- properties: Optional[dict] = None,- identification_params: Optional[dict] = None,- metadata: Optional[dict] = None,- ) -> Node | None:- """- Add a single entity (node) to the graph.- """- import uuid as uuid_lib-- node = Node(- uuid=str(uuid_lib.uuid4()),- name=name,- labels=labels,- description=description,- properties=properties or {},- )-- result = self.add_nodes(- nodes=[node],- brain_id=brain_id,- identification_params=identification_params,- metadata=metadata,- )-- if isinstance(result, list) and len(result) > 0:- return result[0]- return None- def update_entity(+ def update_node(self,uuid: str,brain_id: str,diff --git a/src/services/api/controllers/changelogs.py b/src/services/api/controllers/changelogs.pynew file mode 100644index 0000000..18190d1--- /dev/null+++ b/src/services/api/controllers/changelogs.py@@ -0,0 +1,79 @@+"""+File: /changelogs.py+Created Date: Saturday December 27th 2025+Author: Christian Nonis <[email protected]>+-----+Last Modified: Saturday December 27th 2025+Modified By: the developer formerly known as Christian Nonis at <[email protected]>+-----+"""+import asyncio+from typing import Optional+from fastapi import HTTPException+from starlette.responses import JSONResponse+from src.services.data.main import data_adapter++async def get_changelog_by_id(+ id: str, brain_id: str = "default"+):+ """+ Get changelog by ID.+ """+ def _get_changelog():+ changelog = data_adapter.get_changelog_by_id(id, brain_id)+ if not changelog:+ raise HTTPException(status_code=404, detail="Changelog not found")+ return changelog++ result = await asyncio.to_thread(_get_changelog)++ return JSONResponse(+ content={+ "message": "Changelog retrieved successfully",+ "changelog": result.model_dump(mode="json")+ }+ )++async def get_changelogs_list(+ limit: int = 10,+ skip: int = 0,+ types: Optional[list[str]] = None,+ query_text: Optional[str] = None,+ brain_id: str = "default",+):+ """+ Get a list of changelogs.+ """+ def _get_list():+ return data_adapter.get_changelogs_list(+ brain_id, limit, skip, types, query_text+ )++ results = await asyncio.to_thread(_get_list)++ return JSONResponse(+ content={+ "message": "Changelogs list retrieved successfully",+ "changelogs": [r.model_dump(mode="json") for r in results],+ "count": len(results)+ }+ )++async def get_changelog_types(+ brain_id: str = "default",+):+ """+ Get all unique types from changelogs.+ """+ def _get_types():+ return data_adapter.get_changelog_types(brain_id)++ results = await asyncio.to_thread(_get_types)++ return JSONResponse(+ content={+ "message": "Changelog types retrieved successfully",+ "types": results,+ "count": len(results)+ }+ )\ No newline at end of filediff --git a/src/services/api/controllers/model.py b/src/services/api/controllers/model.pyindex 8f61da0..65c3a23 100644--- a/src/services/api/controllers/model.py+++ b/src/services/api/controllers/model.py@@ -13,32 +13,39 @@ from typing import Optionalfrom src.services.kg_agent.main import graph_adapterfrom src.constants.kg import Node, Predicate-async def add_entity(- name: str,+async def add_nodes(+ nodes: list[dict],brain_id: str,- labels: list[str],- description: Optional[str] = None,- properties: Optional[dict] = None,identification_params: Optional[dict] = None,metadata: Optional[dict] = None,-) -> Node | None:+) -> list[Node] | str:"""- Add a single entity (node) to the graph.+ Add multiple nodes to the graph."""+ from src.constants.kg import Node+ import 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"),+ ))+result = await asyncio.to_thread(- graph_adapter.add_entity,- name=name,+ graph_adapter.add_nodes,+ nodes=node_objects,brain_id=brain_id,- labels=labels,- description=description,- properties=properties,identification_params=identification_params,metadata=metadata,)+return result--async def update_entity(+async def update_node(uuid: str,brain_id: str,new_name: Optional[str] = None,@@ -51,7 +58,7 @@ async def update_entity(Update an entity (node) in the graph."""result = await asyncio.to_thread(- graph_adapter.update_entity,+ graph_adapter.update_node,uuid=uuid,brain_id=brain_id,new_name=new_name,diff --git a/src/services/api/routes/model.py b/src/services/api/routes/model.pyindex 42aab78..59d45e0 100644--- a/src/services/api/routes/model.py+++ b/src/services/api/routes/model.py@@ -12,8 +12,8 @@ from fastapi import APIRouterfrom src.services.api.constants.requests import AddEntityRequest, UpdateEntityRequest, AddRelationshipRequest, UpdateRelationshipRequestfrom src.services.api.controllers.model import (- add_entity as add_entity_controller,- update_entity as update_entity_controller,+ add_nodes as add_nodes_controller,+ update_node as update_node_controller,add_relationship as add_relationship_controller,update_relationship as update_relationship_controller,)@@ -26,23 +26,35 @@ async def add_entity(request: AddEntityRequest):"""Add a single entity (node) to the graph."""- return await add_entity_controller(+ import uuid as uuid_lib+ from src.constants.kg import Node++ node = Node(+ uuid=str(uuid_lib.uuid4()),name=request.name,- brain_id=request.brain_id,labels=request.labels,description=request.description,properties=request.properties,+ )++ return await add_nodes_controller(+ nodes=[{+ "name": request.name,+ "labels": request.labels,+ "description": request.description,+ "properties": request.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):"""Update an entity (node) in the graph."""- return await update_entity_controller(+ return await update_node_controller(uuid=request.uuid,brain_id=request.brain_id,new_name=request.new_name,diff --git a/src/services/api/routes/retrieve.py b/src/services/api/routes/retrieve.pyindex 7ea39cd..9ff9e31 100644--- a/src/services/api/routes/retrieve.py+++ b/src/services/api/routes/retrieve.py@@ -35,6 +35,11 @@ from src.services.api.controllers.observations import (get_observations_list as get_observations_list_controller,get_observation_labels as get_observation_labels_controller,)+from src.services.api.controllers.changelogs import (+ get_changelog_by_id as get_changelog_by_id_controller,+ get_changelogs_list as get_changelogs_list_controller,+ get_changelog_types as get_changelog_types_controller,+)retrieve_router = APIRouter(prefix="/retrieve", tags=["retrieve"])@@ -223,4 +228,38 @@ 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)\ No newline at end of file+ 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",+):+ """+ Get all unique types from changelogs.+ """+ 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",+):+ """+ Get changelog by 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",+):+ """+ Get a list of changelogs.+ """+ if types:+ types = types.split(",")+ return await get_changelogs_list_controller(limit, skip, types, query_text, brain_id)\ No newline at end of file