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.

feat+fix(changelogs+relationships&retrieve): added changelogs and fixed duplicated relationships creation with change to lowercase node properties instead of capitalized

Christian10e910a5ec13
diff --git a/pyproject.toml b/pyproject.toml
index 8c9149a..51fe3fe 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "brainapi2"
-version = "1.6.16-dev"
+version = "1.7.0-dev"
description = "Version 1.x.x of the BrainAPI memory layer."
authors = [
{name = "Christian",email = "[email protected]"}
diff --git a/src/adapters/data.py b/src/adapters/data.py
index b1dbcc0..9fd406f 100644
--- a/src/adapters/data.py
+++ b/src/adapters/data.py
@@ -10,7 +10,7 @@ Modified By: the developer formerly known as Christian Nonis at <alch.infoemail@
from typing import List, Tuple
from src.adapters.interfaces.data import DataClient, SearchResult
-from src.constants.data import Brain, Observation, StructuredData, TextChunk
+from src.constants.data import Brain, KGChanges, Observation, StructuredData, TextChunk
class DataAdapter:
@@ -82,3 +82,11 @@ class DataAdapter:
Get the list of brains from the data client.
"""
return self.data.get_brains_list()
+
+ def save_kg_changes(
+ self, kg_changes: KGChanges, brain_id: str = "default"
+ ) -> KGChanges:
+ """
+ Save a KG changes to the data client.
+ """
+ return self.data.save_kg_changes(kg_changes, brain_id)
diff --git a/src/adapters/embeddings.py b/src/adapters/embeddings.py
index 5726ecf..4506e8c 100644
--- a/src/adapters/embeddings.py
+++ b/src/adapters/embeddings.py
@@ -68,16 +68,16 @@ class VectorStoreAdapter:
def search_similar_by_ids(
self,
vector_ids: list[str],
+ brain_id: str,
store: str,
min_similarity: float,
limit: int = 10,
- brain_id: str = "default",
) -> list[Vector]:
"""
Search similar vectors by their IDs.
"""
return self.vector_store.search_similar_by_ids(
- vector_ids, store, min_similarity, limit, brain_id
+ vector_ids, brain_id, store, min_similarity, limit
)
diff --git a/src/adapters/graph.py b/src/adapters/graph.py
index 636e09d..d6e94d1 100644
--- a/src/adapters/graph.py
+++ b/src/adapters/graph.py
@@ -8,7 +8,7 @@ Modified By: the developer formerly known as Christian Nonis at <alch.infoemail@
-----
"""
-from typing import Optional, Tuple
+from typing import Literal, Optional, Tuple
from src.adapters.interfaces.graph import GraphClient
from src.constants.kg import (
IdentificationParams,
@@ -247,5 +247,32 @@ class GraphAdapter:
brain_id, limit, skip, node_labels, node_uuids, query_text
)
+ def deprecate_relationship(
+ self,
+ subject: Node,
+ predicate: Predicate,
+ object: Node,
+ brain_id: str = "default",
+ ) -> Tuple[Node, Predicate, Node] | None:
+ """
+ Deprecate a relationship from the graph.
+ """
+ return self.graph.deprecate_relationship(subject, predicate, object, brain_id)
+
+ def update_properties(
+ self,
+ uuid: str,
+ updating: Literal["node", "relationship"],
+ brain_id: str = "default",
+ new_properties: dict = {},
+ properties_to_remove: list[str] = [],
+ ) -> Node | Predicate | None:
+ """
+ Update the properties of a node or relationship in the graph.
+ """
+ return self.graph.update_properties(
+ uuid, updating, brain_id, new_properties, properties_to_remove
+ )
+
_graph_adapter = GraphAdapter()
diff --git a/src/adapters/interfaces/data.py b/src/adapters/interfaces/data.py
index 3b070c1..24717db 100644
--- a/src/adapters/interfaces/data.py
+++ b/src/adapters/interfaces/data.py
@@ -13,7 +13,7 @@ from typing import List, Tuple
from pydantic import BaseModel
-from src.constants.data import Brain, Observation, StructuredData, TextChunk
+from src.constants.data import Brain, KGChanges, Observation, StructuredData, TextChunk
class SearchResult(BaseModel):
@@ -91,3 +91,10 @@ class DataClient(ABC):
Get the list of brains from the data client.
"""
raise NotImplementedError("get_brains_list method not implemented")
+
+ @abstractmethod
+ def save_kg_changes(self, kg_changes: KGChanges, brain_id: str) -> KGChanges:
+ """
+ Save a KG changes to the data client.
+ """
+ raise NotImplementedError("save_kg_changes method not implemented")
diff --git a/src/adapters/interfaces/graph.py b/src/adapters/interfaces/graph.py
index 16527ee..a4f514a 100644
--- a/src/adapters/interfaces/graph.py
+++ b/src/adapters/interfaces/graph.py
@@ -9,7 +9,7 @@ Modified By: the developer formerly known as Christian Nonis at <alch.infoemail@
"""
from abc import ABC, abstractmethod
-from typing import Optional, Tuple
+from typing import Literal, Optional, Tuple
from src.constants.kg import (
IdentificationParams,
@@ -245,3 +245,30 @@ class GraphClient(ABC):
Search the entities of the graph.
"""
raise NotImplementedError("search_entities method not implemented")
+
+ @abstractmethod
+ def deprecate_relationship(
+ self,
+ subject: Node,
+ predicate: Predicate,
+ object: Node,
+ brain_id: str,
+ ) -> Tuple[Node, Predicate, Node] | None:
+ """
+ Deprecate a relationship from the graph.
+ """
+ raise NotImplementedError("deprecate_relationship method not implemented")
+
+ @abstractmethod
+ def update_properties(
+ self,
+ uuid: str,
+ updating: Literal["node", "relationship"],
+ brain_id: str,
+ new_properties: dict,
+ properties_to_remove: list[str],
+ ) -> Node | Predicate | None:
+ """
+ Update the properties of a node or relationship in the graph.
+ """
+ raise NotImplementedError("update_properties method not implemented")
diff --git a/src/constants/data.py b/src/constants/data.py
index 62379fe..b2a2709 100644
--- a/src/constants/data.py
+++ b/src/constants/data.py
@@ -9,7 +9,8 @@ Modified By: the developer formerly known as Christian Nonis at <alch.infoemail@
"""
from datetime import datetime
-from typing import List, Optional
+from enum import Enum
+from typing import Annotated, Any, List, Literal, Optional, Union
import uuid
from pydantic import BaseModel, Field
@@ -62,24 +63,138 @@ class Observation(BaseModel):
)
-class KGChanges(BaseModel):
+class KGChangesType(Enum):
"""
- KG changes model.
+ KG changes type.
"""
- id: str = Field(default_factory=lambda: str(uuid.uuid4()))
+ RELATIONSHIP_CREATED = "relationship_created"
+ RELATIONSHIP_DEPRECATED = "relationship_deprecated"
+ NODE_PROPERTIES_UPDATED = "node_properties_updated"
+ RELATIONSHIP_PROPERTIES_UPDATED = "relationship_properties_updated"
+
+
+class PartialNode(BaseModel):
+ """
+ Partial node model.
+ """
- node_ids: Optional[List[str]] = Field(
- default=None, description="The id of the node that was changed."
+ uuid: str = Field(description="The id of the node.")
+ name: str = Field(description="The name of the node.")
+ labels: List[str] = Field(description="The labels of the node.")
+ description: Optional[str] = Field(description="The description of the node.")
+ properties: dict = Field(description="The properties of the node.")
+
+
+class PartialPredicate(BaseModel):
+ """
+ Partial relationship model.
+ """
+
+ uuid: str = Field(description="The id of the relationship.")
+ name: str = Field(description="The name of the relationship.")
+ description: Optional[str] = Field(
+ description="The description of the relationship."
+ )
+ properties: Optional[dict] = Field(
+ default=None, description="The properties of the relationship."
+ )
+
+
+class KGChangeLogRelationshipCreated(BaseModel):
+ """
+ KG change log relationship created model.
+ """
+
+ type: Literal[KGChangesType.RELATIONSHIP_CREATED] = Field(
+ default=KGChangesType.RELATIONSHIP_CREATED,
+ description="The type of the change.",
+ )
+ subject: PartialNode = Field(description="The subject of the relationship.")
+ predicate: PartialPredicate = Field(
+ description="The predicate of the relationship."
+ )
+ object: PartialNode = Field(description="The object of the relationship.")
+
+
+class KGChangeLogRelationshipDeprecated(BaseModel):
+ """
+ KG change log relationship deprecated model.
+ """
+
+ type: Literal[KGChangesType.RELATIONSHIP_DEPRECATED] = Field(
+ default=KGChangesType.RELATIONSHIP_DEPRECATED,
+ description="The type of the change.",
+ )
+ subject: PartialNode = Field(description="The subject of the relationship.")
+ predicate: PartialPredicate = Field(
+ description="The predicate of the relationship."
)
- predicate_id: Optional[str] = Field(
- default=None, description="The id of the predicate that was changed."
+ object: PartialNode = Field(description="The object of the relationship.")
+ new_predicate: Optional[PartialPredicate] = Field(
+ description="The new predicate of the relationship."
)
- changelog: List[dict] = Field(description="The changelog of the changes.")
- date: datetime = Field(
+
+class KGChangeLogPredicateUpdatedProperty(BaseModel):
+ """
+ KG change log relationship updated property model.
+ """
+
+ property: str = Field(description="The property that was updated.")
+ previous_value: Any = Field(description="The previous value of the property.")
+ new_value: Any = Field(description="The new value of the property.")
+
+
+class KGChangeLogNodePropertiesUpdated(BaseModel):
+ """
+ KG change log node properties updated model.
+ """
+
+ type: Literal[KGChangesType.NODE_PROPERTIES_UPDATED] = Field(
+ default=KGChangesType.NODE_PROPERTIES_UPDATED,
+ description="The type of the change.",
+ )
+ node: PartialNode = Field(description="The node that was updated.")
+ properties: List[KGChangeLogPredicateUpdatedProperty] = Field(
+ description="The properties that were updated."
+ )
+
+
+class KGChangeLogPredicatePropertiesUpdated(BaseModel):
+ """
+ KG change log relationship properties updated model.
+ """
+
+ type: Literal[KGChangesType.RELATIONSHIP_PROPERTIES_UPDATED] = Field(
+ default=KGChangesType.RELATIONSHIP_PROPERTIES_UPDATED,
+ description="The type of the change.",
+ )
+ predicate: PartialPredicate = Field(description="The predicate that was updated.")
+ properties: List[KGChangeLogPredicateUpdatedProperty] = Field(
+ description="The properties that were updated."
+ )
+
+
+class KGChanges(BaseModel):
+ """
+ KG changes model.
+ """
+
+ id: str = Field(default_factory=lambda: str(uuid.uuid4()))
+ type: KGChangesType = Field(description="The type of the changes.")
+ change: Annotated[
+ Union[
+ KGChangeLogRelationshipCreated,
+ KGChangeLogRelationshipDeprecated,
+ KGChangeLogNodePropertiesUpdated,
+ KGChangeLogPredicatePropertiesUpdated,
+ ],
+ Field(discriminator="type"),
+ ] = Field(description="The change data, discriminated by type.")
+ timestamp: datetime = Field(
default_factory=datetime.now,
- description="The date and time the changes were made.",
+ description="The timestamp of the changes.",
)
diff --git a/src/constants/kg.py b/src/constants/kg.py
index ea80b8f..c030070 100644
--- a/src/constants/kg.py
+++ b/src/constants/kg.py
@@ -48,6 +48,7 @@ class Predicate(BaseModel):
Predicate model.
"""
+ uuid: str = Field(default_factory=lambda: str(uuid.uuid4()))
name: str
description: str
last_updated: datetime = Field(
diff --git a/src/core/agents/kg_agent.py b/src/core/agents/kg_agent.py
index 0744c33..c346aed 100644
--- a/src/core/agents/kg_agent.py
+++ b/src/core/agents/kg_agent.py
@@ -26,8 +26,10 @@ from src.constants.prompts.kg_agent import (
)
from src.core.agents.tools.kg_agent import (
KGAgentAddTripletsTool,
+ KGAgentDeleteRelationshipTool,
KGAgentExecuteGraphOperationTool,
KGAgentSearchGraphTool,
+ KGAgentUpdatePropertiesTool,
)
from src.adapters.embeddings import EmbeddingsAdapter, VectorStoreAdapter
@@ -67,7 +69,9 @@ class KGAgent:
"use the appropriate syntax."
)
- def _get_tools(self, identification_params: dict, metadata: dict) -> List[BaseTool]:
+ def _get_tools(
+ self, identification_params: dict, metadata: dict, brain_id: str = "default"
+ ) -> List[BaseTool]:
return [
KGAgentAddTripletsTool(
self,
@@ -76,6 +80,7 @@ class KGAgent:
self.embeddings,
identification_params,
metadata,
+ brain_id=brain_id,
),
KGAgentSearchGraphTool(
self,
@@ -84,6 +89,18 @@ class KGAgent:
self.embeddings,
identification_params,
metadata,
+ brain_id=brain_id,
+ ),
+ KGAgentDeleteRelationshipTool(
+ self,
+ self.kg,
+ self.vector_store,
+ brain_id=brain_id,
+ ),
+ KGAgentUpdatePropertiesTool(
+ self,
+ self.kg,
+ brain_id=brain_id,
),
]
@@ -94,6 +111,7 @@ class KGAgent:
tools: Optional[List[BaseTool]] = None,
output_schema: Optional[BaseModel] = None,
extra_system_prompt: Optional[dict] = None,
+ brain_id: str = "default",
):
system_prompt = KG_AGENT_SYSTEM_PROMPT.format(
extra_system_prompt=extra_system_prompt if extra_system_prompt else ""
@@ -101,7 +119,11 @@ class KGAgent:
self.agent = create_agent(
model=self.llm_adapter.llm.langchain_model,
- tools=tools if tools else self._get_tools(identification_params, metadata),
+ tools=(
+ tools
+ if tools
+ else self._get_tools(identification_params, metadata, brain_id)
+ ),
system_prompt=system_prompt,
response_format=output_schema if output_schema else None,
)
@@ -117,12 +139,13 @@ class KGAgent:
metadata: Optional[dict],
identification_params: Optional[dict],
preferred_entities: Optional[list[str]],
+ brain_id: str = "default",
) -> str:
"""
Update the knowledge graph with new information.
"""
- self._get_agent(identification_params, metadata)
+ self._get_agent(identification_params, metadata, brain_id=brain_id)
preferred_entities_prompt = f"""
You must prioritize the extraction of the following entities: {preferred_entities},
@@ -151,13 +174,17 @@ class KGAgent:
return response
def structured_update_kg(
- self, main_node: Node, textual_data: dict, identification_params: dict
+ self,
+ main_node: Node,
+ textual_data: dict,
+ identification_params: dict,
+ brain_id: str = "default",
) -> str:
"""
Update the knowledge graph with new structured information.
"""
- self._get_agent(identification_params, metadata={})
+ self._get_agent(identification_params, metadata={}, brain_id=brain_id)
response = self.agent.invoke(
{
diff --git a/src/core/agents/tools/kg_agent/KGAgentAddTripletsTool.py b/src/core/agents/tools/kg_agent/KGAgentAddTripletsTool.py
index 700296b..0bda98a 100644
--- a/src/core/agents/tools/kg_agent/KGAgentAddTripletsTool.py
+++ b/src/core/agents/tools/kg_agent/KGAgentAddTripletsTool.py
@@ -14,8 +14,18 @@ from langchain.tools import BaseTool
from src.adapters.graph import GraphAdapter
from src.adapters.embeddings import EmbeddingsAdapter, VectorStoreAdapter
+from src.constants.data import (
+ PartialNode,
+ KGChangeLogNodePropertiesUpdated,
+ KGChangeLogPredicateUpdatedProperty,
+ KGChangeLogRelationshipCreated,
+ KGChanges,
+ KGChangesType,
+ PartialPredicate,
+)
from src.constants.kg import Node, Predicate, Triple
from src.services.api.constants.tool_schemas import TRIPLE_SCHEMA
+from src.services.data.main import data_adapter
from src.utils.nlp.names import most_similar_name_with_labels_or_none
@@ -31,6 +41,7 @@ class KGAgentAddTripletsTool(BaseTool):
embeddings: EmbeddingsAdapter
identification_params: Optional[dict] = None
metadata: Optional[dict] = None
+ brain_id: str = "default"
args_schema: dict = {
"type": "object",
@@ -51,6 +62,7 @@ class KGAgentAddTripletsTool(BaseTool):
embeddings: EmbeddingsAdapter,
identification_params: Optional[dict] = None,
metadata: Optional[dict] = None,
+ brain_id: str = "default",
):
description: str = (
"This tool is used to register triplets into the knowledge graph. "
@@ -64,6 +76,7 @@ class KGAgentAddTripletsTool(BaseTool):
description=description,
identification_params=identification_params or {},
metadata=metadata or {},
+ brain_id=brain_id or "default",
)
def _run(self, *args, **kwargs) -> str:
@@ -79,8 +92,12 @@ class KGAgentAddTripletsTool(BaseTool):
v_sub = self.embeddings.embed_text(subject.name)
v_obj = self.embeddings.embed_text(object_node.name)
- v_sim_sub = self.vector_store.search_vectors(v_sub.embeddings, "nodes", k=5)
- v_sim_obj = self.vector_store.search_vectors(v_obj.embeddings, "nodes", k=5)
+ v_sim_sub = self.vector_store.search_vectors(
+ v_sub.embeddings, "nodes", k=5, brain_id=self.brain_id
+ )
+ v_sim_obj = self.vector_store.search_vectors(
+ v_obj.embeddings, "nodes", k=5, brain_id=self.brain_id
+ )
sim_sub = most_similar_name_with_labels_or_none(
subject.name,
@@ -111,7 +128,9 @@ class KGAgentAddTripletsTool(BaseTool):
"labels": subject.labels,
"uuid": str(uuid4()),
}
- vector = self.vector_store.add_vectors([v_sub], store="nodes")
+ vector = self.vector_store.add_vectors(
+ [v_sub], store="nodes", brain_id=self.brain_id
+ )
subject.uuid = v_sub.metadata.get("uuid")
if sim_obj:
@@ -132,7 +151,9 @@ class KGAgentAddTripletsTool(BaseTool):
"labels": object_node.labels,
"uuid": str(uuid4()),
}
- vector = self.vector_store.add_vectors([v_obj], store="nodes")
+ vector = self.vector_store.add_vectors(
+ [v_obj], store="nodes", brain_id=self.brain_id
+ )
object_node.uuid = v_obj.metadata.get("uuid")
predicate = Predicate(
@@ -150,20 +171,72 @@ class KGAgentAddTripletsTool(BaseTool):
"node_ids": [triplet.subject.uuid, triplet.object.uuid],
"predicate": triplet.predicate.name,
}
- self.vector_store.add_vectors([vector], "triplets")
+ self.vector_store.add_vectors([vector], "triplets", brain_id=self.brain_id)
self.kg.add_nodes(
[triplet.subject, triplet.object],
+ brain_id=self.brain_id,
metadata=self.metadata,
)
+ sub_kg_changelog = KGChanges(
+ type=KGChangesType.NODE_PROPERTIES_UPDATED,
+ change=KGChangeLogNodePropertiesUpdated(
+ node=PartialNode(
+ **triplet.subject.model_dump(mode="json"),
+ ),
+ properties=[
+ KGChangeLogPredicateUpdatedProperty(
+ property=property,
+ previous_value=None,
+ new_value=triplet.subject.properties[property],
+ )
+ for property in triplet.subject.properties
+ ],
+ ),
+ )
+ obj_kg_changelog = KGChanges(
+ type=KGChangesType.NODE_PROPERTIES_UPDATED,
+ change=KGChangeLogNodePropertiesUpdated(
+ node=PartialNode(
+ **triplet.object.model_dump(mode="json"),
+ ),
+ properties=[
+ KGChangeLogPredicateUpdatedProperty(
+ property=property,
+ previous_value=None,
+ new_value=triplet.object.properties[property],
+ )
+ for property in triplet.object.properties
+ ],
+ ),
+ )
+ data_adapter.save_kg_changes(sub_kg_changelog, brain_id=self.brain_id)
+ data_adapter.save_kg_changes(obj_kg_changelog, brain_id=self.brain_id)
self.kg.add_relationship(
triplet.subject,
triplet.predicate,
triplet.object,
+ brain_id=self.brain_id,
)
+ kg_changes = KGChanges(
+ type=KGChangesType.RELATIONSHIP_CREATED,
+ change=KGChangeLogRelationshipCreated(
+ type=KGChangesType.RELATIONSHIP_CREATED,
+ subject=PartialNode(
+ **triplet.subject.model_dump(mode="json"),
+ ),
+ predicate=PartialPredicate(
+ uuid=triplet.predicate.uuid,
+ name=triplet.predicate.name,
+ description=triplet.predicate.description,
+ ),
+ object=PartialNode(
+ **triplet.object.model_dump(mode="json"),
+ ),
+ ),
+ )
+ data_adapter.save_kg_changes(kg_changes, brain_id=self.brain_id)
# TODO: save natural language relationship/predicate+s+o vector
- # TODO: add changelog relationship created
-
return f"Triplets added successfully: {triplets}"
diff --git a/src/core/agents/tools/kg_agent/KGAgentDeleteRelationshipTool.py b/src/core/agents/tools/kg_agent/KGAgentDeleteRelationshipTool.py
index 904267b..a39f59d 100644
--- a/src/core/agents/tools/kg_agent/KGAgentDeleteRelationshipTool.py
+++ b/src/core/agents/tools/kg_agent/KGAgentDeleteRelationshipTool.py
@@ -7,3 +7,127 @@ Last Modified: Thursday October 23rd 2025 9:29:22 pm
Modified By: the developer formerly known as Christian Nonis at <[email protected]>
-----
"""
+
+from typing import List, Optional, Tuple
+from uuid import uuid4
+from langchain.tools import BaseTool
+
+from src.adapters.graph import GraphAdapter
+from src.adapters.embeddings import EmbeddingsAdapter, VectorStoreAdapter
+from src.constants.data import (
+ KGChangeLogRelationshipDeprecated,
+ KGChanges,
+ KGChangesType,
+)
+from src.constants.kg import Node, Predicate
+from src.services.data.main import data_adapter
+
+
+class KGAgentDeleteRelationshipTool(BaseTool):
+ """
+ Tool for deleting a relationship from the knowledge graph.
+ """
+
+ name: str = "kg_agent_delete_relationship"
+ kg_agent: object
+ kg: GraphAdapter
+ vector_store: VectorStoreAdapter
+ brain_id: str = "default"
+
+ args_schema: dict = {
+ "type": "object",
+ "properties": {
+ "subject": {
+ "type": "object",
+ "properties": {
+ "labels": {
+ "type": "array",
+ "description": ("The labels of the subject node."),
+ "items": {
+ "type": "string",
+ },
+ },
+ "name": {
+ "type": "string",
+ "description": ("The name of the subject node."),
+ },
+ },
+ "required": ["labels", "name"],
+ },
+ "predicate": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": ("The name of the predicate."),
+ },
+ },
+ "required": ["name"],
+ },
+ "object": {
+ "type": "object",
+ "properties": {
+ "labels": {
+ "type": "array",
+ "description": ("The labels of the object node."),
+ "items": {
+ "type": "string",
+ },
+ },
+ "name": {
+ "type": "string",
+ "description": ("The name of the object node."),
+ },
+ },
+ "required": ["labels", "name"],
+ },
+ },
+ "required": ["subject", "predicate", "object"],
+ }
+
+ def __init__(
+ self,
+ kg_agent,
+ kg: GraphAdapter,
+ vector_store: VectorStoreAdapter,
+ brain_id: str = "default",
+ ):
+ description: str = (
+ "This tool is used to deprecate a relationship that is no longer valid from the knowledge graph. "
+ "Returns the relationship that was deprecated in the knowledge graph if it was found else returns an error message."
+ )
+ super().__init__(
+ kg_agent=kg_agent,
+ kg=kg,
+ vector_store=vector_store,
+ description=description,
+ brain_id=brain_id or "default",
+ )
+
+ def _run(self, *args, **kwargs) -> str:
+ subject = Node(**kwargs.get("subject"))
+ predicate = Predicate(**kwargs.get("predicate"))
+ object_node = Node(**kwargs.get("object"))
+
+ deprecated_relationship: Tuple[Node, Predicate, Node] | None = (
+ self.kg.deprecate_relationship(
+ subject,
+ predicate,
+ object_node,
+ brain_id=self.brain_id,
+ )
+ )
+ if deprecated_relationship:
+ kg_changes = KGChanges(
+ type=KGChangesType.RELATIONSHIP_DEPRECATED,
+ change=KGChangeLogRelationshipDeprecated(
+ type=KGChangesType.RELATIONSHIP_DEPRECATED,
+ subject=deprecated_relationship[0],
+ predicate=deprecated_relationship[1],
+ object=deprecated_relationship[2],
+ ),
+ )
+ data_adapter.save_kg_changes(kg_changes, brain_id=self.brain_id)
+ return f"Relationship deprecated successfully: {deprecated_relationship}"
+
+ return "Relationship not found in the knowledge graph."
diff --git a/src/core/agents/tools/kg_agent/KGAgentSearchGraphTool.py b/src/core/agents/tools/kg_agent/KGAgentSearchGraphTool.py
index 7edfa59..036f1fe 100644
--- a/src/core/agents/tools/kg_agent/KGAgentSearchGraphTool.py
+++ b/src/core/agents/tools/kg_agent/KGAgentSearchGraphTool.py
@@ -30,6 +30,7 @@ class KGAgentSearchGraphTool(BaseTool):
embeddings: EmbeddingsAdapter
identification_params: Optional[dict] = None
metadata: Optional[dict] = None
+ brain_id: str = "default"
args_schema: dict = {
"type": "object",
@@ -80,6 +81,7 @@ class KGAgentSearchGraphTool(BaseTool):
embeddings: EmbeddingsAdapter,
identification_params: Optional[dict] = None,
metadata: Optional[dict] = None,
+ brain_id: str = "default",
):
description: str = (
"Tool for searching the knowledge graph. "
@@ -98,6 +100,7 @@ class KGAgentSearchGraphTool(BaseTool):
description=description,
identification_params=identification_params or {},
metadata=metadata or {},
+ brain_id=brain_id,
)
def _run(self, *args, **kwargs) -> str:
@@ -108,12 +111,12 @@ class KGAgentSearchGraphTool(BaseTool):
if query:
query_embedding = self.embeddings.embed_text(query)
v_triplets_results = self.vector_store.search_vectors(
- query_embedding.embeddings, "triplets", k=5
+ query_embedding.embeddings, "triplets", k=5, brain_id=self.brain_id
)
v_nodes_results = self.vector_store.search_vectors(
- query_embedding.embeddings, "nodes"
+ query_embedding.embeddings, "nodes", brain_id=self.brain_id
)
- nodes.extend(self.kg.node_text_search(query))
+ nodes.extend(self.kg.node_text_search(query, brain_id=self.brain_id))
nodes.extend(
self.kg.get_by_uuids(
[
@@ -128,7 +131,8 @@ class KGAgentSearchGraphTool(BaseTool):
for node_id in v_triplet_result.metadata.get("node_ids", [])
if node_id is not None
],
- ]
+ ],
+ brain_id=self.brain_id,
)
)
@@ -136,7 +140,7 @@ class KGAgentSearchGraphTool(BaseTool):
Node(name=node["name"], labels=node["labels"])
for node in kwargs.get("nodes", [])
]
- nodes.extend(self.kg.search_graph(_nodes))
+ nodes.extend(self.kg.search_graph(_nodes, brain_id=self.brain_id))
nodes.extend(
self.kg.get_nodes_by_uuid(
@@ -148,6 +152,7 @@ class KGAgentSearchGraphTool(BaseTool):
for v_result in v_results
if v_result.metadata.get("predicate", None)
],
+ brain_id=self.brain_id,
)
)
diff --git a/src/core/agents/tools/kg_agent/KGAgentUpdateNodesTool.py b/src/core/agents/tools/kg_agent/KGAgentUpdateNodesTool.py
deleted file mode 100644
index 2c84d36..0000000
--- a/src/core/agents/tools/kg_agent/KGAgentUpdateNodesTool.py
+++ /dev/null
@@ -1,9 +0,0 @@
-"""
-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/KGAgentUpdatePropertiesTool.py b/src/core/agents/tools/kg_agent/KGAgentUpdatePropertiesTool.py
new file mode 100644
index 0000000..e6c6ef9
--- /dev/null
+++ b/src/core/agents/tools/kg_agent/KGAgentUpdatePropertiesTool.py
@@ -0,0 +1,101 @@
+"""
+File: /KGAgentUpdatePropertiesTool.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]>
+-----
+"""
+
+from langchain.tools import BaseTool
+
+from src.adapters.graph import GraphAdapter
+
+
+class KGAgentUpdatePropertiesTool(BaseTool):
+ """
+ Tool for updating the properties of a node or relationship in the knowledge graph.
+ """
+
+ name: str = "kg_agent_update_properties"
+ kg_agent: object
+ kg: GraphAdapter
+ brain_id: str = "default"
+
+ args_schema: dict = {
+ "type": "object",
+ "properties": {
+ "updating": {
+ "type": "string",
+ "description": ("What to update, a relationship or a node"),
+ "enum": ["relationship", "node"],
+ },
+ "uuid": {
+ "type": "string",
+ "description": ("The UUID of the node or relationship to update."),
+ },
+ "new_properties": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "property": {
+ "type": "string",
+ "description": ("The property to update."),
+ },
+ "value": {
+ "type": "string",
+ "description": ("The new value of the property."),
+ },
+ },
+ },
+ "description": ("The new properties to update."),
+ },
+ "properties_to_remove": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "description": ("The properties to remove."),
+ },
+ "description": ("The properties to remove."),
+ },
+ },
+ "required": ["updating", "uuid", "properties"],
+ }
+
+ def __init__(
+ self,
+ kg_agent: object,
+ kg: GraphAdapter,
+ brain_id: str = "default",
+ ):
+ description: str = (
+ "This tool is used to update the properties of a node or relationship in the knowledge graph. "
+ "Returns the node or relationship that was updated in the knowledge graph if it was found else returns an error message."
+ )
+ super().__init__(
+ kg_agent=kg_agent,
+ kg=kg,
+ description=description,
+ brain_id=brain_id or "default",
+ )
+
+ def _run(self, *args, **kwargs) -> str:
+ updating = kwargs.get("updating", "node")
+ uuid = kwargs.get("uuid", "")
+ new_properties = kwargs.get("new_properties", {})
+ properties_to_remove = kwargs.get("properties_to_remove", [])
+
+ updated_node_or_relationship = self.kg.update_properties(
+ uuid=uuid,
+ updating=updating,
+ brain_id=self.brain_id,
+ new_properties=new_properties,
+ properties_to_remove=properties_to_remove,
+ )
+
+ if updated_node_or_relationship:
+ return f"Node or relationship updated successfully: {updated_node_or_relationship}"
+ else:
+ return "Node or relationship not found"
diff --git a/src/core/agents/tools/kg_agent/__init__.py b/src/core/agents/tools/kg_agent/__init__.py
index c01c4df..2224de8 100644
--- a/src/core/agents/tools/kg_agent/__init__.py
+++ b/src/core/agents/tools/kg_agent/__init__.py
@@ -12,10 +12,14 @@ from .KGAgentExecuteGraphOperationTool import KGAgentExecuteGraphOperationTool
from .KGAgentAddNodesTool import KGAgentAddNodesTool
from .KGAgentAddTripletsTool import KGAgentAddTripletsTool
from .KGAgentSearchGraphTool import KGAgentSearchGraphTool
+from .KGAgentDeleteRelationshipTool import KGAgentDeleteRelationshipTool
+from .KGAgentUpdatePropertiesTool import KGAgentUpdatePropertiesTool
__all__ = [
"KGAgentExecuteGraphOperationTool",
"KGAgentAddNodesTool",
"KGAgentAddTripletsTool",
"KGAgentSearchGraphTool",
+ "KGAgentDeleteRelationshipTool",
+ "KGAgentUpdatePropertiesTool",
]
diff --git a/src/lib/milvus/client.py b/src/lib/milvus/client.py
index 8573cef..4b8df7d 100644
--- a/src/lib/milvus/client.py
+++ b/src/lib/milvus/client.py
@@ -113,7 +113,7 @@ class MilvusClient(VectorStoreClient):
index_params=index_params,
)
except Exception as e:
- pass
+ print(f"[Milvus] Error creating index for collection {store}: {e}")
try:
has_partition = self.client.has_partition(store, brain_id)
diff --git a/src/lib/mongo/client.py b/src/lib/mongo/client.py
index b7b3be5..124e155 100644
--- a/src/lib/mongo/client.py
+++ b/src/lib/mongo/client.py
@@ -14,7 +14,7 @@ from pymongo.database import Database
from pymongo.collection import Collection
from src.adapters.interfaces.data import DataClient, SearchResult
from src.config import config
-from src.constants.data import Brain, Observation, StructuredData, TextChunk
+from src.constants.data import Brain, KGChanges, Observation, StructuredData, TextChunk
class MongoClient(DataClient):
@@ -163,5 +163,10 @@ class MongoClient(DataClient):
for result in result
]
+ def save_kg_changes(self, kg_changes: KGChanges, brain_id: str) -> KGChanges:
+ collection = self.get_collection("kg_changes", database=brain_id)
+ collection.insert_one(kg_changes.model_dump(mode="json"))
+ return kg_changes
+
_mongo_client = MongoClient()
diff --git a/src/lib/neo4j/client.py b/src/lib/neo4j/client.py
index a24cf71..cbf0ee6 100644
--- a/src/lib/neo4j/client.py
+++ b/src/lib/neo4j/client.py
@@ -9,7 +9,7 @@ Modified By: the developer formerly known as Christian Nonis at <alch.infoemail@
"""
import os
-from typing import Any, Optional, Tuple
+from typing import Any, Literal, Optional, Tuple
from neo4j import GraphDatabase
from src.adapters.interfaces.graph import GraphClient
from src.config import config
@@ -91,7 +91,7 @@ class Neo4jClient(GraphClient):
Clean a property key to be used in a Cypher query.
"""
words = property_key.split()
- return "".join(word.capitalize() for word in words)
+ return words[0].lower() + "".join(word.capitalize() for word in words[1:])
def _format_property_key(self, property_key: str) -> str:
"""
@@ -225,11 +225,13 @@ class Neo4jClient(GraphClient):
safe_desc = predicate.description.replace("'", "\\'")
cypher_query = f"""
- MATCH (a:{":".join(self._clean_labels(subject.labels))}) WHERE a.Name = '{subject.name}'
- MATCH (b:{":".join(self._clean_labels(to_object.labels))}) WHERE b.Name = '{to_object.name}'
- CREATE (a)-[:{":".join(self._clean_labels([predicate.name]))} {{ Description: '{safe_desc}' }}]->(b)
+ MATCH (a:{":".join(self._clean_labels(subject.labels))}) WHERE a.name = '{subject.name}'
+ MATCH (b:{":".join(self._clean_labels(to_object.labels))}) WHERE b.name = '{to_object.name}'
+ MERGE (a)-[r:{":".join(self._clean_labels([predicate.name]))}]->(b)
+ ON CREATE SET r.description = '{safe_desc}', r.uuid = '{predicate.uuid}'
RETURN a, b
"""
+
self.ensure_database(brain_id)
result = self.driver.execute_query(cypher_query, database_=brain_id)
return result
@@ -243,7 +245,7 @@ class Neo4jClient(GraphClient):
queries = []
for node in nodes:
- query = f"""MATCH (n:{":".join(self._clean_labels(node.labels))}) WHERE n.Name = '{node.name}'
+ query = f"""MATCH (n:{":".join(self._clean_labels(node.labels))}) WHERE n.name = '{node.name}'
OPTIONAL MATCH (n)-[r*1]-(m)
RETURN n, r, m"""
queries.append(query)
@@ -259,7 +261,7 @@ class Neo4jClient(GraphClient):
"""
cypher_query = f"""
MATCH (n)
- WHERE toLower(n.Name) CONTAINS toLower('{text}')
+ WHERE toLower(n.name) CONTAINS toLower('{text}')
RETURN n
"""
self.ensure_database(brain_id)
@@ -440,12 +442,15 @@ class Neo4jClient(GraphClient):
where_clauses = []
for key, value in params_dict.items():
- where_clauses.append(f"n.{key} = '{value}'")
+ where_clauses.append(
+ f"n.{self._format_property_key(key)} = {self._format_value(value)}"
+ )
cypher_query = f"""
MATCH (n{(":" + ":".join(self._clean_labels(entity_types))) if entity_types else ""}) {("WHERE " + " AND ".join(where_clauses)) if where_clauses else ""}
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)
if not result.records or len(result.records) == 0:
@@ -712,9 +717,9 @@ class Neo4jClient(GraphClient):
if query_text:
if query_search_target == "all":
filters.append(
- f"(toLower(coalesce(n.name, n.Name, '')) CONTAINS toLower('{query_text}') OR "
- f"toLower(coalesce(m.name, m.Name, '')) CONTAINS toLower('{query_text}') OR "
- f"toLower(coalesce(r.description, r.Description, '')) CONTAINS toLower('{query_text}'))"
+ f"(toLower(coalesce(n.name, n.name, '')) CONTAINS toLower('{query_text}') OR "
+ f"toLower(coalesce(m.name, m.name, '')) CONTAINS toLower('{query_text}') OR "
+ f"toLower(coalesce(r.description, r.description, '')) CONTAINS toLower('{query_text}'))"
)
elif query_search_target == "node_name":
filters.append(f"toLower(n.name) CONTAINS toLower('{query_text}')")
@@ -854,7 +859,7 @@ class Neo4jClient(GraphClient):
filters.append(f"n.uuid IN [{','.join(node_uuids)}]")
if query_text:
filters.append(
- f"(toLower(coalesce(n.name, n.Name, '')) CONTAINS toLower('{query_text}'))"
+ f"(toLower(coalesce(n.name, n.name, '')) CONTAINS toLower('{query_text}'))"
)
cypher_query = f"""
MATCH (n)
@@ -903,5 +908,119 @@ class Neo4jClient(GraphClient):
)
return SearchEntitiesResult(results=nodes, total=total)
+ def deprecate_relationship(
+ self,
+ subject: Node,
+ predicate: Predicate,
+ object: Node,
+ brain_id: str,
+ ) -> Tuple[Node, Predicate, Node] | None:
+ """
+ Deprecate a relationship from the graph.
+ """
+ cypher_query = f"""
+ MATCH (a:{":".join(self._clean_labels(subject.labels))}) WHERE a.name = '{subject.name}'
+ MATCH (b:{":".join(self._clean_labels(object.labels))}) WHERE b.name = '{object.name}'
+ MATCH (a)-[r:{":".join(self._clean_labels([predicate.name]))}]->(b)
+ SET r.deprecated = true
+ RETURN a.uuid as a_uuid, a.name as a_name, labels(a) as a_labels, a.description as a_description, properties(a) as a_properties,
+ b.uuid as b_uuid, b.name as b_name, labels(b) as b_labels, b.description as b_description, properties(b) as b_properties,
+ r.uuid as r_uuid, type(r) as r_type, r.description as r_description, properties(r) as r_properties
+ """
+ self.ensure_database(brain_id)
+ result = self.driver.execute_query(cypher_query, database_=brain_id)
+ if result.records:
+ return (
+ Node(
+ uuid=result.records[0].get("a_uuid", "") or "",
+ name=result.records[0].get("a_name", "") or "",
+ labels=result.records[0].get("a_labels", []) or [],
+ description=result.records[0].get("a_description", "") or "",
+ properties=result.records[0].get("a_properties", {}) or {},
+ ),
+ Predicate(
+ name=result.records[0].get("r_type", "") or "",
+ description=result.records[0].get("r_description", "") or "",
+ direction=result.records[0].get("r_direction", "neutral"),
+ ),
+ Node(
+ uuid=result.records[0].get("b_uuid", "") or "",
+ name=result.records[0].get("b_name", "") or "",
+ labels=result.records[0].get("b_labels", []) or [],
+ description=result.records[0].get("b_description", "") or "",
+ properties=result.records[0].get("b_properties", {}) or {},
+ ),
+ )
+ return None
+
+ def update_properties(
+ self,
+ uuid: str,
+ updating: Literal["node", "relationship"],
+ brain_id: str,
+ new_properties: dict,
+ properties_to_remove: list[str],
+ ) -> Node | Predicate | None:
+ """
+ Update the properties of a node or relationship in the graph.
+ """
+
+ property_set_operations = []
+ for property, value in new_properties.items():
+ cypher_key = self._format_property_key(property)
+ formatted_value = self._format_value(value)
+ property_set_operations.append(f"t.{cypher_key} = {formatted_value}")
+
+ property_remove_operations = []
+ for property in properties_to_remove:
+ cypher_key = self._format_property_key(property)
+ property_remove_operations.append(f"t.{cypher_key}")
+
+ properties_set_op = (
+ f"SET {', '.join(property_set_operations)}"
+ if property_set_operations
+ else ""
+ )
+ properties_remove_op = (
+ f"REMOVE {', '.join(property_remove_operations)}"
+ if property_remove_operations
+ else ""
+ )
+
+ if updating == "node":
+ cypher_query = f"""
+ 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}'
+ {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)
+
+ if result.records:
+ if updating == "node":
+ 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 {},
+ )
+ elif updating == "relationship":
+ return Predicate(
+ name=result.records[0].get("rel_type", "") or "",
+ description=result.records[0].get("rel_description", "") or "",
+ direction=result.records[0].get("direction", "neutral"),
+ )
+ return None
+
_neo4j_client = Neo4jClient()
diff --git a/src/services/api/controllers/retrieve.py b/src/services/api/controllers/retrieve.py
index d9cd9a5..6628ef0 100644
--- a/src/services/api/controllers/retrieve.py
+++ b/src/services/api/controllers/retrieve.py
@@ -176,6 +176,7 @@ async def retrieve_neighbors(
# And the values are the similar nodes found, respectively
v_neighbors = vector_store_adapter.search_similar_by_ids(
vector_ids=related_node_ids,
+ brain_id=brain_id,
store="nodes",
min_similarity=0.2,
limit=(limit - len(normalized)) * 10,
diff --git a/src/services/api/routes/ingest.py b/src/services/api/routes/ingest.py
index 1838fe7..97a905f 100644
--- a/src/services/api/routes/ingest.py
+++ b/src/services/api/routes/ingest.py
@@ -40,7 +40,6 @@ async def ingest_structured_data(data: IngestionStructuredRequestBody):
"""
Ingest structured data to the processing pipeline and save to the memory.
"""
- print("[data]", data)
task = ingest_structured_data_task.delay(data.model_dump())
return JSONResponse(
diff --git a/src/services/api/routes/retrieve.py b/src/services/api/routes/retrieve.py
index 1701b3a..bb3112d 100644
--- a/src/services/api/routes/retrieve.py
+++ b/src/services/api/routes/retrieve.py
@@ -72,7 +72,9 @@ async def get_neighbors_with_identification_params(
Get the neighbors of an entity.
"""
return await retrieve_neighbors_controller(
- identification_params=request.identification_params, limit=request.limit
+ identification_params=request.identification_params,
+ limit=request.limit,
+ brain_id=request.brain_id,
)
diff --git a/src/workers/tasks/ingestion.py b/src/workers/tasks/ingestion.py
index cf7d0f0..aad08a1 100644
--- a/src/workers/tasks/ingestion.py
+++ b/src/workers/tasks/ingestion.py
@@ -10,7 +10,16 @@ Modified By: the developer formerly known as Christian Nonis at <alch.infoemail@
import json
from uuid import uuid4
-from src.constants.data import Observation, StructuredData, TextChunk
+from src.constants.data import (
+ KGChangeLogPredicateUpdatedProperty,
+ KGChanges,
+ KGChangesType,
+ Observation,
+ PartialNode,
+ StructuredData,
+ TextChunk,
+ KGChangeLogNodePropertiesUpdated,
+)
from src.constants.kg import Node
from src.services.api.constants.requests import IngestionStructuredRequestBody
from src.services.data.main import data_adapter
@@ -119,6 +128,7 @@ def ingest_data(self, args: dict):
metadata={**payload.meta_keys, "resource_id": text_chunk.id},
identification_params=payload.identification_params,
preferred_entities=payload.preferred_extraction_entities,
+ brain_id=payload.brain_id,
)
return self.request.id
@@ -153,6 +163,26 @@ def ingest_structured_data(self, args: dict):
identification_params=element.identification_params.model_dump(mode="json"),
metadata=element.textual_data,
)[0]
+
+ # Saving the node properties updated change
+ kg_changes = KGChanges(
+ type=KGChangesType.NODE_PROPERTIES_UPDATED,
+ change=KGChangeLogNodePropertiesUpdated(
+ node=PartialNode(
+ **node.model_dump(mode="json"),
+ ),
+ properties=[
+ KGChangeLogPredicateUpdatedProperty(
+ property=property,
+ previous_value=None,
+ new_value=node.properties[property],
+ )
+ for property in node.properties
+ ],
+ ),
+ )
+ data_adapter.save_kg_changes(kg_changes, brain_id=payload.brain_id)
+
vector = embeddings_adapter.embed_text(node.name)
vector.id = node.uuid
vector.metadata = {
@@ -245,6 +275,7 @@ def ingest_structured_data(self, args: dict):
main_node=node,
textual_data=element.textual_data,
identification_params=element.identification_params.model_dump(mode="json"),
+ brain_id=payload.brain_id,
)
return self.request.id