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(kg agent): search + add rels
Christian60d0cb5e85c5
diff --git a/.pylintrc b/.pylintrcindex 7089a1f..58595ae 100644--- a/.pylintrc+++ b/.pylintrc@@ -13,3 +13,6 @@ good-names=i,j,k,ex,Run,_,id,db,ai,llm[IMPORTS]extension-pkg-allow-list=chunker_cpp++[IGNORE]+C0103\ No newline at end of filediff --git a/src/adapters/graph.py b/src/adapters/graph.pyindex 1a8f29c..d364369 100644--- a/src/adapters/graph.py+++ b/src/adapters/graph.py@@ -64,5 +64,25 @@ class GraphAdapter:"""return self.graph.add_nodes(nodes, identification_params, metadata)+ def add_relationship(+ self,+ subject: Node,+ predicate: str,+ to_object: Node,+ ) -> str:+ """+ Add a relationship between two nodes to the graph.+ """+ return self.graph.add_relationship(subject, predicate, to_object)++ def search_graph(+ self,+ nodes: list[Node],+ ) -> list[Node]:+ """+ Search the graph for nodes and 1 degree relationships.+ """+ return self.graph.search_graph(nodes)+_graph_adapter = GraphAdapter()diff --git a/src/adapters/interfaces/graph.py b/src/adapters/interfaces/graph.pyindex 5a18fc9..ebd64c5 100644--- a/src/adapters/interfaces/graph.py+++ b/src/adapters/interfaces/graph.py@@ -53,3 +53,25 @@ class GraphClient(ABC):Add nodes to the graph."""raise NotImplementedError("add_nodes method not implemented")++ @abstractmethod+ def add_relationship(+ self,+ subject: Node,+ predicate: str,+ to_object: Node,+ ) -> str:+ """+ Add a relationship between two nodes to the graph.+ """+ raise NotImplementedError("add_relationship method not implemented")++ @abstractmethod+ def search_graph(+ self,+ nodes: list[Node],+ ) -> list[Node]:+ """+ Search the graph for nodes and 1 degree relationships.+ """+ raise NotImplementedError("search_graph method not implemented")diff --git a/src/core/agents/kg_agent.py b/src/core/agents/kg_agent.pyindex c6dde12..5b5ef07 100644--- a/src/core/agents/kg_agent.py+++ b/src/core/agents/kg_agent.py@@ -21,12 +21,7 @@ from src.constants.prompts.kg_agent import ()from src.core.agents.tools.kg_agent import (KGAgentAddTripletsTool,- KGAgentExecuteGraphOperationTool,- KGAgentAddNodesTool,- KGAgentAddRelationshipsTool,- KGAgentUpdateNodesTool,- KGAgentDeleteNodesTool,- KGAgentDeleteRelationshipsTool,+ KGAgentSearchGraphTool,)@@ -58,15 +53,8 @@ class KGAgent:def _get_tools(self, identification_params: dict, metadata: dict) -> List[BaseTool]:return [- KGAgentExecuteGraphOperationTool(- self, self.kg, self.kg.graphdb_description- ),- # KGAgentAddNodesTool(self, self.kg, identification_params, metadata),KGAgentAddTripletsTool(self, self.kg, identification_params, metadata),- # KGAgentAddRelationshipsTool(self, self.kg, self.kg.graphdb_description),- # KGAgentUpdateNodesTool(self, self.kg, self.kg.graphdb_description),- # KGAgentDeleteNodesTool(self, self.kg, self.kg.graphdb_description),- # KGAgentDeleteRelationshipsTool(self, self.kg, self.kg.graphdb_description),+ KGAgentSearchGraphTool(self, self.kg, identification_params, metadata),]def _get_agent(self, identification_params: dict, metadata: dict):@@ -82,7 +70,6 @@ class KGAgent:"""Search the knowledge graph for information."""- # TODO vector search and retrievaldef update_kg(self,diff --git a/src/core/agents/observations_agent.py b/src/core/agents/observations_agent.pynew file mode 100644index 0000000..7cc5632--- /dev/null+++ b/src/core/agents/observations_agent.py@@ -0,0 +1,9 @@+"""+File: /observations_agent.py+Created Date: Thursday October 23rd 2025+Author: Christian Nonis <[email protected]>+-----+Last Modified: Thursday October 23rd 2025 10:11:00 pm+Modified By: the developer formerly known as Christian Nonis at <[email protected]>+-----+"""diff --git a/src/core/agents/tools/kg_agent.py b/src/core/agents/tools/kg_agent.pydeleted file mode 100644index 3ce70d0..0000000--- a/src/core/agents/tools/kg_agent.py+++ /dev/null@@ -1,197 +0,0 @@-"""-File: /kg_agent.py-Created Date: Sunday October 19th 2025-Author: Christian Nonis <[email protected]>-------Last Modified: Sunday October 19th 2025 3:36:26 pm-Modified By: the developer formerly known as Christian Nonis at <[email protected]>-------"""--from typing import Optional-import uuid-from langchain.tools import BaseTool--from src.adapters.graph import GraphAdapter-from src.constants.kg import Node, Triple-from src.services.api.constants.tool_schemas import NODE_SCHEMA, TRIPLE_SCHEMA---class KGAgentExecuteGraphOperationTool(BaseTool):- """- Tool for executing a graph operation.- """-- name: str = "kg_agent_execute_graph_operation"-- kg_agent: object- kg: GraphAdapter-- def __init__(self, kg_agent, kg: GraphAdapter, database_desc: str):- description: str = (- "Tool for executing search operations on the knowledge graph. "- "Use this tool to search for information and existing nodes in the knowledge graph. "- "The query should be a valid graph 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."- )- # description: str = (- # "Tool for executing any type of graph operation search/edit/query/delete/etc. "- # "The query should be a valid graph 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."- # )- formatted_description = description.format(database_desc=database_desc)- super().__init__(kg_agent=kg_agent, kg=kg, description=formatted_description)-- def _run(self, *args, **kwargs) -> str:- _query = ""- if len(args) > 0:- _query = args[0]-- if len(kwargs) > 0:- args_query = kwargs.get("args", {})- if isinstance(args_query, dict):- _query = args_query.get("query", "")- elif isinstance(args_query, list):- _query = args_query[0].get("query", "")-- if len(_query) == 0:- return "No query provided in the arguments or kwargs"-- response = self.kg.execute_operation(_query)-- return response---class KGAgentAddNodesTool(BaseTool):- """- Tool for adding nodes to the knowledge graph.- """-- name: str = "kg_agent_add_nodes"-- kg_agent: object- kg: GraphAdapter- identification_params: Optional[dict] = None- metadata: Optional[dict] = None-- args_schema: dict = {- "type": "object",- "properties": {- "nodes": {- "type": "array",- "items": NODE_SCHEMA,- },- },- "required": ["nodes"],- }-- def __init__(- self,- kg_agent,- kg: GraphAdapter,- identification_params: Optional[dict] = None,- metadata: Optional[dict] = None,- ):- description: str = (- "Tool specifically for adding nodes to the knowledge graph. "- "This tool will return the nodes that were added to the knowledge graph."- "Input should be a valid JSON object with a 'nodes' key. "- )- super().__init__(- kg_agent=kg_agent,- kg=kg,- description=description,- identification_params=identification_params or {},- metadata=metadata or {},- )-- def _run(self, *args, **kwargs) -> str:- nodes = [- Node(**node, uuid=str(uuid.uuid4())) for node in kwargs.get("nodes", [])- ]- self.kg.add_nodes(nodes, self.identification_params, self.metadata)- return "Nodes added successfully"---class KGAgentAddTripletsTool(BaseTool):- """- Tool for adding triplets to the knowledge graph.- """-- name: str = "kg_agent_add_triplets"- kg_agent: object- kg: GraphAdapter- identification_params: Optional[dict] = None- metadata: Optional[dict] = None-- args_schema: dict = {- "type": "object",- "properties": {- "triplets": {- "type": "array",- "description": ("The triplets to add to the knowledge graph."),- "items": TRIPLE_SCHEMA,- },- },- }-- def __init__(- self,- kg_agent,- kg: GraphAdapter,- identification_params: Optional[dict] = None,- metadata: Optional[dict] = None,- ):- description: str = (- "This tool is used to register triplets into the knowledge graph. "- "Returns the triplets that were added to the knowledge graph. "- )- super().__init__(- kg_agent=kg_agent,- kg=kg,- description=description,- identification_params=identification_params or {},- metadata=metadata or {},- )-- def _run(self, *args, **kwargs) -> str:- triplets = []- for triplet_data in kwargs.get("triplets", []):- subject = Node(**triplet_data["subject"])- object_node = Node(**triplet_data["object"])-- triplet = Triple(- subject=subject, predicate=triplet_data["predicate"], object=object_node- )- triplets.append(triplet)-- for triplet in triplets:- print(- f"{triplet.subject.name} - {triplet.predicate} -> {triplet.object.name}"- )- self.kg.add_nodes(- [triplet.subject, triplet.object],- self.identification_params,- self.metadata,- )- return f"Triplets added successfully: {triplets}"---class KGAgentAddRelationshipsTool(BaseTool):- pass---class KGAgentUpdateNodesTool(BaseTool):- pass---class KGAgentDeleteNodesTool(BaseTool):- pass---class KGAgentDeleteRelationshipsTool(BaseTool):- passdiff --git a/src/core/agents/tools/kg_agent/KGAgentAddNodesTool.py b/src/core/agents/tools/kg_agent/KGAgentAddNodesTool.pynew file mode 100644index 0000000..7f25e42--- /dev/null+++ b/src/core/agents/tools/kg_agent/KGAgentAddNodesTool.py@@ -0,0 +1,68 @@+"""+File: /KGAgentAddNodesTool.py+Created Date: Thursday October 23rd 2025+Author: Christian Nonis <[email protected]>+-----+Last Modified: Thursday October 23rd 2025 9:27:01 pm+Modified By: the developer formerly known as Christian Nonis at <[email protected]>+-----+"""++import uuid+from typing import Optional+from langchain.tools import BaseTool++from src.adapters.graph import GraphAdapter+from src.constants.kg import Node+from src.services.api.constants.tool_schemas import NODE_SCHEMA+++class KGAgentAddNodesTool(BaseTool):+ """+ Tool for adding nodes to the knowledge graph.+ """++ name: str = "kg_agent_add_nodes"++ kg_agent: object+ kg: GraphAdapter+ identification_params: Optional[dict] = None+ metadata: Optional[dict] = None++ args_schema: dict = {+ "type": "object",+ "properties": {+ "nodes": {+ "type": "array",+ "items": NODE_SCHEMA,+ },+ },+ "required": ["nodes"],+ }++ def __init__(+ self,+ kg_agent,+ kg: GraphAdapter,+ identification_params: Optional[dict] = None,+ metadata: Optional[dict] = None,+ ):+ description: str = (+ "Tool specifically for adding nodes to the knowledge graph. "+ "This tool will return the nodes that were added to the knowledge graph."+ "Input should be a valid JSON object with a 'nodes' key. "+ )+ super().__init__(+ kg_agent=kg_agent,+ kg=kg,+ description=description,+ identification_params=identification_params or {},+ metadata=metadata or {},+ )++ def _run(self, *args, **kwargs) -> str:+ nodes = [+ Node(**node, uuid=str(uuid.uuid4())) for node in kwargs.get("nodes", [])+ ]+ self.kg.add_nodes(nodes, self.identification_params, self.metadata)+ return "Nodes added successfully"diff --git a/src/core/agents/tools/kg_agent/KGAgentAddTripletsTool.py b/src/core/agents/tools/kg_agent/KGAgentAddTripletsTool.pynew file mode 100644index 0000000..1e50352--- /dev/null+++ b/src/core/agents/tools/kg_agent/KGAgentAddTripletsTool.py@@ -0,0 +1,82 @@+"""+File: /KGAgentAddTripletsTool.py+Created Date: Thursday October 23rd 2025+Author: Christian Nonis <[email protected]>+-----+Last Modified: Thursday October 23rd 2025 9:27:41 pm+Modified By: the developer formerly known as Christian Nonis at <[email protected]>+-----+"""++from typing import Optional+from langchain.tools import BaseTool++from src.adapters.graph import GraphAdapter+from src.constants.kg import Node, Triple+from src.services.api.constants.tool_schemas import TRIPLE_SCHEMA+++class KGAgentAddTripletsTool(BaseTool):+ """+ Tool for adding triplets to the knowledge graph.+ """++ name: str = "kg_agent_add_triplets"+ kg_agent: object+ kg: GraphAdapter+ identification_params: Optional[dict] = None+ metadata: Optional[dict] = None++ args_schema: dict = {+ "type": "object",+ "properties": {+ "triplets": {+ "type": "array",+ "description": ("The triplets to add to the knowledge graph."),+ "items": TRIPLE_SCHEMA,+ },+ },+ }++ def __init__(+ self,+ kg_agent,+ kg: GraphAdapter,+ identification_params: Optional[dict] = None,+ metadata: Optional[dict] = None,+ ):+ description: str = (+ "This tool is used to register triplets into the knowledge graph. "+ "Returns the triplets that were added to the knowledge graph. "+ )+ super().__init__(+ kg_agent=kg_agent,+ kg=kg,+ description=description,+ identification_params=identification_params or {},+ metadata=metadata or {},+ )++ def _run(self, *args, **kwargs) -> str:+ triplets = []+ for triplet_data in kwargs.get("triplets", []):+ subject = Node(**triplet_data["subject"])+ object_node = Node(**triplet_data["object"])++ triplet = Triple(+ subject=subject, predicate=triplet_data["predicate"], object=object_node+ )+ triplets.append(triplet)++ for triplet in triplets:+ self.kg.add_nodes(+ [triplet.subject, triplet.object],+ self.identification_params,+ self.metadata,+ )+ self.kg.add_relationship(+ triplet.subject,+ triplet.predicate,+ triplet.object,+ )+ return f"Triplets added successfully: {triplets}"diff --git a/src/core/agents/tools/kg_agent/KGAgentDeleteNodesTool.py b/src/core/agents/tools/kg_agent/KGAgentDeleteNodesTool.pynew file mode 100644index 0000000..6bac50a--- /dev/null+++ b/src/core/agents/tools/kg_agent/KGAgentDeleteNodesTool.py@@ -0,0 +1,9 @@+"""+File: /KGAgentDeleteNodesTool.py+Created Date: Thursday October 23rd 2025+Author: Christian Nonis <[email protected]>+-----+Last Modified: Thursday October 23rd 2025 9:29:40 pm+Modified By: the developer formerly known as Christian Nonis at <[email protected]>+-----+"""diff --git a/src/core/agents/tools/kg_agent/KGAgentDeleteRelationshipTool.py b/src/core/agents/tools/kg_agent/KGAgentDeleteRelationshipTool.pynew file mode 100644index 0000000..904267b--- /dev/null+++ b/src/core/agents/tools/kg_agent/KGAgentDeleteRelationshipTool.py@@ -0,0 +1,9 @@+"""+File: /KGAgentDeleteRelationshipTool.py+Created Date: Thursday October 23rd 2025+Author: Christian Nonis <[email protected]>+-----+Last Modified: Thursday October 23rd 2025 9:29:22 pm+Modified By: the developer formerly known as Christian Nonis at <[email protected]>+-----+"""diff --git a/src/core/agents/tools/kg_agent/KGAgentExecuteGraphOperationTool.py b/src/core/agents/tools/kg_agent/KGAgentExecuteGraphOperationTool.pynew file mode 100644index 0000000..37a479c--- /dev/null+++ b/src/core/agents/tools/kg_agent/KGAgentExecuteGraphOperationTool.py@@ -0,0 +1,62 @@+"""+File: /KGAgentExecuteGraphOperationTool.py+Created Date: Thursday October 23rd 2025+Author: Christian Nonis <[email protected]>+-----+Last Modified: Thursday October 23rd 2025 9:26:22 pm+Modified By: the developer formerly known as Christian Nonis at <[email protected]>+-----+"""++from langchain.tools import BaseTool++from src.adapters.graph import GraphAdapter+++class KGAgentExecuteGraphOperationTool(BaseTool):+ """+ Tool for executing a graph operation.+ """++ name: str = "kg_agent_execute_graph_operation"++ kg_agent: object+ kg: GraphAdapter++ def __init__(self, kg_agent, kg: GraphAdapter, database_desc: str):+ description: str = (+ "Tool for executing search operations on the knowledge graph. "+ "Use this tool to search for information and existing nodes in the knowledge graph. "+ "The query should be a valid graph 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."+ )+ # description: str = (+ # "Tool for executing any type of graph operation search/edit/query/delete/etc. "+ # "The query should be a valid graph 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."+ # )+ formatted_description = description.format(database_desc=database_desc)+ super().__init__(kg_agent=kg_agent, kg=kg, description=formatted_description)++ def _run(self, *args, **kwargs) -> str:+ _query = ""+ if len(args) > 0:+ _query = args[0]++ if len(kwargs) > 0:+ args_query = kwargs.get("args", {})+ if isinstance(args_query, dict):+ _query = args_query.get("query", "")+ elif isinstance(args_query, list):+ _query = args_query[0].get("query", "")++ if len(_query) == 0:+ return "No query provided in the arguments or kwargs"++ response = self.kg.execute_operation(_query)++ return responsediff --git a/src/core/agents/tools/kg_agent/KGAgentSearchGraphTool.py b/src/core/agents/tools/kg_agent/KGAgentSearchGraphTool.pynew file mode 100644index 0000000..9ec4e99--- /dev/null+++ b/src/core/agents/tools/kg_agent/KGAgentSearchGraphTool.py@@ -0,0 +1,90 @@+"""+File: /KGAgentSearchGraphTool.py+Created Date: Thursday October 23rd 2025+Author: Christian Nonis <[email protected]>+-----+Last Modified: Thursday October 23rd 2025 9:28:20 pm+Modified By: the developer formerly known as Christian Nonis at <[email protected]>+-----+"""++from typing import Optional+from langchain.tools import BaseTool++from src.adapters.graph import GraphAdapter+from src.constants.kg import Node+++class KGAgentSearchGraphTool(BaseTool):+ """+ Tool for searching the knowledge graph.+ """++ name: str = "kg_agent_search_graph"+ kg_agent: object+ kg: GraphAdapter+ identification_params: Optional[dict] = None+ metadata: Optional[dict] = None++ args_schema: dict = {+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "description": (+ "Add this parameter if you want to search textually into the knowledge graph."+ ),+ },+ "nodes": {+ "type": "array",+ "description": (+ "Add this parameter if you want to search for specific nodes "+ "in the knowledge graph by their name and label."+ ),+ "items": {+ "type": "object",+ "properties": {+ "label": {+ "type": "string",+ "description": "The label of the node to search for.",+ },+ "name": {+ "type": "string",+ "description": "The name of the node to search for.",+ },+ },+ "required": ["label", "name"],+ },+ },+ },+ }++ def __init__(+ self,+ kg_agent,+ kg: GraphAdapter,+ identification_params: Optional[dict] = None,+ metadata: Optional[dict] = None,+ ):+ description: str = (+ "Tool for searching the knowledge graph. "+ "This tool will return the nodes with the properties "+ "and relationships that were found in the knowledge graph."+ "You can both search textually for semantically related nodes "+ "or search for specific nodes by their name and label."+ "The tool will return a list of nodes with the properties "+ "and 1st degree relationships that were found in the knowledge graph."+ )+ super().__init__(+ kg_agent=kg_agent,+ kg=kg,+ description=description,+ identification_params=identification_params or {},+ metadata=metadata or {},+ )++ def _run(self, *args, **kwargs) -> str:+ query = kwargs.get("query", "")+ nodes = kwargs.get("nodes", [])+ _nodes = [Node(name=node["name"], label=node["label"]) for node in nodes]+ return self.kg.search_graph(nodes)diff --git a/src/core/agents/tools/kg_agent/KGAgentUpdateNodesTool.py b/src/core/agents/tools/kg_agent/KGAgentUpdateNodesTool.pynew file mode 100644index 0000000..2c84d36--- /dev/null+++ b/src/core/agents/tools/kg_agent/KGAgentUpdateNodesTool.py@@ -0,0 +1,9 @@+"""+File: /KGAgentUpdateNodesTool.py+Created Date: Thursday October 23rd 2025+Author: Christian Nonis <[email protected]>+-----+Last Modified: Thursday October 23rd 2025 9:29:08 pm+Modified By: the developer formerly known as Christian Nonis at <[email protected]>+-----+"""diff --git a/src/core/agents/tools/kg_agent/__init__.py b/src/core/agents/tools/kg_agent/__init__.pynew file mode 100644index 0000000..c01c4df--- /dev/null+++ b/src/core/agents/tools/kg_agent/__init__.py@@ -0,0 +1,21 @@+"""+File: /__init__.py+Created Date: Thursday October 23rd 2025+Author: Christian Nonis <[email protected]>+-----+Last Modified: Thursday October 23rd 2025 9:26:10 pm+Modified By: the developer formerly known as Christian Nonis at <[email protected]>+-----+"""++from .KGAgentExecuteGraphOperationTool import KGAgentExecuteGraphOperationTool+from .KGAgentAddNodesTool import KGAgentAddNodesTool+from .KGAgentAddTripletsTool import KGAgentAddTripletsTool+from .KGAgentSearchGraphTool import KGAgentSearchGraphTool++__all__ = [+ "KGAgentExecuteGraphOperationTool",+ "KGAgentAddNodesTool",+ "KGAgentAddTripletsTool",+ "KGAgentSearchGraphTool",+]diff --git a/src/lib/neo4j/client.py b/src/lib/neo4j/client.pyindex ca91a79..cd9a3c6 100644--- a/src/lib/neo4j/client.py+++ b/src/lib/neo4j/client.py@@ -35,7 +35,8 @@ class Neo4jClient(GraphClient):@propertydef graphdb_description(self) -> str:"""- Get the description of the graph database. It is used to let the agent know which syntax to use.+ Get the description of the graph database.+ It is used to let the agent know which syntax to use."""return "The graph database is Neo4j. Cyphter is the language used to operate with it."@@ -99,5 +100,41 @@ class Neo4jClient(GraphClient):for node in nodes]+ def add_relationship(+ self,+ subject: Node,+ predicate: str,+ to_object: Node,+ ) -> str:+ """+ Add a relationship between two nodes to the graph.+ """+ cypher_query = f"""+ MATCH (a:{subject.label.replace(" ", "")}) WHERE a.name = '{subject.name}'+ MATCH (b:{to_object.label.replace(" ", "")}) WHERE b.name = '{to_object.name}'+ CREATE (a)-[:{predicate.replace(" ", "_").upper()}]->(b)+ RETURN a, b+ """+ result = self.driver.execute_query(cypher_query)+ return result++ def search_graph(self, nodes: list[Node]) -> list[Node]:+ """+ Search the graph for nodes and 1 degree relationships.+ """+ if not nodes:+ return []++ queries = []+ for node in nodes:+ query = f"""MATCH (n:{node.label}) WHERE n.name = '{node.name}'+ OPTIONAL MATCH (n)-[r*1]-(m)+ RETURN n, r, m"""+ queries.append(query)++ cypher_query = " UNION ".join(queries)+ result = self.driver.execute_query(cypher_query)+ return result+_neo4j_client = Neo4jClient()diff --git a/src/services/observations/__init__.py b/src/services/observations/__init__.pynew file mode 100644index 0000000..bc8e9cc--- /dev/null+++ b/src/services/observations/__init__.py@@ -0,0 +1,9 @@+"""+File: /__init__.py+Created Date: Thursday October 23rd 2025+Author: Christian Nonis <[email protected]>+-----+Last Modified: Thursday October 23rd 2025 10:10:38 pm+Modified By: the developer formerly known as Christian Nonis at <[email protected]>+-----+"""