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.

📝 Add docstrings to `dev`

coderabbitai[bot]ec97004fb379
diff --git a/src/adapters/data.py b/src/adapters/data.py
index ac4cb96..9d1a9d8 100644
--- a/src/adapters/data.py
+++ b/src/adapters/data.py
@@ -141,7 +141,13 @@ class DataAdapter:
def get_observation_labels(self, brain_id: str = "default") -> list[str]:
"""
- Get all unique labels from observations.
+ Retrieve all unique observation labels for the specified brain.
+
+ Parameters:
+ brain_id (str): Identifier of the brain to query labels from.
+
+ Returns:
+ list[str]: All unique labels present in observations for the specified brain.
"""
return self.data.get_observation_labels(brain_id=brain_id)
@@ -149,7 +155,14 @@ class DataAdapter:
self, id: str, brain_id: str = "default"
) -> KGChanges:
"""
- Get changelog by ID.
+ Retrieve a changelog entry by its identifier.
+
+ Parameters:
+ id (str): Identifier of the changelog entry to retrieve.
+ brain_id (str): Brain namespace key to query; defaults to "default".
+
+ Returns:
+ KGChanges: The changelog entry matching the given `id`.
"""
return self.data.get_changelog_by_id(id=id, brain_id=brain_id)
@@ -162,12 +175,28 @@ class DataAdapter:
query_text: str = None
) -> list[KGChanges]:
"""
- Get a list of changelogs.
+ Retrieve a paginated list of knowledge-graph changelogs for a brain.
+
+ Parameters:
+ brain_id (str): Identifier of the brain to query.
+ limit (int): Maximum number of changelogs to return.
+ skip (int): Number of changelogs to skip (offset).
+ types (list[str] | None): If provided, restrict results to these changelog types.
+ query_text (str | None): If provided, filter changelogs by matching text.
+
+ Returns:
+ list[KGChanges]: Changelogs matching the filters and pagination parameters.
"""
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.
+ Retrieve distinct changelog types for a brain.
+
+ Parameters:
+ brain_id (str): Identifier of the brain to query; defaults to "default".
+
+ Returns:
+ list[str]: List of changelog type names.
"""
return self.data.get_changelog_types(brain_id=brain_id)
\ No newline at end of file
diff --git a/src/adapters/graph.py b/src/adapters/graph.py
index 11e4842..725c6d5 100644
--- a/src/adapters/graph.py
+++ b/src/adapters/graph.py
@@ -128,13 +128,22 @@ class GraphAdapter:
def get_graph_relationships(self, brain_id: str = "default") -> list[str]:
"""
- Get the relationships of the graph.
+ Retrieve the relationship types present in the graph.
+
+ Parameters:
+ brain_id (str): Identifier of the graph/brain to query.
+
+ Returns:
+ A list of relationship type names.
"""
return self.graph.get_graph_relationships(brain_id)
def get_by_uuid(self, uuid: str, brain_id: str = "default") -> Node:
"""
- Get a node by its UUID.
+ Retrieve the node with the specified UUID from the graph.
+
+ Returns:
+ Node: The node matching the provided UUID.
"""
return self.graph.get_by_uuid(uuid, brain_id)
@@ -262,7 +271,17 @@ class GraphAdapter:
properties_to_remove: list[str] = [],
) -> Node | Predicate | None:
"""
- Update the properties of a node or relationship in the graph.
+ Update properties on a graph node or relationship.
+
+ Parameters:
+ uuid (str): UUID of the node or relationship to update.
+ updating (Literal["node", "relationship"]): Target entity type to update.
+ brain_id (str): Identifier of the graph (defaults to "default").
+ new_properties (dict): Properties to add or replace on the entity.
+ properties_to_remove (list[str]): Names of properties to remove from the entity.
+
+ Returns:
+ Node | Predicate | None: The updated entity, or `None` if the entity was not found.
"""
return self.graph.update_properties(
uuid, updating, brain_id, new_properties, properties_to_remove
@@ -270,19 +289,31 @@ class GraphAdapter:
def get_graph_relationship_types(self, brain_id: str = "default") -> list[str]:
"""
- Get all unique relationship types from the graph.
+ Retrieve all relationship type names present in the graph.
+
+ Parameters:
+ brain_id (str): Identifier of the graph (brain) to query. Defaults to "default".
+
+ Returns:
+ list[str]: List of unique relationship type names found in the graph.
"""
return self.graph.get_graph_relationship_types(brain_id)
def get_graph_node_types(self, brain_id: str = "default") -> list[str]:
"""
Get all unique node types from the graph.
+
+ @returns:
+ A list of node type names available in the graph.
"""
return self.graph.get_graph_node_types(brain_id)
def get_graph_node_properties(self, brain_id: str = "default") -> list[str]:
"""
- Get all unique property keys from nodes in the graph.
+ Retrieve all unique node property keys present in the graph.
+
+ @returns
+ list[str]: A list of unique property key names present on nodes for the specified brain.
"""
return self.graph.get_graph_node_properties(brain_id)
@@ -297,7 +328,19 @@ class GraphAdapter:
properties_to_remove: Optional[list[str]] = None,
) -> Node | None:
"""
- Update an entity (node) in the graph.
+ Update an existing node's identifying fields, labels, and properties in the graph.
+
+ Parameters:
+ uuid (str): UUID of the node to update.
+ brain_id (str): Identifier of the brain/graph where the node resides.
+ new_name (Optional[str]): New name for the node; leave None to keep the current name.
+ new_description (Optional[str]): New description for the node; leave None to keep the current description.
+ new_labels (Optional[list[str]]): New set of labels for the node; provide to replace the node's labels.
+ new_properties (Optional[dict]): Properties to add or update on the node; keys are property names and values are their new values.
+ properties_to_remove (Optional[list[str]]): List of property names to remove from the node.
+
+ Returns:
+ Node | None: The updated node if the update succeeded, or `None` if the node was not found.
"""
return self.graph.update_node(
uuid,
@@ -309,4 +352,4 @@ class GraphAdapter:
properties_to_remove,
)
-_graph_adapter = GraphAdapter()
+_graph_adapter = GraphAdapter()
\ No newline at end of file
diff --git a/src/adapters/interfaces/data.py b/src/adapters/interfaces/data.py
index d541035..085fb4b 100644
--- a/src/adapters/interfaces/data.py
+++ b/src/adapters/interfaces/data.py
@@ -147,14 +147,27 @@ class DataClient(ABC):
@abstractmethod
def get_observation_labels(self, brain_id: str) -> list[str]:
"""
- Get all unique labels from observations.
+ Return all unique observation labels for the specified brain.
+
+ Parameters:
+ brain_id (str): Identifier of the brain whose observation labels should be retrieved.
+
+ Returns:
+ labels (list[str]): A list of unique label strings present in the brain's observations.
"""
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.
+ Retrieve a changelog entry by its identifier within a brain.
+
+ Parameters:
+ id (str): Identifier of the changelog to retrieve.
+ brain_id (str): Identifier of the brain that contains the changelog.
+
+ Returns:
+ KGChanges: The changelog entry matching the provided `id` in the specified `brain_id`.
"""
raise NotImplementedError("get_changelog_by_id method not implemented")
@@ -168,13 +181,29 @@ class DataClient(ABC):
query_text: str = None
) -> list[KGChanges]:
"""
- Get a list of changelogs.
+ Retrieve a paginated list of knowledge-graph changelogs for a brain.
+
+ Parameters:
+ brain_id (str): Identifier of the brain whose changelogs to retrieve.
+ limit (int): Maximum number of changelogs to return.
+ skip (int): Number of changelogs to skip (offset) for pagination.
+ types (list[str] | None): Optional list of changelog types to filter results by.
+ query_text (str | None): Optional text to filter changelogs by relevance or content.
+
+ Returns:
+ list[KGChanges]: A list of KGChanges matching the provided filters and pagination.
"""
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.
+ Return the set of unique changelog types associated with the specified brain.
+
+ Parameters:
+ brain_id (str): Identifier of the brain whose changelog types should be retrieved.
+
+ Returns:
+ list[str]: A list of unique changelog type names (order not guaranteed).
"""
raise NotImplementedError("get_changelog_types method not implemented")
\ No newline at end of file
diff --git a/src/adapters/interfaces/graph.py b/src/adapters/interfaces/graph.py
index 49d21e8..93b1165 100644
--- a/src/adapters/interfaces/graph.py
+++ b/src/adapters/interfaces/graph.py
@@ -117,7 +117,13 @@ class GraphClient(ABC):
@abstractmethod
def get_graph_relationships(self, brain_id: str) -> list[str]:
"""
- Get the relationships of the graph.
+ Retrieve the relationship types present in the specified graph.
+
+ Parameters:
+ brain_id (str): Identifier of the brain/graph to query.
+
+ Returns:
+ list[str]: Relationship type names present in the graph.
"""
raise NotImplementedError("get_graph_relationships method not implemented")
@@ -128,7 +134,14 @@ class GraphClient(ABC):
brain_id: str,
) -> Node:
"""
- Get a node by its UUID.
+ Retrieve a node identified by its UUID from the specified brain.
+
+ Parameters:
+ uuid (str): The node's UUID.
+ brain_id (str): Identifier of the brain/graph to query.
+
+ Returns:
+ Node: The node matching the given UUID.
"""
raise NotImplementedError("get_by_uuid method not implemented")
@@ -262,28 +275,56 @@ class GraphClient(ABC):
properties_to_remove: list[str],
) -> Node | Predicate | None:
"""
- Update the properties of a node or relationship in the graph.
+ Update properties on a graph node or relationship.
+
+ Parameters:
+ uuid (str): UUID of the target node or relationship.
+ updating (Literal["node", "relationship"]): Whether to update a node's properties or a relationship's properties.
+ brain_id (str): Identifier of the graph/brain where the entity resides.
+ new_properties (dict): Properties to set or overwrite on the target entity.
+ properties_to_remove (list[str]): Property keys to remove from the target entity.
+
+ Returns:
+ Node | Predicate | None: The updated node or relationship object if the update succeeds, or `None` if no entity was found or no update was performed.
"""
raise NotImplementedError("update_properties method not implemented")
@abstractmethod
def get_graph_relationship_types(self, brain_id: str) -> list[str]:
"""
- Get all unique relationship types from the graph.
+ List unique relationship types present in the specified graph.
+
+ Parameters:
+ brain_id (str): Identifier of the graph/brain to query.
+
+ Returns:
+ relationship_types (list[str]): Relationship type names present in the graph.
"""
raise NotImplementedError("get_graph_relationship_types method not implemented")
@abstractmethod
def get_graph_node_types(self, brain_id: str) -> list[str]:
"""
- Get all unique node types from the graph.
+ Return all unique node types (labels) present in the graph for the given brain.
+
+ Parameters:
+ brain_id (str): Identifier of the brain/graph to query.
+
+ Returns:
+ list[str]: A list of node type names (labels) present in the specified graph.
"""
raise NotImplementedError("get_graph_node_types method not implemented")
@abstractmethod
def get_graph_node_properties(self, brain_id: str) -> list[str]:
"""
- Get all unique property keys from nodes in the graph.
+ Retrieve all unique node property keys present in the graph for the given brain.
+
+ Parameters:
+ brain_id (str): Identifier of the graph/brain to query.
+
+ Returns:
+ list[str]: Unique property key names found on nodes in the specified graph.
"""
raise NotImplementedError("get_graph_node_properties method not implemented")
@@ -299,6 +340,18 @@ class GraphClient(ABC):
properties_to_remove: Optional[list[str]] = None,
) -> Node | None:
"""
- Update an entity (node) in the graph.
+ Update a node's identifying fields, labels, and properties in the graph.
+
+ Parameters:
+ uuid (str): UUID of the node to update.
+ brain_id (str): Identifier of the graph/brain where the node resides.
+ new_name (Optional[str]): New name for the node; if omitted, name is unchanged.
+ new_description (Optional[str]): New description for the node; if omitted, description is unchanged.
+ new_labels (Optional[list[str]]): New set of labels for the node; if provided, replaces existing labels.
+ new_properties (Optional[dict]): Properties to add or update on the node; keys with values will be set or overwritten.
+ properties_to_remove (Optional[list[str]]): List of property keys to remove from the node.
+
+ Returns:
+ Node | None: The updated Node if the node was found and modified, `None` if no matching node exists.
"""
raise NotImplementedError("update_entity method not implemented")
\ No newline at end of file
diff --git a/src/core/agents/kg_agent.py b/src/core/agents/kg_agent.py
index 047fc48..13461d8 100644
--- a/src/core/agents/kg_agent.py
+++ b/src/core/agents/kg_agent.py
@@ -207,7 +207,15 @@ class KGAgent:
self, node: Node, looking_for: Optional[str], limit: int
) -> RetrieveNeighborsOutputSchema:
"""
- Retrieve the neighbors of a node.
+ Retrieve neighbors and related information for a given node using the KG agent.
+
+ Parameters:
+ node (Node): The main node for which neighbors should be retrieved.
+ looking_for (Optional[str or Iterable[str]]): One or more reasons or search hints the agent should prioritize when selecting neighbors. When provided as a sequence, each element is treated as a separate reason.
+ limit (int): Maximum number of neighbor results the agent should return.
+
+ Returns:
+ RetrieveNeighborsOutputSchema: The agent-produced structured neighbor information and associated metadata.
"""
graph_db_prop_keys = self.kg.get_graph_node_properties()
@@ -259,4 +267,4 @@ class KGAgent:
response = _response.get("structured_response")
- return response
+ return response
\ No newline at end of file
diff --git a/src/core/search/entities.py b/src/core/search/entities.py
index e97f063..24a437c 100644
--- a/src/core/search/entities.py
+++ b/src/core/search/entities.py
@@ -21,7 +21,17 @@ def search_entities(
brain_id: str = "default",
) -> SearchEntitiesResult:
"""
- Search the entities of the graph.
+ Search entities in the knowledge graph.
+
+ Parameters:
+ limit (int): Maximum number of entities to return.
+ skip (int): Number of entities to skip (offset) for pagination.
+ node_labels (Optional[list[str]]): Filter results to nodes matching any of these labels.
+ query_text (Optional[str]): Text to match against entity properties or content.
+ brain_id (str): Identifier of the graph/brain to query.
+
+ Returns:
+ SearchEntitiesResult: Result object containing matched entities and pagination metadata.
"""
result = graph_adapter.search_entities(
brain_id, limit, skip, node_labels, query_text
diff --git a/src/core/search/relationships.py b/src/core/search/relationships.py
index f0bc70a..8f6d3a5 100644
--- a/src/core/search/relationships.py
+++ b/src/core/search/relationships.py
@@ -24,7 +24,20 @@ def search_relationships(
brain_id: str = "default",
) -> SearchRelationshipsResult:
"""
- Search the relationships of the graph.
+ Search for relationships in the knowledge graph using optional filters and full-text query.
+
+ Parameters:
+ limit (int): Maximum number of relationship records to return.
+ skip (int): Number of matching records to skip (offset).
+ relationship_types (list[str] | None): List of relationship type names to include; when None, all types are allowed.
+ from_node_labels (list[str] | None): List of labels to filter source nodes; when None, any source node label is allowed.
+ to_node_labels (list[str] | None): List of labels to filter target nodes; when None, any target node label is allowed.
+ query_text (str | None): Full-text query string applied to the specified search target; when None, no full-text filtering is applied.
+ query_search_target (str | None): Field to apply the full-text query to (e.g., "all", "from", "to", "relationship"); defaults to "all".
+ brain_id (str): Identifier of the brain/graph context to search within.
+
+ Returns:
+ SearchRelationshipsResult: Search results containing matching relationships and associated metadata.
"""
result = graph_adapter.search_relationships(
brain_id,
diff --git a/src/lib/mongo/client.py b/src/lib/mongo/client.py
index 0a3eaf4..97d819f 100644
--- a/src/lib/mongo/client.py
+++ b/src/lib/mongo/client.py
@@ -271,6 +271,15 @@ class MongoClient(DataClient):
]
def get_observation_labels(self, brain_id: str) -> list[str]:
+ """
+ Return the list of unique observation labels for the specified brain, sorted lexicographically.
+
+ Parameters:
+ brain_id (str): Name/key of the brain used as the MongoDB database to query.
+
+ Returns:
+ list[str]: Sorted list of distinct label strings found in observations' metadata.labels.
+ """
collection = self.get_collection("observations", database=brain_id)
pipeline = [
{"$match": {"metadata.labels": {"$exists": True}}},
@@ -284,6 +293,20 @@ class MongoClient(DataClient):
def get_changelog_by_id(
self, id: str, brain_id: str
) -> KGChanges:
+ """
+ Retrieve a changelog entry by id from the specified brain's kg_changes collection.
+
+ If a document is found, convert string values of the nested `change.type` and the top-level `type`
+ fields to the `KGChangesType` enum when present, then validate and return a `KGChanges` model.
+ Returns `None` if no matching document exists.
+
+ Parameters:
+ id (str): The changelog document id to retrieve.
+ brain_id (str): The brain (database) name where the kg_changes collection resides.
+
+ Returns:
+ KGChanges or None: The validated `KGChanges` model for the found document, or `None` if not found.
+ """
from src.constants.data import KGChangesType
collection = self.get_collection("kg_changes", database=brain_id)
@@ -308,6 +331,19 @@ class MongoClient(DataClient):
types: list[str] = None,
query_text: str = None
) -> list[KGChanges]:
+ """
+ Retrieve changelog entries for a brain with optional type filtering and text search.
+
+ Parameters:
+ brain_id (str): Identifier of the brain (database) to query.
+ limit (int): Maximum number of changelogs to return.
+ skip (int): Number of changelogs to skip (offset).
+ types (list[str] | None): If provided, restrict results to changelogs whose top-level `type` is in this list.
+ query_text (str | None): If provided, perform a case-insensitive substring search on the `change` and `type` fields.
+
+ Returns:
+ list[KGChanges]: Changelogs validated into `KGChanges` models, sorted by `timestamp` descending. Entries that fail model validation are skipped (an error message is printed). String values in nested `change.type` and top-level `type` are converted to `KGChangesType` when applicable.
+ """
from src.constants.data import KGChangesType
collection = self.get_collection("kg_changes", database=brain_id)
@@ -341,6 +377,15 @@ class MongoClient(DataClient):
return changelogs
def get_changelog_types(self, brain_id: str) -> list[str]:
+ """
+ Retrieve the sorted list of distinct changelog types for a brain.
+
+ Parameters:
+ brain_id (str): Identifier of the brain (database name) to query.
+
+ Returns:
+ list[str]: Changelog type strings sorted in ascending order.
+ """
collection = self.get_collection("kg_changes", database=brain_id)
pipeline = [
{"$group": {"_id": "$type"}},
@@ -349,4 +394,4 @@ class MongoClient(DataClient):
results = collection.aggregate(pipeline)
return [result["_id"] for result in results]
-_mongo_client = MongoClient()
+_mongo_client = MongoClient()
\ No newline at end of file
diff --git a/src/lib/neo4j/client.py b/src/lib/neo4j/client.py
index 9ed1941..0a389c9 100644
--- a/src/lib/neo4j/client.py
+++ b/src/lib/neo4j/client.py
@@ -432,7 +432,15 @@ class Neo4jClient(GraphClient):
entity_types: Optional[list[str]] = None,
) -> Node:
"""
- Get a node by its identification params and entity types.
+ Finds a node matching the provided identification parameters and optional entity types.
+
+ Parameters:
+ identification_params (IdentificationParams): Identification fields used to locate the node (model_dump is used to build WHERE clauses).
+ brain_id (str): Target database identifier to query.
+ entity_types (list[str], optional): Node labels to restrict the match; when provided, the search matches nodes with any of these labels.
+
+ Returns:
+ Node or None: The matching Node populated with uuid, name, labels, description, and properties, or `None` if no node is found.
"""
params_dict = identification_params.model_dump(
@@ -467,7 +475,13 @@ class Neo4jClient(GraphClient):
self, node: Node, limit: int, brain_id: str
) -> list[Tuple[Node, Predicate, Node]]:
"""
- Get the neighbors of a node.
+ Retrieve neighbor triples for the given node where the neighbor shares at least one label with the source node.
+
+ Returns:
+ list[Tuple[Node, Predicate, Node]]: A list of tuples (neighbor_node, predicate, intermediate_node) where
+ - neighbor_node is the matched neighbor (node m),
+ - predicate describes the relationship r2 between the intermediate node and the neighbor (including direction),
+ - intermediate_node is the connector node (c) through which the neighbor is reached.
"""
cypher_query = f"""
@@ -950,7 +964,19 @@ class Neo4jClient(GraphClient):
properties_to_remove: list[str],
) -> Node | Predicate | None:
"""
- Update the properties of a node or relationship in the graph.
+ Update properties on a node or relationship identified by UUID.
+
+ Sets and/or removes properties on the matched entity and returns the updated representation.
+
+ Parameters:
+ uuid (str): UUID of the node or relationship to update.
+ updating (Literal["node", "relationship"]): Whether to update a node or a relationship.
+ brain_id (str): Target database identifier.
+ new_properties (dict): Mapping of property keys to values to set or update on the entity.
+ properties_to_remove (list[str]): List of property keys to remove from the entity.
+
+ Returns:
+ Node | Predicate | None: A `Node` when a node was updated, a `Predicate` when a relationship was updated, or `None` if no matching entity was found.
"""
property_set_operations = []
@@ -1012,7 +1038,13 @@ class Neo4jClient(GraphClient):
def get_graph_relationship_types(self, brain_id: str) -> list[str]:
"""
- Get all unique relationship types from the graph.
+ Return all relationship type names present in the specified brain (database).
+
+ Parameters:
+ brain_id (str): Target database name to query for relationship types.
+
+ Returns:
+ list[str]: A list of relationship type names found in the graph.
"""
cypher_query = """
CALL db.relationshipTypes() YIELD relationshipType
@@ -1024,7 +1056,13 @@ class Neo4jClient(GraphClient):
def get_graph_node_types(self, brain_id: str) -> list[str]:
"""
- Get all unique node types from the graph.
+ Return the set of node label types present in the specified graph database.
+
+ Parameters:
+ brain_id (str): The target database/graph identifier to query.
+
+ Returns:
+ list[str]: A list of node label strings found in the database.
"""
cypher_query = """
CALL db.labels() YIELD label
@@ -1036,7 +1074,10 @@ class Neo4jClient(GraphClient):
def get_graph_node_properties(self, brain_id: str) -> list[str]:
"""
- Get all unique property keys from nodes in the graph.
+ Return all distinct node property keys present in the database, ordered alphabetically.
+
+ Returns:
+ properties (list[str]): Sorted list of distinct property key names used on nodes.
"""
cypher_query = """
MATCH (n)
@@ -1059,11 +1100,21 @@ class Neo4jClient(GraphClient):
properties_to_remove: Optional[list[str]] = None,
) -> Node | None:
"""
- Update an entity (node) in the graph.
- When new_properties is passed, it compares with existing properties:
- - Adds new properties that don't exist
- - Updates properties that have changed
- - Keeps existing properties that aren't in new_properties
+ Update the node identified by `uuid` with the provided name, description, labels, and property changes.
+
+ If `new_properties` is provided, only properties that are new or whose values differ from the existing node are set; existing properties not mentioned are left unchanged. If `properties_to_remove` is provided, those properties are removed. If `new_labels` is provided, existing labels are removed (if the node was loaded) and replaced with the cleaned `new_labels`. If no changes are specified, the function returns the existing node (or None if not found) without executing an update.
+
+ Parameters:
+ uuid (str): UUID of the node to update.
+ brain_id (str): Target database/brain identifier.
+ new_name (Optional[str]): New value for the node's `name` property.
+ new_description (Optional[str]): New value for the node's `description` property.
+ new_labels (Optional[list[str]]): New labels to assign to the node; labels will be cleaned and applied.
+ new_properties (Optional[dict]): Properties to add or update; only keys that are new or changed are applied when the existing node can be loaded.
+ properties_to_remove (Optional[list[str]]): Property keys to remove from the node.
+
+ Returns:
+ Node or None: The updated Node when the update succeeds, the existing Node if no changes were requested, or `None` if the node does not exist or no update occurred.
"""
operations = []
@@ -1144,4 +1195,4 @@ class Neo4jClient(GraphClient):
return None
-_neo4j_client = Neo4jClient()
+_neo4j_client = Neo4jClient()
\ No newline at end of file
diff --git a/src/services/api/controllers/changelogs.py b/src/services/api/controllers/changelogs.py
index 18190d1..380c606 100644
--- a/src/services/api/controllers/changelogs.py
+++ b/src/services/api/controllers/changelogs.py
@@ -17,9 +17,30 @@ async def get_changelog_by_id(
id: str, brain_id: str = "default"
):
"""
- Get changelog by ID.
+ Retrieve a changelog by its ID for a specified brain.
+
+ Parameters:
+ id (str): Identifier of the changelog to retrieve.
+ brain_id (str): Identifier of the brain to query; defaults to "default".
+
+ Returns:
+ JSONResponse: Response with a payload containing:
+ - message (str): "Changelog retrieved successfully"
+ - changelog (dict): The changelog serialized as JSON.
+
+ Raises:
+ HTTPException: Raised with status code 404 if the changelog is not found.
"""
def _get_changelog():
+ """
+ Retrieve the changelog with the given ID for the current brain, raising a 404 error if it does not exist.
+
+ Raises:
+ HTTPException: with status 404 and detail "Changelog not found" when no changelog is found.
+
+ Returns:
+ The retrieved changelog model instance.
+ """
changelog = data_adapter.get_changelog_by_id(id, brain_id)
if not changelog:
raise HTTPException(status_code=404, detail="Changelog not found")
@@ -42,9 +63,28 @@ async def get_changelogs_list(
brain_id: str = "default",
):
"""
- Get a list of changelogs.
+ Retrieve a paginated, optionally filtered list of changelogs for a brain.
+
+ Parameters:
+ limit (int): Maximum number of changelogs to return.
+ skip (int): Number of changelogs to skip (offset).
+ types (Optional[list[str]]): If provided, restrict results to these changelog types.
+ query_text (Optional[str]): If provided, filter changelogs by matching text.
+ brain_id (str): Identifier of the brain from which to fetch changelogs.
+
+ Returns:
+ JSONResponse: Response content contains:
+ - message: Success message string.
+ - changelogs: List of changelog objects serialized as JSON.
+ - count: Integer count of returned changelogs.
"""
def _get_list():
+ """
+ Retrieve a list of changelog entries using the surrounding scope's filters and pagination.
+
+ Returns:
+ list: Changelog objects matching the provided brain_id, limit, skip, types, and query_text.
+ """
return data_adapter.get_changelogs_list(
brain_id, limit, skip, types, query_text
)
@@ -63,9 +103,24 @@ async def get_changelog_types(
brain_id: str = "default",
):
"""
- Get all unique types from changelogs.
+ Retrieve all unique changelog types for a given brain.
+
+ Parameters:
+ brain_id (str): Identifier of the brain to query; defaults to "default".
+
+ Returns:
+ JSONResponse: Response content contains:
+ - message (str): Success message.
+ - types (list[str]): List of unique changelog types.
+ - count (int): Number of types returned.
"""
def _get_types():
+ """
+ Retrieve the list of unique changelog types for the current brain.
+
+ Returns:
+ list[str]: A list of changelog type names.
+ """
return data_adapter.get_changelog_types(brain_id)
results = await asyncio.to_thread(_get_types)
diff --git a/src/services/api/controllers/meta.py b/src/services/api/controllers/meta.py
index 00986b5..78de7c7 100644
--- a/src/services/api/controllers/meta.py
+++ b/src/services/api/controllers/meta.py
@@ -14,21 +14,39 @@ from src.services.kg_agent.main import graph_adapter
async def get_entities_labels(brain_id: str):
"""
- Get the entity properties of the graph.
+ Retrieve node labels (types) for the graph identified by `brain_id`.
+
+ Parameters:
+ brain_id (str): Identifier of the brain/graph to query.
+
+ Returns:
+ list[str]: Node label/type names present in the graph.
"""
result = await asyncio.to_thread(graph_adapter.get_graph_node_types, brain_id)
return result
async def get_relationships_properties(brain_id: str):
"""
- Get the entity properties of the graph.
+ Retrieve relationship types and their property keys for the graph associated with the given brain.
+
+ Parameters:
+ brain_id (str): Identifier of the brain whose graph to query.
+
+ Returns:
+ relationship_properties: A collection mapping relationship types to their associated property keys.
"""
result = await asyncio.to_thread(graph_adapter.get_graph_relationship_types, brain_id)
return result
async def get_entity_properties(brain_id: str):
"""
- Get all unique property keys from entities in the graph.
+ Retrieve all unique property keys for node entities in the specified graph.
+
+ Parameters:
+ brain_id (str): Identifier of the brain/graph to query.
+
+ Returns:
+ list[str]: Unique property key names present on nodes in the graph.
"""
result = await asyncio.to_thread(graph_adapter.get_graph_node_properties, brain_id)
return result
\ No newline at end of file
diff --git a/src/services/api/controllers/model.py b/src/services/api/controllers/model.py
index 65c3a23..35a8aa0 100644
--- a/src/services/api/controllers/model.py
+++ b/src/services/api/controllers/model.py
@@ -20,7 +20,18 @@ async def add_nodes(
metadata: Optional[dict] = None,
) -> list[Node] | str:
"""
- Add multiple nodes to the graph.
+ Create and add multiple Node objects to the graph.
+
+ Each input dict is converted into a Node (a new UUID is generated for each) and then added to the graph via the graph adapter.
+
+ Parameters:
+ nodes (list[dict]): List of node data dicts. Expected keys include `name`, optional `labels` (list), optional `description`, and optional `properties` (dict).
+ brain_id (str): Identifier for the target brain/graph.
+ identification_params (dict, optional): Parameters used to identify existing nodes for deduplication or matching; passed through to the graph adapter.
+ metadata (dict, optional): Additional metadata forwarded to the graph adapter.
+
+ Returns:
+ list[Node] | str: The list of added Node objects, or a string result as returned by the graph adapter.
"""
from src.constants.kg import Node
import uuid as uuid_lib
@@ -55,7 +66,21 @@ async def update_node(
properties_to_remove: Optional[list[str]] = None,
) -> Node | None:
"""
- Update an entity (node) in the graph.
+ Update fields of a node in the graph.
+
+ Only the provided parameters will be applied to the node; omitted optional parameters are left unchanged.
+
+ Parameters:
+ uuid (str): UUID of the node to update.
+ brain_id (str): Identifier of the brain/graph where the node resides.
+ new_name (Optional[str]): New name for the node.
+ new_description (Optional[str]): New description for the node.
+ new_labels (Optional[list[str]]): Labels to assign to the node.
+ new_properties (Optional[dict]): Properties to set or update on the node.
+ properties_to_remove (Optional[list[str]]): List of property keys to remove from the node.
+
+ Returns:
+ Node | None: The updated Node if it exists, `None` if no node with the given UUID was found.
"""
result = await asyncio.to_thread(
graph_adapter.update_node,
@@ -78,7 +103,17 @@ async def add_relationship(
brain_id: str,
) -> str:
"""
- Add a relationship between two nodes in the graph.
+ Create a predicate relationship between two nodes identified by UUIDs within the specified brain.
+
+ Parameters:
+ subject_uuid (str): UUID of the subject node.
+ predicate_name (str): Name of the predicate (relationship).
+ predicate_description (str): Description for the predicate.
+ object_uuid (str): UUID of the object node.
+ brain_id (str): Identifier of the brain/graph where the relationship will be created.
+
+ Returns:
+ str: Adapter result for the created relationship (typically the relationship identifier).
"""
subject_node = await asyncio.to_thread(
graph_adapter.get_by_uuid,
@@ -123,7 +158,16 @@ async def update_relationship(
properties_to_remove: list[str],
) -> Predicate | None:
"""
- Update a relationship's properties in the graph.
+ Update properties of an existing relationship identified by its UUID.
+
+ Parameters:
+ uuid (str): UUID of the relationship to update.
+ brain_id (str): Identifier of the brain/graph scope where the relationship exists.
+ new_properties (dict): Properties to add or update on the relationship.
+ properties_to_remove (list[str]): List of property names to remove from the relationship.
+
+ Returns:
+ Predicate | None: The updated Predicate object if the relationship was found and updated, `None` otherwise.
"""
result = await asyncio.to_thread(
graph_adapter.update_properties,
diff --git a/src/services/api/controllers/retrieve.py b/src/services/api/controllers/retrieve.py
index b6f2325..56793e1 100644
--- a/src/services/api/controllers/retrieve.py
+++ b/src/services/api/controllers/retrieve.py
@@ -337,7 +337,23 @@ async def get_relationships(
brain_id: str = "default",
):
"""
- Get the relationships of the graph.
+ Retrieve relationships from the knowledge graph with optional filtering and pagination.
+
+ Parameters:
+ relationship_types (list[str], optional): Filter results to specific relationship types.
+ from_node_labels (list[str], optional): Filter relationships originating from nodes with these labels.
+ to_node_labels (list[str], optional): Filter relationships targeting nodes with these labels.
+ query_text (str, optional): Text to search within relationship or node content.
+ query_search_target (str, optional): Field to target for text search; commonly "all", "from", or "to".
+ limit (int, optional): Maximum number of relationships to return.
+ skip (int, optional): Number of relationships to skip (offset).
+ brain_id (str, optional): Identifier of the brain/graph to query.
+
+ Returns:
+ JSONResponse: A response whose JSON content contains:
+ - message: Confirmation string.
+ - relationships: List of serialized relationship objects.
+ - total: Total number of matching relationships.
"""
relationships = await asyncio.to_thread(
search_relationships,
@@ -367,7 +383,20 @@ async def get_entities(
brain_id: str = "default",
):
"""
- Get the entities of the graph.
+ Retrieve entities from the knowledge graph with optional label and text filters.
+
+ Parameters:
+ limit (int): Maximum number of entities to return (pagination).
+ skip (int): Number of entities to skip (pagination offset).
+ node_labels (Optional[list[str]]): If provided, only return entities whose labels match any value in this list.
+ query_text (Optional[str]): If provided, filter entities by matching text content.
+ brain_id (str): Identifier of the knowledge graph/brain to query.
+
+ Returns:
+ JSONResponse: Object containing:
+ - message (str): Informational message.
+ - entities (list): Serialized entity objects.
+ - total (int): Total number of matching entities.
"""
entities = await asyncio.to_thread(
search_entities, limit, skip, node_labels, query_text, brain_id
diff --git a/src/services/api/routes/meta.py b/src/services/api/routes/meta.py
index 2051f35..ed13c3c 100644
--- a/src/services/api/routes/meta.py
+++ b/src/services/api/routes/meta.py
@@ -23,7 +23,13 @@ async def get_relationships_properties(
brain_id: str = "default",
):
"""
- Get all unique relationship types from the graph.
+ Retrieve all unique relationship types present in the graph for the specified brain.
+
+ Parameters:
+ brain_id (str): Identifier of the brain/graph to query. Defaults to "default".
+
+ Returns:
+ A list of relationship type names (strings) found in the specified graph.
"""
return await get_relationships_properties_controller(brain_id)
@@ -32,7 +38,13 @@ async def get_entities_labels(
brain_id: str = "default",
):
"""
- Get all unique node labels from the graph.
+ Retrieve all unique node labels present in the graph.
+
+ Parameters:
+ brain_id (str): Identifier of the brain/graph to query. Defaults to "default".
+
+ Returns:
+ labels (list[str]): List of unique node label names.
"""
return await get_entities_labels_controller(brain_id)
@@ -41,6 +53,12 @@ async def get_entity_properties(
brain_id: str = "default",
):
"""
- Get all unique property keys from entities in the graph.
+ Retrieve all unique property keys used by entities in the specified brain/graph.
+
+ Parameters:
+ brain_id (str): Identifier of the brain/graph to query; defaults to "default".
+
+ Returns:
+ list[str]: A list of property key names present on entities in the graph.
"""
return await get_entity_properties_controller(brain_id)
\ No newline at end of file
diff --git a/src/services/api/routes/model.py b/src/services/api/routes/model.py
index 59d45e0..c63ddf9 100644
--- a/src/services/api/routes/model.py
+++ b/src/services/api/routes/model.py
@@ -24,7 +24,10 @@ model_router = APIRouter(prefix="/model", tags=["model"])
@model_router.post(path="/entity")
async def add_entity(request: AddEntityRequest):
"""
- Add a single entity (node) to the graph.
+ Create a new entity (node) in the knowledge graph.
+
+ Returns:
+ Response payload containing details of the created node.
"""
import uuid as uuid_lib
from src.constants.kg import Node
@@ -53,6 +56,8 @@ async def add_entity(request: AddEntityRequest):
async def update_entity(request: UpdateEntityRequest):
"""
Update an entity (node) in the graph.
+
+ @returns The controller's response containing the updated node representation or an operation result.
"""
return await update_node_controller(
uuid=request.uuid,
@@ -68,7 +73,10 @@ async def update_entity(request: UpdateEntityRequest):
@model_router.post(path="/relationship")
async def add_relationship(request: AddRelationshipRequest):
"""
- Add a relationship between two nodes in the graph.
+ Create a relationship linking two nodes in the graph.
+
+ Returns:
+ relationship (dict): Representation of the created relationship.
"""
return await add_relationship_controller(
subject_uuid=request.subject_uuid,
@@ -81,7 +89,12 @@ async def add_relationship(request: AddRelationshipRequest):
@model_router.put(path="/relationship")
async def update_relationship(request: UpdateRelationshipRequest):
"""
- Update a relationship's properties in the graph.
+ Update properties of an existing relationship.
+
+ Uses the following fields from `request`: `uuid`, `brain_id`, `new_properties` (defaults to an empty dict if missing), and `properties_to_remove` (defaults to an empty list if missing).
+
+ Returns:
+ The updated relationship representation or a result object describing the outcome of the update.
"""
return await update_relationship_controller(
uuid=request.uuid,
diff --git a/src/services/api/routes/retrieve.py b/src/services/api/routes/retrieve.py
index 9ff9e31..94d4d59 100644
--- a/src/services/api/routes/retrieve.py
+++ b/src/services/api/routes/retrieve.py
@@ -126,7 +126,20 @@ async def get_relationships(
brain_id: str = "default",
):
"""
- Get the relationships of the graph.
+ Retrieve relationships from the knowledge graph filtered by the provided criteria.
+
+ Parameters:
+ relationship_types (Optional[str]): Comma-separated relationship types to include; will be split into a list if provided.
+ from_node_labels (Optional[str]): Comma-separated source node labels to filter by; will be split into a list if provided.
+ to_node_labels (Optional[str]): Comma-separated target node labels to filter by; will be split into a list if provided.
+ query_text (Optional[str]): Free-text query to match against relationships or nodes.
+ query_search_target (Optional[str]): Which part to apply `query_text` to (for example, "all", "source", or "target"); defaults to "all".
+ limit (int): Maximum number of relationships to return; defaults to 10.
+ skip (int): Number of relationships to skip (offset); defaults to 0.
+ brain_id (str): Identifier of the brain (dataset) to query; defaults to "default".
+
+ Returns:
+ A list of relationship records that match the provided filters.
"""
if relationship_types:
relationship_types = relationship_types.split(",")
@@ -153,7 +166,17 @@ async def get_entities(
brain_id: str = "default",
):
"""
- Get the entities of the graph.
+ Retrieve entities from the graph matching optional label and text filters.
+
+ Parameters:
+ limit (int): Maximum number of entities to return.
+ skip (int): Number of entities to skip (offset).
+ node_labels (Optional[str]): Comma-separated node labels to filter by (e.g. "Person,Company"); if provided, only entities with any of these labels are returned.
+ query_text (Optional[str]): Free-text filter to match entity properties or content.
+ brain_id (str): Identifier of the brain/knowledge store to query.
+
+ Returns:
+ A collection of entities that match the provided filters and pagination parameters.
"""
if node_labels:
node_labels = node_labels.split(",")
@@ -224,7 +247,18 @@ async def get_observations_list(
brain_id: str = "default",
):
"""
- Get a list of observations.
+ Retrieve a list of observations filtered by the provided parameters.
+
+ Parameters:
+ limit (int): Maximum number of observations to return.
+ skip (int): Number of observations to skip (offset).
+ resource_id (Optional[str]): If provided, only return observations for this resource identifier.
+ labels (Optional[str]): Comma-separated observation labels to filter by; when provided, labels are treated as a list of strings.
+ query_text (Optional[str]): Full-text query to filter observations.
+ brain_id (str): Identifier of the brain/tenant to query.
+
+ Returns:
+ list: A list of observation records that match the provided filters.
"""
if labels:
labels = labels.split(",")
@@ -235,7 +269,13 @@ async def get_changelog_types(
brain_id: str = "default",
):
"""
- Get all unique types from changelogs.
+ Retrieve all unique changelog types for the specified brain.
+
+ Parameters:
+ brain_id (str): Identifier of the brain to query; defaults to "default".
+
+ Returns:
+ list[str]: List of unique changelog type names.
"""
return await get_changelog_types_controller(brain_id)
@@ -245,7 +285,14 @@ async def get_changelog_by_id(
brain_id: str = "default",
):
"""
- Get changelog by ID.
+ Retrieve a changelog record by its identifier.
+
+ Parameters:
+ id (str): The changelog's unique identifier.
+ brain_id (str): Identifier of the brain to query; defaults to "default".
+
+ Returns:
+ The changelog record matching `id`.
"""
return await get_changelog_by_id_controller(id, brain_id)
@@ -258,7 +305,14 @@ async def get_changelogs_list(
brain_id: str = "default",
):
"""
- Get a list of changelogs.
+ Retrieve a paginated list of changelogs.
+
+ Parameters:
+ types (Optional[str]): Optional comma-separated changelog types to filter by; each type will be applied as a filter.
+ query_text (Optional[str]): Optional text used to filter changelogs by content or metadata.
+
+ Returns:
+ list: Changelog records matching the provided filters, constrained by `limit` and `skip`.
"""
if types:
types = types.split(",")