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
Refactor graph operation serialization and deduplicate janitor graph tools
Cursor Agentf12f04f4349f
diff --git a/src/adapters/graph.py b/src/adapters/graph.pyindex a13c66e..4221f0f 100644--- a/src/adapters/graph.py+++ b/src/adapters/graph.py@@ -22,6 +22,9 @@ from src.constants.kg import (SearchRelationshipsResult,)from src.adapters.interfaces.embeddings import VectorStoreClient+from src.adapters.graph_operation_result_serializer import (+ serialize_graph_operation_result,+)from src.utils.normalization.list_reduction import reduce_listfrom src.utils.similarity.vectors import cosine_similarity@@ -115,7 +118,8 @@ class GraphAdapter:Execute a generic graph operation."""try:- return self.graph.execute_operation(operation, brain_id)+ result = self.graph.execute_operation(operation, brain_id)+ return serialize_graph_operation_result(result)except Exception as e: # pylint: disable=broad-exception-caughtprint(f"Error executing graph operation: {e} - {operation}")return f"Error executing graph operation: {e}"diff --git a/src/adapters/graph_operation_result_serializer.py b/src/adapters/graph_operation_result_serializer.pynew file mode 100644index 0000000..73bf06c--- /dev/null+++ b/src/adapters/graph_operation_result_serializer.py@@ -0,0 +1,107 @@+import json+from abc import ABC, abstractmethod+from typing import Any, Iterable+++class GraphOperationResultSerializer(ABC):+ @abstractmethod+ def can_handle(self, result: Any) -> bool:+ raise NotImplementedError++ @abstractmethod+ def serialize(self, result: Any) -> str:+ raise NotImplementedError+++class NoneResultSerializer(GraphOperationResultSerializer):+ def can_handle(self, result: Any) -> bool:+ return result is None++ def serialize(self, result: Any) -> str:+ return ""+++class StringResultSerializer(GraphOperationResultSerializer):+ def can_handle(self, result: Any) -> bool:+ return isinstance(result, str)++ def serialize(self, result: Any) -> str:+ return result+++class Neo4jResultSerializer(GraphOperationResultSerializer):+ def can_handle(self, result: Any) -> bool:+ return hasattr(result, "records")++ def serialize(self, result: Any) -> str:+ records = result.records or []+ limited_records = records[:20]+ serialized_records = []+ for record in limited_records:+ if hasattr(record, "data"):+ serialized_records.append(record.data())+ continue+ try:+ serialized_records.append(dict(record))+ except Exception:+ serialized_records.append(str(record))+ keys = None+ try:+ keys = list(result.keys())+ except Exception:+ try:+ keys = list(result.keys)+ except Exception:+ keys = None+ payload = {+ "records": serialized_records,+ "truncated": len(records) > 20,+ }+ if keys is not None:+ payload["keys"] = keys+ return json.dumps(payload, default=str)+++class JsonResultSerializer(GraphOperationResultSerializer):+ def can_handle(self, result: Any) -> bool:+ return isinstance(result, (dict, list, tuple, int, float, bool))++ def serialize(self, result: Any) -> str:+ return json.dumps(result, default=str)+++class FallbackResultSerializer(GraphOperationResultSerializer):+ def can_handle(self, result: Any) -> bool:+ return True++ def serialize(self, result: Any) -> str:+ return str(result)+++class GraphOperationResultSerializerChain:+ def __init__(+ self, serializers: Iterable[GraphOperationResultSerializer] | None = None+ ):+ self.serializers = list(+ serializers+ or [+ NoneResultSerializer(),+ StringResultSerializer(),+ Neo4jResultSerializer(),+ JsonResultSerializer(),+ FallbackResultSerializer(),+ ]+ )++ def serialize(self, result: Any) -> str:+ for serializer in self.serializers:+ if serializer.can_handle(result):+ return serializer.serialize(result)+ return str(result)+++_default_graph_operation_serializer = GraphOperationResultSerializerChain()+++def serialize_graph_operation_result(result: Any) -> str:+ return _default_graph_operation_serializer.serialize(result)diff --git a/src/adapters/interfaces/graph.py b/src/adapters/interfaces/graph.pyindex 89fb2ef..e527bd7 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, TypedDict+from typing import Any, Dict, List, Literal, Optional, Tuple, TypedDictfrom src.constants.kg import (IdentificationParams,@@ -50,7 +50,7 @@ class GraphClient(ABC):raise NotImplementedError("graphdb_type method not implemented")@abstractmethod- def execute_operation(self, operation: str, brain_id: str) -> str:+ def execute_operation(self, operation: str, brain_id: str) -> Any:"""Execute a generic graph operation."""diff --git a/src/core/agents/janitor_agent.py b/src/core/agents/janitor_agent.pyindex 1db09dc..11ae136 100644--- a/src/core/agents/janitor_agent.py+++ b/src/core/agents/janitor_agent.py@@ -49,7 +49,6 @@ from src.core.agents.tools.janitor_agent import (JanitorAgentGetSchemaTool,JanitorAgentSearchEntitiesTool,JanitorAgentExecuteGraphReadOperationTool,- JanitorAgentExecuteGraphOperationTool,)from src.core.agents.tools.janitor_agent.JanitorAgentSearchRelationshipTool import (JanitorAgentSearchRelationshipsTool,@@ -729,9 +728,6 @@ class JanitorAgent:f"Atomic janitor agent invoke failed after {last_attempt.attempt_number} attempts. "f"Last error: {last_attempt.exception()}") from last_attempt.exception()- except:- raise-def _invoke_and_process(previous_messages: list):"""Invoke the agent with retry logic, append any returned messages to the outer `accumulated_messages` list, and return the agent response.diff --git a/src/core/agents/tools/janitor_agent/JanitorAgentExecuteGraphOperationTool.py b/src/core/agents/tools/janitor_agent/JanitorAgentExecuteGraphOperationTool.pydeleted file mode 100644index 5917e82..0000000--- a/src/core/agents/tools/janitor_agent/JanitorAgentExecuteGraphOperationTool.py+++ /dev/null@@ -1,74 +0,0 @@-"""-File: /JanitorAgentExecuteGraphOperationTool.py-Created Date: Friday January 2nd 2026-Author: Christian Nonis <[email protected]>-------Last Modified: Friday January 2nd 2026 11:42:24 am-Modified By: the developer formerly known as Christian Nonis at <[email protected]>-------"""--from langchain.tools import BaseTool--from src.adapters.graph import GraphAdapter---class JanitorAgentExecuteGraphOperationTool(BaseTool):- """- Tool for executing a graph operation.- """-- name: str = "execute_graph_read_operation"-- janitor_agent: object- kg: GraphAdapter- brain_id: str = "default"-- args_schema: dict = {- "type": "object",- "properties": {- "query": {- "type": "string",- "description": "The query to execute on the knowledge graph. Should be a valid graph read only operation depending on the graph database type.",- },- },- "required": ["query"],- }-- def __init__(- self,- janitor_agent,- kg: GraphAdapter,- database_desc: str,- brain_id: str = "default",- ):- description: str = (- "Tool for executing read only operations on the knowledge graph. "- "Use this tool to read information from the knowledge graph. "- "The query should be a valid graph read only operation depending on the graph database type."- "The query should be a valid JSON object with a 'query' key. "- "{database_desc}."- "If you get an error, try again after fixing your query and don't give up. "- "If you get a result, return the result as a JSON object."- )- formatted_description = description.format(database_desc=database_desc)- super().__init__(- janitor_agent=janitor_agent,- kg=kg,- description=formatted_description,- brain_id=brain_id,- )-- def _run(self, *args, **kwargs) -> str:- _query = ""- if len(args) > 0:- _query = args[0]- else:- _query = kwargs.get("query", "")-- if len(_query) == 0:- return "No query provided in the arguments or kwargs"-- response = self.kg.execute_operation(_query, brain_id=self.brain_id)-- return responsediff --git a/src/core/agents/tools/janitor_agent/__init__.py b/src/core/agents/tools/janitor_agent/__init__.pyindex 4061f44..a1dbdc1 100644--- a/src/core/agents/tools/janitor_agent/__init__.py+++ b/src/core/agents/tools/janitor_agent/__init__.py@@ -10,7 +10,6 @@ Modified By: the developer formerly known as Christian Nonis at <alch.infoemail@from .JanitorAgentGetSchemaTool import JanitorAgentGetSchemaToolfrom .JanitorAgentSearchEntitiesTool import JanitorAgentSearchEntitiesTool-from .JanitorAgentExecuteGraphOperationTool import JanitorAgentExecuteGraphOperationToolfrom .JanitorAgentExecuteGraphReadOperationTool import (JanitorAgentExecuteGraphReadOperationTool,)@@ -19,5 +18,4 @@ __all__ = ["JanitorAgentGetSchemaTool","JanitorAgentSearchEntitiesTool","JanitorAgentExecuteGraphReadOperationTool",- "JanitorAgentExecuteGraphOperationTool",]diff --git a/src/core/agents/tools/kg_agent/KGAgentExecuteGraphOperationTool.py b/src/core/agents/tools/kg_agent/KGAgentExecuteGraphOperationTool.pyindex af4d252..41390f6 100644--- a/src/core/agents/tools/kg_agent/KGAgentExecuteGraphOperationTool.py+++ b/src/core/agents/tools/kg_agent/KGAgentExecuteGraphOperationTool.py@@ -59,39 +59,6 @@ class KGAgentExecuteGraphOperationTool(BaseTool):brain_id=brain_id,)- def _serialize_response(self, response) -> str:- if response is None:- return ""-- if hasattr(response, "records"):- records = response.records or []- if len(records) > 20:- records = records[:20]- serialized_records = []- for record in records:- if hasattr(record, "data"):- serialized_records.append(record.data())- else:- try:- serialized_records.append(dict(record))- except Exception:- serialized_records.append(str(record))- keys = None- try:- keys = list(response.keys())- except Exception:- try:- keys = list(response.keys)- except Exception:- keys = None- payload = {"records": serialized_records}- if keys is not None:- payload["keys"] = keys- payload["truncated"] = len(response.records or []) > 20- return json.dumps(payload, default=str)-- return json.dumps(response, default=str)-def _run(self, *args, **kwargs) -> str:"""Execute a graph operation using a query extracted from the provided arguments and return the KG adapter's response.@@ -156,4 +123,4 @@ class KGAgentExecuteGraphOperationTool(BaseTool):)return f"Error executing query: {e}"- return self._serialize_response(response)+ return responsediff --git a/src/lib/neo4j/client.py b/src/lib/neo4j/client.pyindex 8b1c8e4..4190524 100644--- a/src/lib/neo4j/client.py+++ b/src/lib/neo4j/client.py@@ -47,7 +47,7 @@ class Neo4jClient(GraphClient):notifications_min_severity="OFF",)- def execute_operation(self, operation: str, brain_id: str) -> str:+ def execute_operation(self, operation: str, brain_id: str) -> Any:"""Execute a Neo4j operation with database override."""diff --git a/tests/test_architecture_refactors.py b/tests/test_architecture_refactors.pyindex 102df56..330d21f 100644--- a/tests/test_architecture_refactors.py+++ b/tests/test_architecture_refactors.py@@ -1,3 +1,4 @@+import jsonimport osimport unittestfrom unittest.mock import patch@@ -178,6 +179,59 @@ class GraphAdapterReductionTests(unittest.TestCase):self.assertEqual(averaged, [2.0, 3.0])+class GraphOperationSerializationTests(unittest.TestCase):+ def test_execute_operation_serializes_none_result(self):+ class FakeGraphClient:+ def execute_operation(self, operation: str, brain_id: str):+ return None++ adapter = GraphAdapter()+ adapter.add_client(FakeGraphClient())+ result = adapter.execute_operation("RETURN 1", brain_id="default")+ self.assertEqual(result, "")++ def test_execute_operation_serializes_mapping_result(self):+ class FakeGraphClient:+ def execute_operation(self, operation: str, brain_id: str):+ return {"operation": operation, "brain_id": brain_id, "ok": True}++ adapter = GraphAdapter()+ adapter.add_client(FakeGraphClient())+ result = adapter.execute_operation("RETURN 1", brain_id="test-brain")+ self.assertEqual(+ json.loads(result),+ {"operation": "RETURN 1", "brain_id": "test-brain", "ok": True},+ )++ def test_execute_operation_serializes_neo4j_like_result_with_limit(self):+ class FakeRecord:+ def __init__(self, value: int):+ self.value = value++ def data(self):+ return {"value": self.value}++ class FakeNeo4jResult:+ def __init__(self):+ self.records = [FakeRecord(value) for value in range(25)]++ def keys(self):+ return ["value"]++ class FakeGraphClient:+ def execute_operation(self, operation: str, brain_id: str):+ return FakeNeo4jResult()++ adapter = GraphAdapter()+ adapter.add_client(FakeGraphClient())+ result = adapter.execute_operation("MATCH (n) RETURN n", brain_id="default")+ payload = json.loads(result)+ self.assertTrue(payload["truncated"])+ self.assertEqual(payload["keys"], ["value"])+ self.assertEqual(len(payload["records"]), 20)+ self.assertEqual(payload["records"][0], {"value": 0})++class EntityStatusControllerTests(unittest.IsolatedAsyncioTestCase):async def test_get_entity_status_skips_missing_graph_nodes(self):fake_vector = type(diff --git a/tests/test_static_hardening_refactors.py b/tests/test_static_hardening_refactors.pyindex 047a902..f0e9b19 100644--- a/tests/test_static_hardening_refactors.py+++ b/tests/test_static_hardening_refactors.py@@ -119,5 +119,17 @@ class EntityStatusHardeningTests(unittest.TestCase):self.assertIn("continue", source)+class JanitorToolDeduplicationTests(unittest.TestCase):+ def test_janitor_tools_init_exports_single_graph_read_tool(self):+ source = read_source("src/core/agents/tools/janitor_agent/__init__.py")+ self.assertIn("JanitorAgentExecuteGraphReadOperationTool", source)+ self.assertNotIn("JanitorAgentExecuteGraphOperationTool", source)++ def test_janitor_agent_imports_single_graph_read_tool(self):+ source = read_source("src/core/agents/janitor_agent.py")+ self.assertIn("JanitorAgentExecuteGraphReadOperationTool", source)+ self.assertNotIn("JanitorAgentExecuteGraphOperationTool", source)++if __name__ == "__main__":unittest.main()