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
📝 Add docstrings to `development`
coderabbitai[bot]0564cde7b8d9
diff --git a/src/adapters/data.py b/src/adapters/data.pyindex bc0ca59..9748480 100644--- a/src/adapters/data.py+++ b/src/adapters/data.py@@ -157,13 +157,13 @@ class DataAdapter:def get_observation_labels(self, brain_id: str = "default") -> list[str]:"""- Retrieve all unique observation labels for the specified brain.-+ Get all unique observation labels for the specified brain.+Parameters:- brain_id (str): Identifier of the brain to query labels from.-+ brain_id (str): Identifier of the brain to query.+Returns:- list[str]: All unique labels present in observations for the specified brain.+ list[str]: A list of unique observation label strings for the specified brain."""return self.data.get_observation_labels(brain_id=brain_id)@@ -225,8 +225,15 @@ class DataAdapter:self, structured_data: StructuredData, brain_id: str = "default") -> StructuredData:"""- Update a structured data.+ Update an existing structured data entry.++ Parameters:+ structured_data (StructuredData): The structured data object with updated information.+ brain_id (str): Identifier of the brain context for the update.++ Returns:+ StructuredData: The updated structured data object."""return self.data.update_structured_data(structured_data=structured_data, brain_id=brain_id- )+ )\ No newline at end of filediff --git a/src/adapters/embeddings.py b/src/adapters/embeddings.pyindex 8dfc111..3eb3e73 100644--- a/src/adapters/embeddings.py+++ b/src/adapters/embeddings.py@@ -85,7 +85,19 @@ class VectorStoreAdapter:limit: int = 10,) -> dict[str, list[Vector]]:"""- Search similar vectors by their IDs.+ Finds vectors similar to the provided vector IDs within a specified store and brain.++ Parameters:+ vector_ids (list[str]): IDs of the source vectors to find similarities for.+ brain_id (str): Identifier of the brain/namespace to search within.+ store (str): Name of the vector store to query.+ min_similarity (float): Minimum similarity threshold for returned vectors (inclusive).+ limit (int): Maximum number of similar vectors to return per source ID.++ Returns:+ dict[str, list[Vector]]: Mapping from each source vector ID to a list of similar Vectors.+ Each list contains at most `limit` items, includes only vectors with similarity >= `min_similarity`,+ and is ordered by descending similarity."""return self.vector_store.search_similar_by_ids(vector_ids, brain_id, store, min_similarity, limit@@ -93,4 +105,4 @@ class VectorStoreAdapter:_embeddings_adapter = EmbeddingsAdapter()-_vector_store_adapter = VectorStoreAdapter()+_vector_store_adapter = VectorStoreAdapter()\ No newline at end of filediff --git a/src/adapters/graph.py b/src/adapters/graph.pyindex 24f40d1..515738b 100644--- a/src/adapters/graph.py+++ b/src/adapters/graph.py@@ -130,22 +130,26 @@ class GraphAdapter:def get_graph_relationships(self, brain_id: str = "default") -> list[str]:"""- Retrieve the relationship types present in the graph.-+ Retrieve relationship type names available in the graph.+Parameters:brain_id (str): Identifier of the graph/brain to query.-+Returns:- A list of relationship type names.+ list[str]: Relationship type names present in the specified graph."""return self.graph.get_graph_relationships(brain_id)def get_by_uuid(self, uuid: str, brain_id: str = "default") -> Node:"""- DEPRECATED: use get_by_uuids instead.-- Retrieve the node with the specified UUID from the graph.-+ Retrieve a node by its UUID from the graph.++ Deprecated: use `get_by_uuids` for batch retrieval.++ Parameters:+ uuid (str): UUID of the node to retrieve.+ brain_id (str): Identifier of the graph/brain to query.+Returns:Node: The node matching the provided UUID."""@@ -314,19 +318,19 @@ class GraphAdapter: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.+ Get all unique node types stored in the graph.++ Returns:+ list[str]: 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]:"""- 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 all unique node property keys present in the graph for the specified brain.++ Returns:+ list[str]: Unique node property key names present in the specified brain's graph."""return self.graph.get_graph_node_properties(brain_id)@@ -380,21 +384,34 @@ class GraphAdapter:similarity_threshold: float = 0.0,) -> List[Tuple[Node, List[Tuple[Predicate, Node, List[Tuple[Predicate, Node]]]]]]:"""- Get the 2nd degree hops for a list of nodes.-+ Compute second-degree neighbor hops for the given starting node UUIDs using vector-store–based filtering.+Parameters:- from_uuids: List[str]: The list of node UUIDs to start from.- flattened: bool: Whether to return simplified nodes and relationships.- vector_store_adapter: VectorStoreClient: The vector store adapter to use.- brain_id: str: The brain ID to use.-+ from_uuids: List[str] — UUIDs of the starting nodes to explore.+ flattened: bool — When true, nodes and predicates are returned as lightweight dicts with core fields (`uuid`, `name`, `labels`/`direction`) instead of full objects.+ vector_store_adapter: VectorStoreClient — Vector store used to fetch embeddings and perform similarity-based filtering.+ brain_id: str — Identifier of the brain/graph space to query.+ similarity_threshold: float — Optional threshold for additional similarity-based filtering (0.0 disables the extra check).+Returns:- List[Tuple[Node, List[Tuple[Predicate, Node, List[Tuple[Predicate, Node]]]]]]: The list of 2nd degree hops.+ List[Tuple[Node, List[Tuple[Predicate, Node, List[Tuple[Predicate, Node]]]]]] — A list where each item corresponds to a starting node and contains:+ - the starting node (or its flattened representation),+ - a list of first-degree entries, each being a tuple of (predicate, first-degree node, list of second-degree (predicate, node) tuples)."""# TODO: add a way to light weight the outputdef flatten_node(n):+ """+ Return a flattened node representation when the surrounding `flattened` flag is true, otherwise return the original node.++ Parameters:+ n: Node+ The node to convert.++ Returns:+ dict: A dictionary with keys `uuid`, `labels`, and `name` when `flattened` is true, otherwise the original node object.+ """return ({"uuid": n.uuid, "labels": n.labels, "name": n.name} if flattened else n)@@ -554,7 +571,16 @@ class GraphAdapter:brain_id: str = "default",) -> bool:"""- Check if a node exists in the graph.+ Determine whether a node with the given UUID, name, and labels exists in the graph.++ Parameters:+ uuid (str): UUID of the node to check; may be empty if matching by name and labels.+ name (str): Name of the node to match.+ labels (list[str]): List of labels/types the node must have.+ brain_id (str): Identifier of the graph/brain to query; defaults to "default".++ Returns:+ true if a matching node exists, false otherwise."""return self.graph.check_node_existence(uuid, name, labels, brain_id)@@ -571,9 +597,17 @@ class GraphAdapter:self, predicate_uuid: str, flow_key: str, brain_id: str = "default") -> List[Tuple[Node, Predicate, Node]]:"""- Get the next node by the flow key.+ Retrieve the next connected node tuple(s) for a relationship identified by a flow key.++ Parameters:+ predicate_uuid (str): UUID of the predicate (relationship) to search from.+ flow_key (str): Flow key value used to select the next relationship target.+ brain_id (str): Identifier of the brain/graph namespace to query.++ Returns:+ List[Tuple[Node, Predicate, Node]]: A list of (subject node, predicate, object node) tuples that are the next nodes matching the provided flow key; empty list if none are found."""return self.graph.get_next_by_flow_key(predicate_uuid, flow_key, brain_id)-_graph_adapter = GraphAdapter()+_graph_adapter = GraphAdapter()\ No newline at end of filediff --git a/src/adapters/interfaces/data.py b/src/adapters/interfaces/data.pyindex cb1c773..d2b261e 100644--- a/src/adapters/interfaces/data.py+++ b/src/adapters/interfaces/data.py@@ -116,7 +116,17 @@ class DataClient(ABC):query_text: str = None,) -> list[StructuredData]:"""- Get a list of structured data.+ Retrieve structured data entries for a specific brain with optional filtering and pagination.++ Parameters:+ brain_id (str): Identifier of the brain to query.+ limit (int): Maximum number of items to return.+ skip (int): Number of items to skip (offset) for pagination.+ types (list[str] | None): If provided, restrict results to these structured data types.+ query_text (str | None): If provided, filter entries that match the text query.++ Returns:+ list[StructuredData]: List of matching StructuredData objects."""raise NotImplementedError("get_structured_data_list method not implemented")@@ -145,20 +155,31 @@ class DataClient(ABC):query_text: str = None,) -> list[Observation]:"""- Get a list of observations.+ Retrieve a filtered, paginated list of observations for a specific brain.++ Parameters:+ brain_id (str): Identifier of the brain to query.+ limit (int): Maximum number of observations to return.+ skip (int): Number of observations to skip (offset) for pagination.+ resource_id (str | None): If provided, restrict results to observations for this resource.+ labels (list[str] | None): If provided, include only observations that have at least one of these labels.+ query_text (str | None): If provided, include only observations whose text matches this query.++ Returns:+ observations (list[Observation]): A list of matching Observation objects ordered according to the backend's default sort."""raise NotImplementedError("get_observations_list method not implemented")@abstractmethoddef get_observation_labels(self, brain_id: str) -> list[str]:"""- Return all unique observation labels for the specified brain.-+ Retrieve 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.+ list[str]: Unique label strings present in the brain's observations."""raise NotImplementedError("get_observation_labels method not implemented")@@ -203,13 +224,13 @@ class DataClient(ABC):@abstractmethoddef get_changelog_types(self, brain_id: str) -> list[str]:"""- Return the set of unique changelog types associated with the specified brain.-+ Return the unique changelog types present for the specified brain.+Parameters:- brain_id (str): Identifier of the brain whose changelog types should be retrieved.-+ brain_id (str): Identifier of the brain to query.+Returns:- list[str]: A list of unique changelog type names (order not guaranteed).+ list[str]: List of unique changelog type names for the brain (order not guaranteed)."""raise NotImplementedError("get_changelog_types method not implemented")@@ -218,6 +239,13 @@ class DataClient(ABC):self, structured_data: StructuredData, brain_id: str) -> StructuredData:"""- Update a structured data.+ Update an existing StructuredData record for a specific brain.++ Parameters:+ structured_data (StructuredData): StructuredData object containing the updated content and identifier of the record to update.+ brain_id (str): Identifier of the brain that owns the structured data.++ Returns:+ StructuredData: The stored StructuredData after the update."""- raise NotImplementedError("update_structured_data method not implemented")+ raise NotImplementedError("update_structured_data method not implemented")\ No newline at end of filediff --git a/src/adapters/interfaces/embeddings.py b/src/adapters/interfaces/embeddings.pyindex 68249e1..9a50bd8 100644--- a/src/adapters/interfaces/embeddings.py+++ b/src/adapters/interfaces/embeddings.py@@ -66,6 +66,16 @@ class VectorStoreClient(ABC):limit: int = 10,) -> dict[str, list[Vector]]:"""- Search similar vectors by their IDs.+ Finds vectors similar to the vectors identified by the given IDs.++ Parameters:+ vector_ids (list[str]): Identifiers of the vectors to find similarities for.+ brain_id (str): Identifier for the brain/context containing the vectors.+ store (str): Name of the vector store to query.+ min_similarity (float): Minimum similarity threshold (e.g., 0.0–1.0) for returned results.+ limit (int): Maximum number of similar vectors to return per input ID.++ Returns:+ dict[str, list[Vector]]: Mapping from each input vector ID to a list of similar `Vector` objects that meet or exceed `min_similarity`, with up to `limit` results per ID."""- raise NotImplementedError("search_similar_by_ids method not implemented")+ raise NotImplementedError("search_similar_by_ids method not implemented")\ No newline at end of filediff --git a/src/adapters/interfaces/graph.py b/src/adapters/interfaces/graph.pyindex a4002d1..aa01956 100644--- a/src/adapters/interfaces/graph.py+++ b/src/adapters/interfaces/graph.py@@ -278,17 +278,17 @@ class GraphClient(ABC):properties_to_remove: list[str],) -> Node | Predicate | None:"""- Update properties on a graph node or relationship.-+ Update properties on a node or relationship in the graph.+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.-+ updating (Literal["node", "relationship"]): Which entity type to update.+ brain_id (str): Identifier of the graph/brain containing the entity.+ new_properties (dict): Properties to set or overwrite on the entity.+ properties_to_remove (list[str]): Property keys to remove from the 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.+ Node | Predicate | None: The updated node or relationship if changes were applied, `None` if the entity was not found or no update occurred."""raise NotImplementedError("update_properties method not implemented")@@ -343,19 +343,19 @@ class GraphClient(ABC):properties_to_remove: Optional[list[str]] = None,) -> Node | None:"""- Update a node's identifying fields, labels, and properties in the graph.-+ Update a node's identifying fields, labels, and properties.+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.-+ brain_id (str): Identifier of the graph or brain containing the node.+ new_name (Optional[str]): New name for the node.+ new_description (Optional[str]): New description for the node.+ new_labels (Optional[list[str]]): New labels to replace existing labels.+ new_properties (Optional[dict]): Properties to add or update on the node.+ properties_to_remove (Optional[list[str]]): 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.+ Node | None: The updated node, or `None` if no matching node exists."""raise NotImplementedError("update_node method not implemented")@@ -374,17 +374,21 @@ class GraphClient(ABC):brain_id: str,) -> Dict[str, List[Tuple[Predicate, Node, List[Tuple[Predicate, Node]]]]]:"""- Gets the 2nd degree hops for each node in a list of things to search for.-- from_ is the node to start from.- flattened is a boolean to indicate if the result should be lightweighted (removed metadata, etc).- brain_id is the brain id to search in.-+ Return second-degree hops for each starting node.++ Parameters:+ from_ (List[str]): List of starting node UUIDs or identifiers to expand.+ flattened (bool): If true, return lightweight results with non-essential metadata removed.+ vector_store_adapter (VectorStoreClient): Adapter used to resolve or enrich nodes via the vector store.+ brain_id (str): Identifier of the brain/graph to query.+Returns:- A dictionary with the from_ string as the key and a list of tuples as the value.- The tuples are the node and their relationships.- The node is the 1st degree hop.- The relationships are the 2nd degree hops.+ hops_by_start (Dict[str, List[Tuple[Predicate, Node, List[Tuple[Predicate, Node]]]]]):+ Mapping from each starting node identifier in `from_` to a list of first-degree entries.+ Each first-degree entry is a tuple of:+ - `Predicate`: relationship from the starting node to the first-hop node,+ - `Node`: the first-hop node,+ - `List[Tuple[Predicate, Node]]`: list of second-degree hops where each item is a `(Predicate, Node)` tuple representing the relationship and the second-hop node."""raise NotImplementedError("get_2nd_degree_hops not implemented")@@ -397,7 +401,16 @@ class GraphClient(ABC):brain_id: str,) -> bool:"""- Check if a node exists in the graph.+ Determine whether a node with the given identity exists in the specified brain.++ Parameters:+ uuid (str): UUID of the node to check.+ name (str): Name of the node to match.+ labels (list[str]): List of labels/types the node must have.+ brain_id (str): Identifier of the brain (graph) to search within.++ Returns:+ true if a node matching the provided uuid, name, and labels exists in the brain, false otherwise."""raise NotImplementedError("check_node_existence method not implemented")@@ -406,8 +419,15 @@ class GraphClient(ABC):self, node: Node | str, depth: int, brain_id: str) -> list[dict]:"""- Get the neighborhood of a node up to a given depth.- Returns a nested structure where each neighbor contains its own neighbors.+ Retrieve the neighborhood of a node up to a specified depth.++ Parameters:+ node (Node | str): The starting node or its UUID.+ depth (int): Maximum distance from the starting node to include (1 = immediate neighbors).+ brain_id (str): Identifier of the brain/graph to query.++ Returns:+ list[dict]: A nested list of dictionaries representing the neighborhood; each dictionary represents a node and contains its neighbors as nested structures up to the requested depth."""raise NotImplementedError("get_neighborhood method not implemented")@@ -416,7 +436,9 @@ class GraphClient(ABC):self, predicate_uuid: str, flow_key: str, brain_id: str) -> List[Tuple[Node, Predicate, Node]]:"""- Get the next node by the flow key.- Returns a tuple where the first element is the connected node to the predicate, the second element is the next relationship by flow key and the third element is the next node.+ Retrieve the next connected node and the relationship identified by a flow key for a given predicate.++ Returns:+ List[Tuple[Node, Predicate, Node]]: A list of triples where each triple is (connected node to the predicate, relationship that matches the provided flow_key, next node reached via that relationship)."""- raise NotImplementedError("get_next_by_flow_key method not implemented")+ raise NotImplementedError("get_next_by_flow_key method not implemented")\ No newline at end of filediff --git a/src/config.py b/src/config.pyindex 8a42ff1..56a5026 100644--- a/src/config.py+++ b/src/config.py@@ -161,6 +161,14 @@ class CeleryConfig:"""def __init__(self):+ """+ Initialize CeleryConfig by loading the worker concurrency setting from the environment.++ Sets `self.worker_concurrency` from the `CELERY_WORKER_CONCURRENCY` environment variable and validates its presence.++ Raises:+ ValueError: If `CELERY_WORKER_CONCURRENCY` is not set.+ """self.worker_concurrency = os.getenv("CELERY_WORKER_CONCURRENCY")if [self.worker_concurrency].count(None) > 0:raise ValueError("Celery configuration is not complete")@@ -172,6 +180,13 @@ class PricingConfig:"""def __init__(self):+ """+ Initialize pricing configuration from environment variables.++ Attributes:+ input_token_price (float): Price per input token from INPUT_TOKEN_PRICE, defaults to 0.0 if unset.+ output_token_price (float): Price per output token from OUTPUT_TOKEN_PRICE, defaults to 0.0 if unset.+ """self.input_token_price = float(os.getenv("INPUT_TOKEN_PRICE", 0))self.output_token_price = float(os.getenv("OUTPUT_TOKEN_PRICE", 0))@@ -182,6 +197,14 @@ class Config:"""def __init__(self):+ """+ Initialize the application's central configuration by composing environment-backed sub-configurations and loading runtime flags.++ This constructor instantiates Azure, Redis, Neo4j, Milvus, Embeddings, Mongo, GCP, Celery, and Pricing configuration objects, reads the RUN_GRAPH_CONSOLIDATOR flag into `run_graph_consolidator`, and loads the `BRAINPAT_TOKEN` into `brainpat_token`.++ Raises:+ ValueError: If `BRAINPAT_TOKEN` is not set in the environment.+ """self.azure = AzureConfig()self.redis = RedisConfig()self.neo4j = Neo4jConfig()@@ -201,4 +224,4 @@ class Config:raise ValueError("BrainPAT token is not set")-config = Config()+config = Config()\ No newline at end of filediff --git a/src/core/agents/architect_agent.py b/src/core/agents/architect_agent.pyindex 4bbd366..eb2b154 100644--- a/src/core/agents/architect_agent.py+++ b/src/core/agents/architect_agent.py@@ -80,6 +80,20 @@ class ArchitectAgent:# database_desc: str,ingestion_manager: IngestionManager,):+ """+ Initialize the ArchitectAgent with the required adapters and managers and prepare internal runtime state.++ Parameters:+ llm_adapter (LLMAdapter): Adapter for interacting with the language model.+ cache_adapter (CacheAdapter): Adapter used for cache reads/writes.+ kg (GraphAdapter): Graph knowledge-base adapter for entity and relationship operations.+ vector_store (VectorStoreAdapter): Adapter for vector storage and retrieval.+ embeddings (EmbeddingsAdapter): Adapter that produces vector embeddings for content.+ ingestion_manager (IngestionManager): Manager responsible for ingesting external data into the system.++ The constructor initializes internal tracking state including token counters (input, output, cached, reasoning),+ message/agent state, and containers for discovered relationships and used entities.+ """self.llm_adapter = llm_adapterself.cache_adapter = cache_adapterself.kg = kg@@ -104,6 +118,22 @@ class ArchitectAgent:targeting: Optional[Node] = None,) -> List[BaseTool]:+ """+ Builds the set of tools the agent uses for relationship creation and entity tracking.++ Parameters:+ text (Optional[str]): Optional prompt or context text passed to the create-relationship tool.+ entities (Optional[Dict[str, ScoutEntity]]): Optional mapping of entity UUIDs to ScoutEntity instances for context.+ brain_id (str): Identifier for the knowledge brain/namespace to scope KG operations.+ targeting (Optional[Node]): Optional target node context to guide relationship creation.++ Returns:+ List[BaseTool]: A list containing:+ - ArchitectAgentCreateRelationshipTool configured with the provided context,+ - ArchitectAgentGetRemainingEntitiesToProcessTool,+ - ArchitectAgentCheckUsedEntitiesTool,+ - ArchitectAgentMarkEntitiesAsUsedTool.+ """return [ArchitectAgentCreateRelationshipTool(self,@@ -135,6 +165,22 @@ class ArchitectAgent:brain_id: str = "default",targeting: Optional[Node] = None,):+ """+ Configure and create the internal LangChain agent and store it on self.agent.++ Parameters:+ type_ (Literal["single", "tooler"]): Chooses agent mode. "single" uses a structured response prompt and no tools; "tooler" uses the tooler system prompt and enables tools.+ tools (Optional[List[BaseTool]]): Explicit tool list to attach when type_ is "tooler". If omitted for "tooler", a default tool set is created from provided context.+ output_schema (Optional[BaseModel]): Schema used as the agent's response format when type_ is "single".+ text (Optional[str]): Optional prompt context forwarded to default tool construction when tools are not provided.+ extra_system_prompt (Optional[dict]): Additional system prompt content interpolated into the selected system prompt.+ entities (Optional[Dict[str, ScoutEntity]]): Entity context forwarded to default tool construction when tools are not provided.+ brain_id (str): Identifier forwarded to default tool construction when tools are not provided.+ targeting (Optional[Node]): Targeting context forwarded to default tool construction when tools are not provided.++ Side effects:+ Creates an agent via create_agent and assigns it to self.agent.+ """if type_ == "single":system_prompt = ARCHITECT_AGENT_SYSTEM_PROMPT.format(extra_system_prompt=extra_system_prompt if extra_system_prompt else ""@@ -179,7 +225,22 @@ class ArchitectAgent:max_retries: int = 3,) -> ArchitectAgentResponse:"""- Run the architect agent.+ Orchestrates the agent to discover relationships and new nodes for the provided entities based on the input text.++ Parameters:+ text (str): Natural-language description or instructions guiding relationship discovery.+ entities (List[ScoutEntity]): Entities to process; each entity should include a UUID.+ targeting (Optional[Node]): Optional node that provides contextual focus for relationship creation.+ brain_id (str): Identifier for the knowledge brain or workspace to use.+ timeout (int): Maximum seconds to wait for a single LLM invocation before timing out.+ max_retries (int): Number of retry attempts for timed-out LLM invocations.++ Returns:+ ArchitectAgentResponse: Contains:+ - new_nodes: list of newly discovered nodes produced by the agent.+ - relationships: list of relationships the agent created between entities or new nodes.+ - input_tokens: count of input tokens consumed during this run.+ - output_tokens: count of output tokens produced during this run."""entities_dict = {entity.uuid: entity for entity in entities}@@ -200,6 +261,17 @@ class ArchitectAgent:all_rels: list[ArchitectAgentRelationship],previous_messages: list = None,):+ """+ Builds a message history including the provided entities and previously created relationships, invokes the configured agent with that history, and returns the agent's response.++ Parameters:+ ent (list[ScoutEntity]): Entities to include in the prompt.+ all_rels (list[ArchitectAgentRelationship]): Previously created relationships to include in the prompt.+ previous_messages (list, optional): Prior message objects to include as conversation history; may be trimmed to fit history limits.++ Returns:+ The agent's response object containing the model's reply and associated metadata.+ """from langchain_core.messages import HumanMessagemessages_list = []@@ -253,6 +325,20 @@ class ArchitectAgent:entities: List[ScoutEntity],seen_relationship_keys: set,) -> set:+ """+ Extracts newly created relationships and nodes from a structured agent response and updates the provided tracking collections.++ Parameters:+ response (dict): Agent response containing a `structured_response` with optional `relationships` and `new_nodes`.+ connected_entity_uuids (set): Set of UUIDs already known to be connected; will be updated with newly connected UUIDs.+ all_relationships (list): List to append newly discovered, deduplicated relationship objects.+ all_new_nodes (list): List to append any new node objects reported in the response.+ entities (List[ScoutEntity]): Source entities to check membership of relationship endpoints (used to mark endpoints as connected).+ seen_relationship_keys (set): Set of (tail_uuid, tip_uuid, relationship_name) tuples used to deduplicate relationships.++ Returns:+ set: The set of entity UUIDs that became connected as a result of processing this response iteration.+ """structured_response = response.get("structured_response", {})iteration_connected = set()@@ -302,6 +388,19 @@ class ArchitectAgent:def _invoke_agent_with_retry(unconnected_entities_list: List[ScoutEntity], previous_messages: list):+ """+ Invoke the architect agent with a single-worker executor and timeout, and update token counts from any returned messages.++ Parameters:+ unconnected_entities_list (List[ScoutEntity]): Entities to include in the agent invocation.+ previous_messages (list): Message history to send to the agent.++ Returns:+ dict: The response dictionary returned by the agent invocation.++ Raises:+ TimeoutError: If the agent call does not complete within the configured timeout.+ """try:with ThreadPoolExecutor(max_workers=1) as executor:future = executor.submit(@@ -324,6 +423,19 @@ class ArchitectAgent:def _invoke_and_process(unconnected_entities_list: List[ScoutEntity], previous_messages: list):+ """+ Invoke the agent for the provided unconnected entities, append any returned messages to the accumulated message history, and process the agent's response to determine which entities became connected.++ Parameters:+ unconnected_entities_list (List[ScoutEntity]): Entities to include in this agent invocation.+ previous_messages (list): Message history to send with the invocation.++ Returns:+ set: UUID strings of entities that were connected as a result of this invocation.++ Raises:+ TimeoutError: If the agent invocation exhausts retries or times out.+ """try:response = _invoke_agent_with_retry(unconnected_entities_list, previous_messages@@ -388,7 +500,23 @@ class ArchitectAgent:max_retries: int = 3,) -> List[ArchitectAgentRelationship]:"""- Run the architect agent tooler.+ Drive the architect agent in "tooler" mode to iteratively discover relationships using available tools and collect the results.++ This invokes the agent with the provided text and entities, manages message history trimming, updates token accounting from message metadata, and accumulates relationships produced by tool-driven agent actions.++ Parameters:+ text (str): Natural-language prompt or instructions for relationship discovery.+ entities (List[ScoutEntity]): Candidate entities the agent may connect; each entity must include a UUID.+ targeting (Optional[Node]): Optional node to which discovered information should be anchored or related.+ brain_id (str): Identifier for the knowledge brain/context to use.+ timeout (int): Maximum seconds to wait for a single agent invocation before raising a timeout.+ max_retries (int): Maximum number of retry attempts for timed or retried invocations.++ Returns:+ List[ArchitectAgentRelationship]: The relationships discovered and collected by the agent during this run.++ Raises:+ TimeoutError: If the agent fails to produce a response within `timeout` after the allowed retry attempts."""entities_dict = {entity.uuid: entity for entity in entities}@@ -405,6 +533,16 @@ class ArchitectAgent:accumulated_messages = []def _invoke_agent(previous_messages: list = None):+ """+ Prepare a pruned message history, append a formatted human prompt for the "tooler" flow, and invoke the agent.++ Parameters:+ previous_messages (list | None): Prior messages to include in the history; if the count exceeds HISTORY_MAX_MESSAGES,+ the oldest messages are removed via RemoveMessage entries and the remaining messages are preserved.++ Returns:+ The response object returned by self.agent.invoke when called with the constructed message list.+ """from langchain_core.messages import HumanMessagemessages_list = []@@ -448,6 +586,18 @@ class ArchitectAgent:reraise=True,)def _invoke_agent_with_retry(previous_messages: list):+ """+ Invoke the agent in a worker thread, enforce the configured timeout, and update token counters from any returned message usage metadata.++ Parameters:+ previous_messages (list): Message history to pass to the agent invocation.++ Returns:+ dict: The agent response object as returned by the underlying _invoke_agent call.++ Raises:+ TimeoutError: If the agent invocation exceeds the configured timeout.+ """try:with ThreadPoolExecutor(max_workers=1) as executor:future = executor.submit(_invoke_agent, previous_messages)@@ -469,6 +619,18 @@ class ArchitectAgent:)def _invoke_and_process(previous_messages: list):+ """+ Invoke the agent with retry logic and append any returned messages to the outer `accumulated_messages` list.++ Parameters:+ previous_messages (list): Message history to send to the agent.++ Returns:+ response (dict): The agent's response object; may include a "messages" key containing new messages.++ Raises:+ TimeoutError: If the agent invocation times out or fails after all retry attempts.+ """try:response = _invoke_agent_with_retry(previous_messages)messages = response.get("messages", [])@@ -489,7 +651,16 @@ class ArchitectAgent:return list(self.relationships_set)def _update_token_counts(self, usage_metadata: dict):- """Extract all token counts from usage metadata"""+ """+ Update the agent's token counters from an LLM usage metadata dictionary.++ Parameters:+ usage_metadata (dict): Metadata containing token usage details. Expected keys:+ - "input_tokens": integer count of input tokens.+ - "output_tokens": integer count of output tokens.+ - "input_token_details": dict with "cache_read" (int) for cached input token reads.+ - "output_token_details": dict with "reasoning" (int) for tokens spent on reasoning.+ """# Base countsself.input_tokens += usage_metadata.get("input_tokens", 0)self.output_tokens += usage_metadata.get("output_tokens", 0)@@ -500,4 +671,4 @@ class ArchitectAgent:# Output details (reasoning)output_details = usage_metadata.get("output_token_details", {})- self.reasoning_tokens += output_details.get("reasoning", 0)+ self.reasoning_tokens += output_details.get("reasoning", 0)\ No newline at end of filediff --git a/src/core/agents/janitor_agent.py b/src/core/agents/janitor_agent.pyindex ddd61f7..7e104f0 100644--- a/src/core/agents/janitor_agent.py+++ b/src/core/agents/janitor_agent.py@@ -81,6 +81,18 @@ class JanitorAgent:embeddings: EmbeddingsAdapter,database_desc: str,):+ """+ Initialize the JanitorAgent with required adapters and a database description.++ Parameters:+ llm_adapter (LLMAdapter): Adapter for language model interactions.+ kg (GraphAdapter): Adapter for graph database operations.+ vector_store (VectorStoreAdapter): Adapter for vector search and retrieval.+ embeddings (EmbeddingsAdapter): Adapter to compute embeddings for text.+ database_desc (str): Human-readable description of the target database.++ Initializes internal token counters and token detail storage.+ """self.llm_adapter = llm_adapterself.kg = kgself.vector_store = vector_store@@ -94,6 +106,15 @@ class JanitorAgent:self.token_detail = Nonedef _get_tools(self, brain_id: str = "default") -> List[BaseTool]:+ """+ Assembles the set of tools the Janitor agent uses, scoped to the specified brain.++ Parameters:+ brain_id (str): Identifier of the brain/context used to instantiate each tool.++ Returns:+ List[BaseTool]: A list containing the schema access tool, the entity search tool (using embeddings and vector store), and the graph read-operation tool configured for this agent and brain_id.+ """return [JanitorAgentGetSchemaTool(self,@@ -124,6 +145,20 @@ class JanitorAgent:brain_id: str = "default",type_: str = Literal["janitor", "graph-janitor"],):+ """+ Configure and instantiate the internal LangChain agent and assign it to `self.agent`.++ Constructs a system prompt based on `type_` ("janitor", "graph-janitor", or "atomic-janitor"), derives a response schema from `output_schema` or `output_schemas` (merging multiple schemas into a Union when needed and wrapping complex schemas in `ToolStrategy`), and calls `create_agent` with the selected model, tools, system prompt, response format, and debug flag.++ Parameters:+ tools (Optional[List[BaseTool]]): Optional list of tools to expose to the agent; if omitted, the agent's default tools for `brain_id` are used.+ output_schema (Optional[BaseModel]): Single response schema or a tuple of schemas to use as the agent's response format.+ output_schemas (Optional[Union[BaseModel, Tuple[BaseModel, ...]]]): Alternative parameter allowing multiple output schemas; when provided, schemas are unified into a Union and wrapped in `ToolStrategy`.+ extra_system_prompt (Optional[dict]): Optional dictionary whose contents are formatted into the selected system prompt.+ brain_id (str): Identifier for the knowledge brain used when resolving default tools.+ type_ (str): Agent mode controlling system prompt selection; supported values are "janitor", "graph-janitor", and "atomic-janitor".++ """system_prompt = Noneif type_ == "janitor":system_prompt = JANITOR_AGENT_SYSTEM_PROMPT.format(@@ -180,7 +215,19 @@ class JanitorAgent:max_retries: int = 3,) -> list[str]:"""- Runs a final janitor consolidation across the kg snapshot+ Run graph-level consolidation for the provided relationships against a KG snapshot.++ Parameters:+ new_relationships (List[ArchitectAgentRelationship]): Relationships to normalize and consolidate into the graph.+ brain_id (str): Identifier of the knowledge brain/context to use.+ timeout (int): Maximum seconds to wait for a single agent invocation before timing out.+ max_retries (int): Number of retry attempts for agent invocation on timeout.++ Returns:+ list[str]: Consolidation tasks produced by the graph janitor; returns an empty list if no tasks were produced.++ Raises:+ TimeoutError: If the agent invocation times out or fails after the configured number of retries."""accumulated_messages = []@@ -214,6 +261,15 @@ class JanitorAgent:)def _invoke_agent(previous_messages: list = None):+ """+ Builds a message history (pruning older entries when it exceeds HISTORY_MAX_MESSAGES), appends a user message containing a graph-normalization prompt populated with the current hops snapshot and the provided new relationships, and invokes the configured agent with that message sequence.++ Parameters:+ previous_messages (list): Optional sequence of prior messages to include in the history. When the sequence length exceeds HISTORY_MAX_MESSAGES, older messages are replaced with RemoveMessage objects to trim the history.++ Returns:+ The agent's response object returned by self.agent.invoke for the assembled messages.+ """from langchain_core.messages import HumanMessagemessages_list = []@@ -251,6 +307,18 @@ class JanitorAgent:reraise=True,)def _invoke_agent_with_retry(previous_messages: list):+ """+ Invoke the configured agent in a thread pool, update the agent's token counters from any returned message usage metadata, and return the agent response.++ Parameters:+ previous_messages (list): The accumulated message history to provide to the agent for this invocation.++ Returns:+ dict: The agent's response object (expected to contain a "messages" list and optional usage metadata).++ Raises:+ TimeoutError: If the agent invocation does not complete within the configured timeout.+ """try:with ThreadPoolExecutor(max_workers=1) as executor:future = executor.submit(_invoke_agent, previous_messages)@@ -272,6 +340,18 @@ class JanitorAgent:)def _invoke_and_process(previous_messages: list):+ """+ Invoke the agent with retry handling and append any returned messages to the accumulated_messages history.++ Parameters:+ previous_messages (list): The list of messages to send to the agent as the current context.++ Returns:+ dict: The raw response object returned by the agent invocation.++ Raises:+ TimeoutError: If the agent invocation exhausts retries or a timeout occurs; the exception message includes the last attempt's error.+ """try:response = _invoke_agent_with_retry(previous_messages)messages = response.get("messages", [])@@ -314,7 +394,21 @@ class JanitorAgent:max_retries: int = 3,) -> JanitorAgentInputOutput:"""- Run the janitor agent.+ Normalize a single insertion unit using the janitor agent.++ Parameters:+ input_output (JanitorAgentInputOutput): The unit of work to normalize (relationship, virtual node, or entity).+ text (str): Human-provided text that guides the normalization.+ targeting (Optional[Node]): Optional human-readable context for a Node target (includes name, description, and properties).+ brain_id (str): Identifier of the brain/knowledge scope to use.+ timeout (int): Maximum seconds to wait for a single agent invocation before raising a TimeoutError.+ max_retries (int): Maximum number of retry attempts for transient invocation timeouts.++ Returns:+ JanitorAgentInputOutput: A container populated with `relationship`, `virtual_node`, and/or `entity` extracted from the agent's structured response; fields are set to `None` when not provided by the agent.++ Raises:+ TimeoutError: If the agent invocation times out or fails after the configured number of retries."""self._get_agent(@@ -324,6 +418,15 @@ class JanitorAgent:accumulated_messages = []def _invoke_agent(previous_messages: list = None):+ """+ Builds a message list (with optional history pruning) and invokes the configured agent with a normalization prompt.++ Parameters:+ previous_messages (list | None): Prior conversation messages to include in the invocation; when provided and longer than HISTORY_MAX_MESSAGES, older messages are removed via deletion markers before sending.++ Returns:+ agent_response: The result returned by the agent's invoke call (the agent's response object).+ """from langchain_core.messages import HumanMessagemessages_list = []@@ -368,6 +471,18 @@ class JanitorAgent:reraise=True,)def _invoke_agent_with_retry(previous_messages: list):+ """+ Invoke the configured agent with the provided message history, update the agent's token counters from any returned message usage metadata, and return the raw agent response.++ Parameters:+ previous_messages (list): Accumulated conversation messages to send to the agent.++ Returns:+ dict: The agent's raw response object (may contain a "messages" list and other metadata).++ Raises:+ TimeoutError: If the agent call exceeds the configured timeout.+ """try:with ThreadPoolExecutor(max_workers=1) as executor:future = executor.submit(_invoke_agent, previous_messages)@@ -389,6 +504,18 @@ class JanitorAgent:)def _invoke_and_process(previous_messages: list):+ """+ Invoke the agent with retry logic and process its response into the accumulated message history.++ Parameters:+ previous_messages (list): The message history passed to the agent for this invocation.++ Returns:+ dict: The raw agent response object returned by the retry wrapper; may contain a "messages" key whose items are appended to the outer `accumulated_messages`.++ Raises:+ TimeoutError: If the retry wrapper exhausts attempts or a timeout occurs; when retries are exhausted the exception message includes the last attempt number and its error.+ """try:response = _invoke_agent_with_retry(previous_messages)messages = response.get("messages", [])@@ -438,8 +565,21 @@ class JanitorAgent:max_retries: int = 3,) -> AtomicJanitorAgentInputOutput | str:"""- Run the atomic janitor agent.- Can return istructions on how to correct the wrong relationships or 'OK' if the relationships are correct.+ Validate and produce correction instructions for a set of atomic relationships using the atomic janitor agent.++ Parameters:+ input_relationships (List[ArchitectAgentRelationship]): The relationships (units of work) to validate.+ text (str): Human-readable context or explanation to guide validation.+ targeting (Optional[Node]): Optional node context providing name, description, and properties to narrow validation.+ brain_id (str): Identifier of the brain/knowledge context to run the agent against.+ timeout (int): Maximum seconds to wait for a single agent invocation before raising a timeout.+ max_retries (int): Maximum number of retry attempts for agent invocation on timeout.++ Returns:+ AtomicJanitorAgentInputOutput | str: `'OK'` if all relationships are valid; otherwise an AtomicJanitorAgentInputOutput containing instructions or corrections.++ Raises:+ TimeoutError: If the agent invocation times out or fails after the configured retry attempts."""self._get_agent(@@ -451,6 +591,15 @@ class JanitorAgent:accumulated_messages = []def _invoke_agent(previous_messages: list = None):+ """+ Assemble a trimmed message history, append an atomic-janitor user message built from the current units of work, text, and optional targeting, then invoke the agent.++ Parameters:+ previous_messages (list | None): Prior messages to include in the invocation; if the list exceeds HISTORY_MAX_MESSAGES, older messages are removed via RemoveMessage objects before sending.++ Returns:+ The raw response returned by self.agent.invoke for the assembled messages.+ """from langchain_core.messages import HumanMessagemessages_list = []@@ -497,6 +646,18 @@ class JanitorAgent:reraise=True,)def _invoke_agent_with_retry(previous_messages: list):+ """+ Invoke the agent using the provided message history, update token counters from any returned usage metadata, and return the agent's response.++ Parameters:+ previous_messages (list): Accumulated conversation messages to send as context to the agent.++ Returns:+ dict: The agent's response object; expected to include a "messages" list containing response message objects.++ Raises:+ TimeoutError: If the invocation exceeds the configured timeout or if retries are exhausted; the exception message contains timing or last-attempt error details.+ """try:with ThreadPoolExecutor(max_workers=1) as executor:future = executor.submit(_invoke_agent, previous_messages)@@ -526,6 +687,18 @@ class JanitorAgent:raisedef _invoke_and_process(previous_messages: list):+ """+ Invoke the agent with retry logic, append any returned messages to the outer `accumulated_messages` list, and return the agent response.++ Parameters:+ previous_messages (list): Messages to include in the invocation request.++ Returns:+ response (dict): The agent's response object; may include a `messages` key with returned messages.++ Raises:+ TimeoutError: If the invocation exhausts retry attempts or a timeout occurs.+ """try:response = _invoke_agent_with_retry(previous_messages)messages = response.get("messages", [])@@ -560,7 +733,16 @@ class JanitorAgent:return structured_responsedef _update_token_counts(self, usage_metadata: dict):- """Extract all token counts from usage metadata"""+ """+ Update the agent's cumulative token counters from a message's usage metadata.++ Parameters:+ usage_metadata (dict): A mapping containing token usage information. Recognized keys:+ - "input_tokens": number to add to `input_tokens`+ - "output_tokens": number to add to `output_tokens`+ - "input_token_details": dict with optional "cache_read" to add to `cached_tokens`+ - "output_token_details": dict with optional "reasoning" to add to `reasoning_tokens`+ """# Base countsself.input_tokens += usage_metadata.get("input_tokens", 0)self.output_tokens += usage_metadata.get("output_tokens", 0)@@ -571,4 +753,4 @@ class JanitorAgent:# Output details (reasoning)output_details = usage_metadata.get("output_token_details", {})- self.reasoning_tokens += output_details.get("reasoning", 0)+ self.reasoning_tokens += output_details.get("reasoning", 0)\ No newline at end of filediff --git a/src/core/agents/kg_agent.py b/src/core/agents/kg_agent.pyindex daf20b1..503ebef 100644--- a/src/core/agents/kg_agent.py+++ b/src/core/agents/kg_agent.py@@ -60,6 +60,16 @@ class KGAgent:embeddings: EmbeddingsAdapter,database_desc: str,):+ """+ Initialize the KGAgent with required adapters, storage, and a human-readable database description.++ Parameters:+ database_desc (str): A brief description of the knowledge graph or database this agent will operate on.++ Description:+ Stores provided adapters and clients on the instance, sets the agent to None, and initializes token accounting fields:+ `input_tokens`, `output_tokens`, `cached_tokens`, `reasoning_tokens` set to 0 and `token_detail` set to None.+ """self.llm_adapter = llm_adapterself.cache_adapter = cache_adapterself.kg = kg@@ -74,6 +84,12 @@ class KGAgent:self.token_detail = Nonedef _execute_graph_operation(self, operation: str) -> str:+ """+ Execute a graph operation string against the configured knowledge graph.++ Returns:+ str: A human-readable status message indicating success, or an error message containing the exception text and the graph database type when execution fails.+ """try:self.kg.execute_operation(operation)return f"Graph operation executed successfully: {operation}"@@ -130,6 +146,20 @@ class KGAgent:extra_system_prompt: Optional[dict] = None,brain_id: str = "default",):+ """+ Configure and create the LLM agent instance used by the KGAgent.++ This method selects an appropriate system prompt based on `type_`, constructs or uses the provided toolset, applies an optional output schema, and assigns the created agent to `self.agent`.++ Parameters:+ type_ (Literal["normal", "graph-consolidator"]): Agent mode determining which system prompt to use.+ identification_params (dict): Identification details (IDs, names) used when building default tools.+ metadata (dict): Contextual metadata passed to tool creation and agent configuration.+ tools (Optional[List[BaseTool]]): Optional explicit list of tools to supply to the agent; if omitted, default tools are created.+ output_schema (Optional[BaseModel]): Optional response schema to enforce the agent's output format.+ extra_system_prompt (Optional[dict]): Optional additional content to interpolate into the selected system prompt.+ brain_id (str): Identifier of the knowledge brain/context to use when creating default tools.+ """system_prompt = Noneif type_ == "normal":system_prompt = KG_AGENT_SYSTEM_PROMPT.format(@@ -230,7 +260,15 @@ class KGAgent:self, node: Node, looking_for: Optional[Union[str, Iterable[str]]], limit: int) -> RetrieveNeighborsOutputSchema:"""- Retrieve the neighbors of a node.+ Retrieve neighboring nodes and relationship information for a given node, filtered by optional criteria and capped by a maximum result count.++ Parameters:+ node (Node): The main node whose neighbors should be retrieved.+ looking_for (Optional[Union[str, Iterable[str]]]): A single reason string or an iterable of reason strings used to filter or prioritize which neighbors to return; if None, no extra filtering is applied.+ limit (int): Maximum number of neighbor entries to return.++ Returns:+ RetrieveNeighborsOutputSchema: Structured neighbor data containing the matching nodes, relationships, and associated properties."""graph_db_prop_keys = self.kg.get_graph_property_keys()@@ -297,7 +335,19 @@ class KGAgent:max_retries: int = 3,) -> str:"""- Run the graph consolidator operator.+ Invoke the graph-consolidator agent to perform a consolidation task on the knowledge graph.++ Parameters:+ task (str): Natural-language instruction describing the consolidation operation to run.+ brain_id (str): Identifier of the knowledge graph brain to target; defaults to "default".+ timeout (int): Maximum seconds to wait for a single agent invocation before timing out.+ max_retries (int): Maximum number of retry attempts for the agent invocation when timeouts occur.++ Returns:+ status (str): `"OK"` when the consolidator completes successfully.++ Raises:+ TimeoutError: If a single invocation exceeds `timeout` seconds or if all retry attempts fail."""self._get_agent(@@ -315,6 +365,14 @@ class KGAgent:)def _invoke_agent():+ """+ Invoke the configured agent with the graph-consolidator prompt for the current task.++ Sends a user message containing the graph-consolidator task prompt to the agent and returns the agent's response.++ Returns:+ dict: Agent response containing generated message content and associated metadata (for example, token usage and model output).+ """return self.agent.invoke({"messages": [@@ -335,6 +393,17 @@ class KGAgent:reraise=True,)def _invoke_agent_with_retry():+ """+ Invoke the graph-consolidator agent with a timeout and update token accounting from the response.++ Waits up to `timeout` seconds for the agent invocation to complete. For any returned message that contains `usage_metadata`, updates the agent's token counters and `token_detail`. Returns the agent response dictionary.++ Returns:+ dict: The agent response.++ Raises:+ TimeoutError: If the agent invocation does not complete within `timeout` seconds.+ """try:with ThreadPoolExecutor(max_workers=1) as executor:future = executor.submit(_invoke_agent)@@ -369,7 +438,20 @@ class KGAgent:return "OK"def _update_token_counts(self, usage_metadata: dict):- """Extract all token counts from usage metadata"""+ """+ Update the agent's token counters from LLM usage metadata.++ Reads token counts from the provided `usage_metadata` mapping and increments the agent's+ internal counters: `input_tokens`, `output_tokens`, `cached_tokens`, and `reasoning_tokens`.+ Missing entries are treated as zero.++ Parameters:+ usage_metadata (dict): Usage metadata containing any of the following keys:+ - "input_tokens": total input token count (int)+ - "output_tokens": total output token count (int)+ - "input_token_details": dict with "cache_read" (int) for cached input tokens+ - "output_token_details": dict with "reasoning" (int) for reasoning/output tokens+ """# Base countsself.input_tokens += usage_metadata.get("input_tokens", 0)self.output_tokens += usage_metadata.get("output_tokens", 0)@@ -380,4 +462,4 @@ class KGAgent:# Output details (reasoning)output_details = usage_metadata.get("output_token_details", {})- self.reasoning_tokens += output_details.get("reasoning", 0)+ self.reasoning_tokens += output_details.get("reasoning", 0)\ No newline at end of filediff --git a/src/core/agents/scout_agent.py b/src/core/agents/scout_agent.pyindex a70cb5c..215d450 100644--- a/src/core/agents/scout_agent.py+++ b/src/core/agents/scout_agent.py@@ -89,6 +89,11 @@ class ScoutAgent:vector_store: VectorStoreAdapter,embeddings: EmbeddingsAdapter,):+ """+ Initialize a ScoutAgent with the provided adapters and reset internal agent and token-tracking state.++ Stores the provided LLM, cache, knowledge graph, vector store, and embeddings adapters on the instance, sets the agent and token_detail to None, and initializes input_tokens, output_tokens, cached_tokens, and reasoning_tokens counters to zero.+ """self.llm_adapter = llm_adapterself.cache_adapter = cache_adapterself.kg = kg@@ -102,6 +107,15 @@ class ScoutAgent:self.reasoning_tokens = 0def _get_tools(self, brain_id: str = "default") -> List[BaseTool]:+ """+ Provide the list of tools available to the agent for a given brain identifier.++ Parameters:+ brain_id (str): Identifier of the brain/context to retrieve tools for; defaults to "default".++ Returns:+ List[BaseTool]: A list of BaseTool instances available to the agent for the specified brain.+ """return []def _get_agent(@@ -132,7 +146,25 @@ class ScoutAgent:max_retries: int = 3,) -> ScoutAgentResponse:"""- Run the scout agent.+ Extract entities from the provided text using the Scout agent and return a structured response containing the entities and token usage.++ Performs an LLM invocation (with optional targeting context), applies retries with exponential backoff on timeouts, enforces a per-invocation timeout, and accumulates token usage from the agent responses.++ Parameters:+ text: The input text to extract entities from.+ targeting: Optional Node providing contextual targeting information (name, description, properties) to bias extraction.+ brain_id: Identifier for the agent/brain configuration to use.+ timeout: Maximum seconds to wait for a single agent invocation before treating it as a timeout.+ max_retries: Maximum number of retry attempts for timed-out invocations using exponential backoff.++ Returns:+ A ScoutAgentResponse containing:+ - entities: list of extracted ScoutEntity objects.+ - input_tokens: accumulated input token count observed during the run.+ - output_tokens: accumulated output token count observed during the run.++ Raises:+ TimeoutError: If a single invocation exceeds `timeout`, or if all retry attempts fail due to timeouts."""self._get_agent(@@ -170,6 +202,15 @@ class ScoutAgent:reraise=True,)def _invoke_agent_with_retry():+ """+ Invoke the agent in a separate thread, enforce the configured timeout, and update token accounting from the agent's response.++ Returns:+ dict: The agent response dictionary.++ Raises:+ TimeoutError: If the agent invocation exceeds the specified timeout.+ """try:with ThreadPoolExecutor(max_workers=1) as executor:future = executor.submit(_invoke_agent)@@ -211,7 +252,16 @@ class ScoutAgent:)def _update_token_counts(self, usage_metadata: dict):- """Extract all token counts from usage metadata"""+ """+ Update the agent's accumulated token counters from a usage metadata dictionary.++ Parameters:+ usage_metadata (dict): Metadata containing token counts. Expected keys:+ - "input_tokens": integer count to add to input_tokens (defaults to 0)+ - "output_tokens": integer count to add to output_tokens (defaults to 0)+ - "input_token_details": dict with optional "cache_read" integer to add to cached_tokens (defaults to 0)+ - "output_token_details": dict with optional "reasoning" integer to add to reasoning_tokens (defaults to 0)+ """# Base countsself.input_tokens += usage_metadata.get("input_tokens", 0)self.output_tokens += usage_metadata.get("output_tokens", 0)@@ -222,4 +272,4 @@ class ScoutAgent:# Output details (reasoning)output_details = usage_metadata.get("output_token_details", {})- self.reasoning_tokens += output_details.get("reasoning", 0)+ self.reasoning_tokens += output_details.get("reasoning", 0)\ No newline at end of filediff --git a/src/core/agents/tools/architect_agent/ArchitectAgentCheckUsedEntitiesTool.py b/src/core/agents/tools/architect_agent/ArchitectAgentCheckUsedEntitiesTool.pyindex 884b731..4c79a66 100644--- a/src/core/agents/tools/architect_agent/ArchitectAgentCheckUsedEntitiesTool.py+++ b/src/core/agents/tools/architect_agent/ArchitectAgentCheckUsedEntitiesTool.py@@ -21,6 +21,14 @@ class ArchitectAgentCheckUsedEntitiesTool(BaseTool):self,architect_agent: object,):+ """+ Initialize the tool with the given architect agent and set its description.++ This tool inspects the architect agent's used_entities_set to report entities that have been used; it should be invoked after relationships are created and entities are marked as used.++ Parameters:+ architect_agent (object): The architect agent instance whose used entities the tool will check.+ """description: str = ("Tool for checking used entities. ""You must call this tool after calling the architect_agent_create_relationship tool and after marking entities as used."@@ -32,9 +40,17 @@ class ArchitectAgentCheckUsedEntitiesTool(BaseTool):)def _run(self, *args, **kwargs) -> str:+ """+ Collect the set of entities marked as used by the architect agent and return them as a JSON string.++ Each entity is converted to a plain mapping by calling `model_dump()` if present on the entity, otherwise `dict()`, and the resulting list of mappings is serialized to JSON.++ Returns:+ json_str (str): JSON-formatted string containing a list of serialized entity mappings.+ """entities_list = [entity.model_dump() if hasattr(entity, "model_dump") else entity.dict()for entity in self.architect_agent.used_entities_set]print("[DEBUG (architect_agent_check_used_entities)]: ", entities_list)- return json.dumps(entities_list)+ return json.dumps(entities_list)\ No newline at end of filediff --git a/src/core/agents/tools/architect_agent/ArchitectAgentCreateRelationshipTool.py b/src/core/agents/tools/architect_agent/ArchitectAgentCreateRelationshipTool.pyindex 948f5c6..6b6e5a7 100644--- a/src/core/agents/tools/architect_agent/ArchitectAgentCreateRelationshipTool.py+++ b/src/core/agents/tools/architect_agent/ArchitectAgentCreateRelationshipTool.py@@ -86,6 +86,17 @@ class ArchitectAgentCreateRelationshipTool(BaseTool):brain_id: str = "default",targeting: Optional[Node] = None,):+ """+ Initialize the tool for creating a set of relationships between entities for a single phrase.++ Parameters:+ architect_agent (object): The owning architect agent instance that this tool will update (holds state like entities, token details, and relationships).+ text (str): The source text or phrase that the relationships represent.+ entities (Optional[Dict[str, ScoutEntity]]): Mapping of entity UUIDs to ScoutEntity objects available to resolve relationship subjects/objects; empty dict if None.+ kg (GraphAdapter): Graph adapter used for resolving and persisting graph-related operations.+ brain_id (str): Identifier of the target brain/namespace for created relationships.+ targeting (Optional[Node]): Optional target node to associate with created relationships.+ """description: str = ("Tool for creating a set of relationships between entities. ""Use this tool to create a set of relationships between entities that together compose a single phrase. "@@ -112,6 +123,24 @@ class ArchitectAgentCreateRelationshipTool(BaseTool):description: strdef _run(self, *args, **kwargs) -> str:+ """+ Validate and create architect relationships from the provided input, normalize them via the JanitorAgent, enqueue ingestion, and return the operation result.++ Parameters:+ relationships (list[dict], optional): A list of relationship objects provided either as the first positional argument (or as args[0]["relationships"]) or via the "relationships" keyword. Each relationship dict should include:+ - subject: UUID or name of the subject entity (required)+ - predicate: relationship name/label+ - object: UUID or name of the object entity (required)+ - description: textual description of the relationship+ - amount: optional numeric value associated with the relationship+ - properties: optional dict of additional properties+ The method resolves subject and object against the tool's entity map and the architect_agent's used_entities_set.++ Returns:+ A success JSON string on successful creation: '{"status": "success", "message": "relationships created successfully"}'.+ An error string if the required "relationships" parameter is missing or if a subject/object cannot be resolved (e.g., 'Subject not found in entities: ...').+ A dict with status "ERROR" when the JanitorAgent reports wrong relationships; the dict includes keys "wrong_relationships" and "newly_created_nodes".+ """rel_key = str(uuid.uuid4())print(@@ -435,4 +464,4 @@ class ArchitectAgentCreateRelationshipTool(BaseTool):return json.dumps({"status": "success", "message": "relationships created successfully"}- )+ )\ No newline at end of filediff --git a/src/core/agents/tools/architect_agent/ArchitectAgentGetRemainingEntitiesToProcessTool.py b/src/core/agents/tools/architect_agent/ArchitectAgentGetRemainingEntitiesToProcessTool.pyindex 1c9622b..c9b1009 100644--- a/src/core/agents/tools/architect_agent/ArchitectAgentGetRemainingEntitiesToProcessTool.py+++ b/src/core/agents/tools/architect_agent/ArchitectAgentGetRemainingEntitiesToProcessTool.py@@ -21,6 +21,12 @@ class ArchitectAgentGetRemainingEntitiesToProcessTool(BaseTool):self,architect_agent: object,):+ """+ Initialize the tool with an architect agent whose entities will be inspected to determine remaining work.++ Parameters:+ architect_agent (object): The architect agent instance that exposes an `entities` mapping; each entity is expected to support `model_dump(mode="json")` for serialization.+ """description: str = ("Tool for getting the remaining entities to process. ""Use this tool to get the remaining entities to process. "@@ -33,6 +39,12 @@ class ArchitectAgentGetRemainingEntitiesToProcessTool(BaseTool):)def _run(self, *args, **kwargs) -> str:+ """+ Get a JSON string listing the remaining entities to process.++ Returns:+ str: A JSON array string where each element is the serialized representation of an entity produced by calling `model_dump(mode="json")` on each entity in `self.architect_agent.entities`.+ """remaining_entities = json.dumps([entity.model_dump(mode="json")@@ -43,4 +55,4 @@ class ArchitectAgentGetRemainingEntitiesToProcessTool(BaseTool):"[DEBUG (architect_agent_get_remaining_entities_to_process)]: ",remaining_entities,)- return remaining_entities+ return remaining_entities\ No newline at end of filediff --git a/src/core/agents/tools/architect_agent/ArchitectAgentMarkEntitiesAsUsedTool.py b/src/core/agents/tools/architect_agent/ArchitectAgentMarkEntitiesAsUsedTool.pyindex dac8662..b78c416 100644--- a/src/core/agents/tools/architect_agent/ArchitectAgentMarkEntitiesAsUsedTool.py+++ b/src/core/agents/tools/architect_agent/ArchitectAgentMarkEntitiesAsUsedTool.py@@ -35,6 +35,12 @@ class ArchitectAgentMarkEntitiesAsUsedTool(BaseTool):self,architect_agent: object,):+ """+ Initialize the tool with a reference to the architect agent whose entities may be marked as used.++ Parameters:+ architect_agent (object): The architect agent instance whose `entities` and `used_entities_set` this tool will update.+ """description: str = ("Tool that marks entities as used. ""Use this tool to mark entities as used. "@@ -46,6 +52,25 @@ class ArchitectAgentMarkEntitiesAsUsedTool(BaseTool):)def _run(self, *args, **kwargs) -> str:+ """+ Mark the given entity UUIDs as used on the associated architect agent.++ Accepts several input shapes to identify the UUIDs to mark: a dict argument with the key "entity_uuids", a keyword "entity_uuids", a list passed as the first positional argument, or keywords "entities" or "uuids". If a single string is provided it will be treated as a single UUID. If no recognizable input is provided, no entities are marked.++ Parameters:+ *args: Positional arguments; supported forms include:+ - A dict containing the key "entity_uuids" with a list of UUID strings.+ - A list of UUID strings as the first positional argument.+ **kwargs: Keyword arguments; supported keys include:+ - "entity_uuids", "entities", or "uuids" with a list (or single string) of UUIDs.+ - If exactly one keyword is provided, its value is used as the UUID list.++ Returns:+ result (str): The string "OK" after processing.++ Side effects:+ For each provided UUID found in self.architect_agent.entities, the entity is removed from that mapping and appended to self.architect_agent.used_entities_set.+ """entities_to_mark = []if args and isinstance(args[0], dict) and "entity_uuids" in args[0]:@@ -92,4 +117,4 @@ class ArchitectAgentMarkEntitiesAsUsedTool(BaseTool):entities_to_mark,)- return "OK"+ return "OK"\ No newline at end of filediff --git a/src/core/agents/tools/janitor_agent/JanitorAgentGetSchemaTool.py b/src/core/agents/tools/janitor_agent/JanitorAgentGetSchemaTool.pyindex 07ae26f..32f611a 100644--- a/src/core/agents/tools/janitor_agent/JanitorAgentGetSchemaTool.py+++ b/src/core/agents/tools/janitor_agent/JanitorAgentGetSchemaTool.py@@ -54,6 +54,20 @@ class JanitorAgentGetSchemaTool(BaseTool):)def _run(self, *args, **kwargs) -> str:+ """+ Retrieve a specified part of the knowledge graph schema and return it as a pretty-printed JSON string.++ Parameters:+ target (str, optional): One of "node_labels", "relationship_types", or "event_names". Defaults to "node_labels".++ Returns:+ str: A JSON-formatted string (indent=4) containing the requested list from the schema:+ - labels for "node_labels"+ - relationships for "relationship_types"+ - event_names for "event_names"+ If `target` is not one of the accepted values, returns the error message+ "Invalid target parameter. It must be either 'node_labels' or 'relationship_types' or 'event_names'".+ """_target = kwargs.get("target", "node_labels").lower()schema_result = self.kg.get_schema(brain_id=self.brain_id)@@ -67,4 +81,4 @@ class JanitorAgentGetSchemaTool(BaseTool):elif _target == "event_names":event_names = schema_result.get("event_names", [])return json.dumps(event_names, indent=4)- return "Invalid target parameter. It must be either 'node_labels' or 'relationship_types' or 'event_names'"+ return "Invalid target parameter. It must be either 'node_labels' or 'relationship_types' or 'event_names'"\ No newline at end of filediff --git a/src/core/agents/tools/janitor_agent/JanitorAgentSearchEntitiesTool.py b/src/core/agents/tools/janitor_agent/JanitorAgentSearchEntitiesTool.pyindex 097544a..61b4892 100644--- a/src/core/agents/tools/janitor_agent/JanitorAgentSearchEntitiesTool.py+++ b/src/core/agents/tools/janitor_agent/JanitorAgentSearchEntitiesTool.py@@ -52,6 +52,14 @@ class JanitorAgentSearchEntitiesTool(BaseTool):vector_store: VectorStoreAdapter,brain_id: str = "default",):+ """+ Initialize the JanitorAgentSearchEntitiesTool with the required adapters and configuration.++ This tool performs plain-text searches against the knowledge graph and an optional vector store, aggregating results into a mapping from a sanitized query key to the list of matching entities.++ Parameters:+ brain_id (str): Identifier of the brain (knowledge scope) to use for searches. Defaults to "default".+ """description: str = ("Tool to search for entities in the knowledge graph by plain text names. ""Call this tool once to search for a list of entities with different names, "@@ -69,6 +77,17 @@ class JanitorAgentSearchEntitiesTool(BaseTool):)def _run(self, *args, **kwargs) -> str:+ """+ Search multiple query strings for matching entities in the knowledge graph and vector store, and return the aggregated results as a JSON-formatted mapping keyed by a sanitized query string.++ Parameters:+ args: If provided, the first positional argument is treated as the list of query strings to process.+ kwargs:+ queries (List[str]): List of query strings to search for when not passed as a positional argument.++ Returns:+ str: A JSON string mapping each sanitized query to either a list of found entity objects (each serialized to JSON) or a message indicating no matches were found.+ """_query = ""if len(args) > 0:_query = args[0]@@ -81,6 +100,18 @@ class JanitorAgentSearchEntitiesTool(BaseTool):found_entities: Dict[str, Union[str, List[Node]]] = {}def _clean_query(query: str) -> str:+ """+ Sanitizes a query string into a normalized key suitable for dictionary lookup.++ Removes common punctuation, trims leading/trailing whitespace, converts to lowercase,+ and replaces spaces and hyphens with underscores.++ Parameters:+ query (str): The input query text to normalize.++ Returns:+ sanitized (str): The normalized query string with punctuation removed, spaces and hyphens replaced by underscores, trimmed and lowercased.+ """chars_to_remove = "'.\"()[]{}\\|*/+=<>,!?:;"chars_to_underscore = " -"translation_table = str.maketrans(@@ -125,4 +156,4 @@ class JanitorAgentSearchEntitiesTool(BaseTool):f.model_dump(mode="json") for f in founds]- return json.dumps(found_entities, indent=4)+ return json.dumps(found_entities, indent=4)\ No newline at end of filediff --git a/src/core/agents/tools/kg_agent/KGAgentExecuteGraphOperationTool.py b/src/core/agents/tools/kg_agent/KGAgentExecuteGraphOperationTool.pyindex 9939279..e9a16ef 100644--- a/src/core/agents/tools/kg_agent/KGAgentExecuteGraphOperationTool.py+++ b/src/core/agents/tools/kg_agent/KGAgentExecuteGraphOperationTool.py@@ -27,6 +27,15 @@ class KGAgentExecuteGraphOperationTool(BaseTool):def __init__(self, kg_agent, kg: GraphAdapter, database_desc: str, brain_id: str = "default"):+ """+ Initialize the KGAgentExecuteGraphOperationTool with the specified components and configuration.++ Parameters:+ kg_agent: The knowledge graph agent to execute operations.+ kg (GraphAdapter): The graph adapter managing the graph database interface.+ database_desc (str): Description of the underlying graph database to include in the tool's description.+ brain_id (str): Identifier for the brain context to use, defaults to "default".+ """description: str = ("Use this tool to execute any type of graph operation search/edit/query/delete/etc. ""The query should be a valid graph operation depending on the graph database type."@@ -50,6 +59,17 @@ class KGAgentExecuteGraphOperationTool(BaseTool):)def _run(self, *args, **kwargs) -> str:+ """+ Execute a graph operation using a query extracted from the provided arguments and return the KG adapter's response.++ The function accepts several argument shapes to locate the query:+ - positional: first positional argument is used as the query string.+ - kwargs 'args' as dict: use the value of the 'query' key.+ - kwargs 'args' as list: use the first element if it's a string, or the first element's 'query' value if it's a dict.++ Returns:+ The result returned by the graph adapter's execute_operation for the resolved query, or the string "No query provided in the arguments or kwargs" if no query could be found.+ """_query = ""if len(args) > 0:_query = args[0]@@ -80,4 +100,4 @@ class KGAgentExecuteGraphOperationTool(BaseTool):response,)- return response+ return response\ No newline at end of filediff --git a/src/core/backups/backup_creator.py b/src/core/backups/backup_creator.pyindex 6dacc50..f7bcb40 100644--- a/src/core/backups/backup_creator.py+++ b/src/core/backups/backup_creator.py@@ -12,7 +12,13 @@ Modified By: Christian Nonis <[email protected]>def create_backup(brain_id: str) -> Backup:"""- Create a backup of the knowledge graph.+ Create a backup of the knowledge graph identified by brain_id.++ Parameters:+ brain_id (str): Identifier of the brain (knowledge graph) to back up.++ Returns:+ Backup: Object containing metadata for the created backup and a download link or path to the stored backup."""# Create Graph backup@@ -28,4 +34,4 @@ def create_backup(brain_id: str) -> Backup:# Return the backup path download link object- pass+ pass\ No newline at end of filediff --git a/src/core/layers/graph_consolidation/graph_consolidation.py b/src/core/layers/graph_consolidation/graph_consolidation.pyindex 76bcae2..2a2055f 100644--- a/src/core/layers/graph_consolidation/graph_consolidation.py+++ b/src/core/layers/graph_consolidation/graph_consolidation.py@@ -67,10 +67,15 @@ def consolidate_graph(brain_id: str = "default",) -> ConsolidationResponse:"""- Commits the final review of the new kg state normalizing names, connections and removing duplicates.-- Only macroscopic fixes are being done here, fixes that involve multiple relationships and areas of the graph.- Atomic fixes on Nodes and Relationships are being done by the janitor_agent calls inside the ArchitectAgentCreateRelationshipTool.+ Consolidates and normalizes a collection of new knowledge-graph relationships across the graph.++ Processes the provided relationships in batches to perform macroscopic fixes such as name normalization, connection normalization, and deduplication across multiple relationships and graph areas. Collects and merges token usage metrics produced during consolidation.++ Parameters:+ brain_id (str): Identifier of the target knowledge graph/brain to consolidate into (defaults to "default").++ Returns:+ ConsolidationResponse: Response containing merged token usage details for the consolidation run."""batches = [@@ -152,4 +157,4 @@ def consolidate_graph(return ConsolidationResponse(token_detail=token_detail,- )+ )\ No newline at end of filediff --git a/src/core/saving/auto_kg.py b/src/core/saving/auto_kg.pyindex fcd3c16..0f2a992 100644--- a/src/core/saving/auto_kg.py+++ b/src/core/saving/auto_kg.py@@ -30,7 +30,15 @@ def enrich_kg_from_input(input: str, targeting: Optional[Node] = None, brain_id: str = "default") -> str:"""- Enrich the knowledge graph from the input.+ Orchestrates enrichment of the knowledge graph from a free-text input.++ Runs the scout and architect agents to extract entities and relationships from the provided input, optionally consolidates the resulting relationships into the graph, and reports token usage and cost metrics. Side effects include updating the knowledge graph and printing debug and cost summaries to standard output.++ Parameters:+ input (str): Free-text content to process and ingest into the knowledge graph.+ targeting (Optional[Node]): Optional target node guiding where or how the input should be applied within the graph.+ brain_id (str): Identifier for the processing context/brain to use for agent operations and consolidation.+"""ingestion_manager = IngestionManager(@@ -116,4 +124,4 @@ def enrich_kg_from_input(print(f"> Cost/Character -> ${((token_details.input.total * config.pricing.input_token_price + token_details.output.total * config.pricing.output_token_price) / len(input)):.12f}")- print("-----------------------------------")+ print("-----------------------------------")\ No newline at end of filediff --git a/src/core/saving/ingestion_manager.py b/src/core/saving/ingestion_manager.pyindex 151e50c..fd82377 100644--- a/src/core/saving/ingestion_manager.py+++ b/src/core/saving/ingestion_manager.py@@ -23,6 +23,17 @@ class IngestionManager:vector_store_adapter: VectorStoreAdapter,graph_adapter: GraphAdapter,):+ """+ Initialize the ingestion manager with adapter instances and prepare internal caches.++ Parameters:+ embeddings_adapter (EmbeddingsAdapter): Adapter used to produce vector embeddings from text.+ vector_store_adapter (VectorStoreAdapter): Adapter used to persist vectors and return vector IDs.+ graph_adapter (GraphAdapter): Adapter used to interact with the knowledge graph.++ Detailed behavior:+ Stores the provided adapters on the instance and initializes `resolved_cache` and `metadata` as empty dictionaries for tracking processed entities and their metadata.+ """self.embeddings = embeddings_adapterself.vector_store = vector_store_adapterself.kg = graph_adapter@@ -30,6 +41,21 @@ class IngestionManager:self.metadata = {}def process_node_vectors(self, node_data: ScoutEntity, brain_id):+ """+ Process and store an embedding for the given node and cache its vector id.++ If the node's name is already resolved in the manager cache, returns immediately.+ Otherwise embeds the node's name, attaches labels/name/uuid metadata to the embedding,+ stores the resulting vector in the "nodes" vector store under the provided brain, and+ updates the node's properties and the manager's resolved cache with the new vector id.++ Parameters:+ node_data (ScoutEntity): Node object whose name will be embedded and whose properties may be updated.+ brain_id: Identifier of the brain/namespace to use when storing vectors.++ Returns:+ The node's UUID.+ """if node_data.name in self.resolved_cache:return node_data.uuid@@ -54,6 +80,24 @@ class IngestionManager:return node_data.uuiddef process_rel_vectors(self, rel_data: ArchitectAgentRelationship, brain_id):+ """+ Embed a relationship's description and store the resulting vector in the relationships vector store.++ If the relationship has a non-empty description, the description text is embedded and the resulting vector (with metadata including UUID, related node IDs, and predicate) is added to the "relationships" vector store using the provided brain_id. On success the relationship's properties are updated with the stored vector ID.++ Parameters:+ rel_data (ArchitectAgentRelationship): Relationship object whose description will be embedded.+ brain_id: Identifier for the brain/context to use when storing the vector.++ Returns:+ tuple: (relationship UUID, vector ID string if a vector was stored, otherwise None)++ Raises:+ TypeError: If rel_data is not an instance of ArchitectAgentRelationship.++ Side effects:+ Updates rel_data.properties['v_id'] when a vector is stored and calls the vector store adapter to persist the embedding.+ """if not isinstance(rel_data, ArchitectAgentRelationship):raise TypeError(f"Expected ArchitectAgentRelationship, got {type(rel_data)}"@@ -78,4 +122,4 @@ class IngestionManager:print("[ ! ]Relationship not embedded:", rel_data)return rel_data.uuid, (rel_data.properties.get("v_id") if rel_data.properties else None- )+ )\ No newline at end of filediff --git a/src/core/search/entities.py b/src/core/search/entities.pyindex 9690e16..ee7402f 100644--- a/src/core/search/entities.py+++ b/src/core/search/entities.py@@ -19,7 +19,12 @@ import unicodedatadef extract_str_entities_from_text(text: str) -> List[str]:"""- Decompose a text into string entity elements.+ Extracts candidate string entities from the given text.++ Normalizes Unicode, splits the text into word tokens, and returns a list of unique, entity-like strings in order of first appearance. Tokens that are common multilingual stop words, shorter than two characters, contain no alphabetic character, or are duplicates are excluded. Tokens that originally start with an uppercase letter are returned with their original casing; other tokens are returned with the first letter capitalized.++ Returns:+ List[str]: A list of filtered, capitalized entity-like strings."""if not text or not text.strip():return []@@ -263,4 +268,4 @@ def search_entities(result = graph_adapter.search_entities(brain_id, limit, skip, node_labels, query_text)- return result+ return result\ No newline at end of filediff --git a/src/core/search/entity_context.py b/src/core/search/entity_context.pyindex 2f86e90..ec68e1f 100644--- a/src/core/search/entity_context.py+++ b/src/core/search/entity_context.py@@ -19,6 +19,13 @@ from src.services.kg_agent.main import (class EntityContext:def __init__(self, target: str, brain_id: str = "default"):+ """+ Initialize the EntityContext with a target entity and knowledge brain identifier.++ Parameters:+ target (str): Text of the entity to resolve in the knowledge graph.+ brain_id (str): Identifier of the brain/store to query. Defaults to "default".+ """self.target = targetself.brain_id = brain_id@@ -26,7 +33,17 @@ class EntityContext:self, context_depth: int = 3) -> Tuple[Node, list[dict], list[dict]]:"""- Gets context around an entity.+ Retrieve contextual information related to the target entity up to a specified depth.++ Returns the target node, its neighborhood structure, a list of unique textual descriptions from the node and predicate metadata, and a structured natural language representation of the neighborhood.++ @param context_depth The depth of the neighborhood context to retrieve around the target entity.++ @returns A tuple containing:+ - The target node object.+ - A list representing the neighborhood of the target node.+ - A list of unique descriptive texts collected from the nodes and predicates.+ - A structured list suitable for natural language processing, representing relationships and descriptions within the neighborhood."""text_contexts = set()@@ -55,6 +72,18 @@ class EntityContext:def _get_text_context(neighbors: list[dict], append_to_web: bool = False) -> list[dict]:+ """+ Builds structured textual context entries from a neighborhood of nodes.++ Processes each neighbor dictionary to collect node and predicate descriptions into the outer `text_contexts` set, and constructs an entry that includes the predicate description, information direction, and a nested structure mapping predicate and node names to descriptions and further nested info. Nested neighbors are processed recursively and included under the `info` key. If `append_to_web` is True, each entry is appended to the outer `natural_language_web` list.++ Parameters:+ neighbors (list[dict]): A list of neighbor mappings; each dict is expected to contain keys like `'node'`, `'predicate'`, and optionally `'neighbors'`.+ append_to_web (bool): If True, append each constructed entry to the module-level `natural_language_web` list.++ Returns:+ list[dict] or None: A list of constructed entry dictionaries, or `None` if no entries were produced.+ """entries = []for nn in neighbors:node = nn.get("node")@@ -86,4 +115,4 @@ class EntityContext:_get_text_context(neighborhood, append_to_web=True)- return (target_node, neighborhood, list(text_contexts), natural_language_web)+ return (target_node, neighborhood, list(text_contexts), natural_language_web)\ No newline at end of filediff --git a/src/core/search/entity_info.py b/src/core/search/entity_info.pyindex c7ae5dc..dae5b22 100644--- a/src/core/search/entity_info.py+++ b/src/core/search/entity_info.py@@ -38,6 +38,12 @@ class MatchPath(BaseModel):class EventSynergyRetriever:def __init__(self, memory_id: str):+ """+ Initialize the retriever with a memory identifier that is also used as the brain identifier.++ Parameters:+ memory_id (str): Identifier for the memory store; assigned to both `memory_id` and `brain_id` on the instance.+ """self.memory_id = memory_idself.brain_id = memory_id@@ -53,8 +59,17 @@ class EventSynergyRetriever:):# -> List[SynergyPath]:"""- Recursively crawls the graph to find high-similarity paths- beyond the initial Triangle.+ Traverse graph neighbors from the given node to locate the connection path most similar to the provided query embedding, searching up to the specified depth.++ Parameters:+ current_node_id (str): UUID of the node to start exploration from.+ query_embedding (List[float]): Embedding vector representing the query used to score neighbor relations.+ depth (int): Remaining recursion depth; exploration stops when depth <= 0.+ visited_ids (Set[str]): Set of visited node UUIDs; this set is mutated to include nodes visited during traversal to avoid cycles.+ most_similar_conn_rel_tuple (Optional[Tuple[Tuple[Predicate, Node], float]]): Optional running best match (relation tuple and its similarity) to carry forward during recursion.++ Returns:+ results (List[Tuple[Tuple[Predicate, Node], float]]): A list containing the most similar (predicate, node) tuple paired with its similarity score found along the explored path, or an empty list if no suitable connections are found."""if depth <= 0:return []@@ -135,8 +150,15 @@ class EventSynergyRetriever:self, target: str, query: str, max_depth: int = 3) -> MatchPath:"""- Starts from a Member and recursively finds the most relevant- synergy paths in the graph.+ Finds and assembles the most relevant graph traversal path(s) that link a target entity to content matching a query.++ Parameters:+ target (str): Text used to locate the starting node in the node vector store.+ query (str): Text used to compute an embedding that guides relevance scoring of neighboring relationships.+ max_depth (int): Maximum recursion depth when exploring neighboring nodes.++ Returns:+ MatchPath: A hierarchical MatchPath rooted at the resolved target node containing the best-match path(s) and an aggregated similarity score. If the target node or any required embeddings are missing, returns a MatchPath with an empty path and similarity 0.0."""query_embedding = embeddings_adapter.embed_text(query)@@ -229,4 +251,4 @@ class EventSynergyRetriever:current_path.children.append(match_paths[i])current_path = match_paths[i]- return root_path+ return root_path\ No newline at end of filediff --git a/src/core/search/entity_sibilings.py b/src/core/search/entity_sibilings.pyindex ad5c3aa..cd5261c 100644--- a/src/core/search/entity_sibilings.py+++ b/src/core/search/entity_sibilings.py@@ -21,13 +21,30 @@ from src.services.kg_agent.main import (class EntitySinergyRetriever:def __init__(self, brain_id: str = "default"):+ """+ Initialize the retriever with the identifier of the brain (knowledge graph) to operate against.++ Parameters:+ brain_id (str): Identifier of the brain/knowledge graph to use for adapter calls. Defaults to "default".+ """self.brain_id = brain_iddef retrieve_sibilings(self, target: str, polarity: Literal["same", "opposite"]) -> Tuple[Node, List[EntitySynergy]]:"""- Retrieve the siblings of an entity.+ Find related entities ("siblings") for a given target text by locating the target node and assembling EntitySynergy connections from its neighbors and embedding-based similarity.++ This returns the resolved target graph node (or None if no matching node is found) and a list of EntitySynergy objects that represent related nodes discovered via neighbor relationships and vector-similarity matches. The method may return early with an empty list when required intermediate data (target node, similarity seeds, or similar nodes) is missing.++ Parameters:+ target: The text used to locate the target entity in the node store.+ polarity: A directive indicating the type of relation to retrieve; expected values are "same" or "opposite".++ Returns:+ (target_node, connections):+ - target_node (Node or None): the graph node matching the provided target text, or `None` if not found.+ - connections (List[EntitySynergy]): a list of EntitySynergy entries representing related entities; may be empty."""target_embedding = embeddings_adapter.embed_text(target)target_node_vs = vector_store_adapter.search_vectors(@@ -164,4 +181,4 @@ class EntitySinergyRetriever:))- return target_node, positivep_connections+ return target_node, positivep_connections\ No newline at end of filediff --git a/src/lib/embeddings/client_small.py b/src/lib/embeddings/client_small.pyindex bfbc509..7fad0e9 100644--- a/src/lib/embeddings/client_small.py+++ b/src/lib/embeddings/client_small.py@@ -21,8 +21,17 @@ class EmbeddingsClientSmall(EmbeddingsClient):self.model = _modeldef embed_text(self, text: str) -> list[float]:+ """+ Return the embedding vector for the given text using the configured model.++ Parameters:+ text (str): Input text to encode.++ Returns:+ list[float]: Dense embedding vector representing the input text.+ """embedding = self.model.encode(text, convert_to_numpy=True)return embedding.tolist()-_embeddings_small_client = EmbeddingsClientSmall()+_embeddings_small_client = EmbeddingsClientSmall()\ No newline at end of filediff --git a/src/lib/llm/client_small.py b/src/lib/llm/client_small.pyindex 1a0e01d..5fa9c2a 100644--- a/src/lib/llm/client_small.py+++ b/src/lib/llm/client_small.py@@ -72,6 +72,17 @@ class LLMClientSmall(LLM):@propertydef langchain_model(self):+ """+ Lazily initialize (thread-safe) and return a LangChain ChatVertexAI wrapper configured for Vertex AI.++ This property constructs the ChatVertexAI instance on first access, sets the+ GOOGLE_APPLICATION_CREDENTIALS environment variable from config.gcp.credentials_path,+ and caches the resulting model for subsequent calls. Initialization is guarded+ with a lock to be safe across threads.++ Returns:+ ChatVertexAI: The initialized LangChain ChatVertexAI model instance.+ """if self._langchain_model is None:with self._lock:if self._langchain_model is None:@@ -98,6 +109,22 @@ class LLMClientSmall(LLM):def generate_text(self, prompt: str, max_new_tokens: int = 100000, timeout: int = None) -> str:+ """+ Generate plain-text completion for a prompt using the configured Vertex AI model.++ If `prompt` is empty or only whitespace, returns the fixed message "Input prompt is empty". The method will retry transient failures up to 3 times and enforce the provided `timeout` per attempt.++ Parameters:+ prompt (str): The input prompt to complete.+ max_new_tokens (int): Maximum number of tokens to generate for the completion. If falsy, no token limit is passed to the API.+ timeout (int): Maximum seconds to wait for a single generation attempt; defaults to the client's default timeout.++ Returns:+ str: The generated plain-text completion, or "Input prompt is empty" when the prompt is empty.++ Raises:+ TimeoutError: If generation times out or all retry attempts fail.+ """if not prompt or len(prompt.strip()) == 0:return "Input prompt is empty"@@ -105,6 +132,14 @@ class LLMClientSmall(LLM):from google.genai.types import GenerateContentConfigdef _generate():+ """+ Call the LLM client's generate_content API for the current model and request a plain-text response.++ If `max_new_tokens` is set in the enclosing scope, the request will include `max_output_tokens` with that value.++ Returns:+ The raw response from the client's `generate_content` call containing the generated plain-text output.+ """return self.client.models.generate_content(model=self.model,contents=[prompt],@@ -155,10 +190,29 @@ class LLMClientSmall(LLM):max_retries: int = 3,timeout: int = None,) -> dict:+ """+ Generate JSON content from a given prompt using the configured language model.++ Attempts generation up to a specified number of retries with exponential backoff and enforces a timeout for each attempt. Parses the generated text as JSON and returns it as a dictionary.++ Parameters:+ max_new_tokens (int): Maximum number of tokens to generate in the response.+ max_retries (int): Number of retry attempts for generation on failure.+ timeout (int): Maximum time in seconds to wait for each generation attempt.++ Returns:+ dict: The generated content parsed as a JSON dictionary.+ """timeout = timeout or self.default_timeoutfrom google.genai.types import GenerateContentConfigdef _generate():+ """+ Generate JSON content from the model based on the given prompt.++ Returns:+ dict: The parsed JSON response generated from the prompt.+ """_response = self.client.models.generate_content(model=self.model,contents=[prompt],@@ -209,4 +263,4 @@ class LLMClientSmall(LLM):raise-_llm_small_client = LLMClientSmall()+_llm_small_client = LLMClientSmall()\ No newline at end of filediff --git a/src/lib/mongo/client.py b/src/lib/mongo/client.pyindex 94ff93f..02cc2e9 100644--- a/src/lib/mongo/client.py+++ b/src/lib/mongo/client.py@@ -400,6 +400,19 @@ class MongoClient(DataClient):def update_structured_data(self, structured_data: StructuredData, brain_id: str) -> StructuredData:+ """+ Update an existing StructuredData record in the specified brain's structured_data collection.++ Parameters:+ structured_data (StructuredData): The structured data object whose stored record will be updated; its `id` is used to locate the document.+ brain_id (str): Identifier of the brain (database) containing the structured_data collection to update.++ Returns:+ StructuredData: The same `structured_data` object that was passed in.++ Notes:+ The function updates the document matching `structured_data.id` by setting its fields to those from `structured_data`. If no matching document exists, no document is inserted.+ """collection = self.get_collection("structured_data", database=brain_id)collection.update_one({"id": structured_data.id},@@ -408,4 +421,4 @@ class MongoClient(DataClient):return structured_data-_mongo_client = MongoClient()+_mongo_client = MongoClient()\ No newline at end of filediff --git a/src/lib/neo4j/client.py b/src/lib/neo4j/client.pyindex eb2b6b7..18ba81f 100644--- a/src/lib/neo4j/client.py+++ b/src/lib/neo4j/client.py@@ -191,7 +191,16 @@ class Neo4jClient(GraphClient):metadata: Optional[dict] = None,) -> list[Node] | str:"""- Add nodes to the graph.+ Insert multiple nodes into the specified brain's graph and return representations of the created nodes.++ Ensures the target database exists, merges or creates each node by its identification properties (at minimum the node's name), sets node properties and standard attributes (description, happened_at, last_updated, metadata, observations, polarity, and uuid), and retries on transient database-not-found errors.++ Parameters:+ identification_params (dict, optional): Additional property keys and values used to identify (MERGE) nodes besides name; keys will be normalized to property-style keys.+ metadata (dict, optional): Metadata to attach to each node; this metadata is merged with any existing node.metadata for the returned Node objects.++ Returns:+ list[Node]: A list of Node objects representing the added nodes. Each returned Node preserves the original node fields and has its metadata set to the merge of the node's own metadata and the provided `metadata`."""results = []self.ensure_database(brain_id)@@ -274,7 +283,18 @@ class Neo4jClient(GraphClient):brain_id: str,) -> str:"""- Add a relationship between two nodes to the graph.+ Create or update a relationship of the given predicate type between two existing nodes and set relationship attributes.++ Matches the source node by its labels and name (from `subject`) and the target node by its labels and name (from `to_object`), merges a relationship of type `predicate.name` between them, and sets relationship fields (including `uuid`, `description`, `v_id`, and any provided `properties`, `happened_at`, `flow_key`, `last_updated`) from the supplied `predicate`, `subject`, and `to_object` objects. Ensures the target database exists before executing the query.++ Parameters:+ subject (Node): Source node whose labels and `name` are used to find the relationship start.+ predicate (Predicate): Relationship descriptor whose `name` determines the relationship type and whose fields supply relationship attributes to set.+ to_object (Node): Target node whose labels and `name` are used to find the relationship end.+ brain_id (str): Database name to run the query against.++ Returns:+ query_result: The raw result returned by the Neo4j driver for the executed Cypher query."""objects = [subject, to_object, predicate]@@ -458,8 +478,16 @@ class Neo4jClient(GraphClient):def get_by_uuid(self, uuid: str, brain_id: str) -> Node:"""- DEPRECATED: use get_by_uuids instead.- Get a node by its UUID.+ Retrieve a node by its UUID.++ Deprecated: use `get_by_uuids` which returns richer node data and supports batching.++ Parameters:+ uuid (str): The UUID of the node to retrieve.+ brain_id (str): Target database/brain identifier.++ Returns:+ Node or None: The matching node, or `None` if no node with the given UUID exists."""cypher_query = """MATCH (n) WHERE n.uuid = $uuid@@ -481,7 +509,14 @@ class Neo4jClient(GraphClient):def get_by_uuids(self, uuids: list[str], brain_id: str) -> list[Node]:"""- Get nodes by their UUIDs.+ Retrieve nodes that match the given UUIDs from the specified database.++ Parameters:+ uuids (list[str]): Node UUIDs to fetch.+ brain_id (str): Name of the Neo4j database to query.++ Returns:+ list[Node]: Nodes with identifiers, names, labels, descriptions, and properties; includes, when available, polarity, happened_at, last_updated, observations, and metadata."""cypher_query = f"""MATCH (n) WHERE n.uuid IN ["{'","'.join(uuids)}"]@@ -568,13 +603,19 @@ class Neo4jClient(GraphClient):of_types: Optional[list[str]] = None,) -> Dict[str, List[Tuple[Predicate, Node]]]:"""- Retrieve neighbor triples for the given node where the neighbor shares at least one label with the source node.-+ Retrieve neighboring nodes connected to each given node, grouped by source node UUID.++ Parameters:+ nodes (list[Node | str]): List of Node objects or node UUID strings to find neighbors for.+ brain_id (str): Database identifier to query.+ same_type_only (bool): If True, include only neighbors whose labels share at least one label with the source node.+ limit (int | None): Optional maximum number of neighbor records to return (applies to the entire result set).+ of_types (Optional[list[str]]): Optional list of node label names to filter neighbors by those labels.+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.+ Dict[str, List[Tuple[Predicate, Node]]]: Mapping from each source node UUID to a list of tuples (Predicate, Node),+ where Predicate describes the relationship (including direction, properties, flow key, and UUID) between the source+ and the neighbor, and Node represents the neighboring node (including its UUID, name, labels, description, and properties)."""if len(nodes) == 0:return {}@@ -1312,8 +1353,16 @@ class Neo4jClient(GraphClient):def get_schema(self, brain_id: str) -> dict:"""- Get the schema/ontology of the graph.- Returns all node labels and relationship types in JSON format.+ Retrieve the graph schema for the given brain, including node labels, relationship types, and event names.++ Parameters:+ brain_id (str): Identifier of the Neo4j database/brain to query.++ Returns:+ dict: A dictionary with keys:+ - "labels": list of node label names (str).+ - "relationships": list of relationship type names (str).+ - "event_names": list of node names (str) for nodes labeled "EVENT"."""self.ensure_database(brain_id)@@ -1350,6 +1399,19 @@ class Neo4jClient(GraphClient):vector_store_adapter: VectorStoreClient,brain_id: str,) -> Dict[str, List[Tuple[Predicate, Node, List[Tuple[Predicate, Node]]]]]:+ """+ Retrieve second-degree neighbor nodes from the given starting nodes.++ Parameters:+ from_ (List[str]): List of node UUIDs to start the hop from.+ flattened (bool): Whether to flatten the result structure.+ vector_store_adapter (VectorStoreClient): Adapter to the vector store.+ brain_id (str): Identifier of the brain or graph context.++ Returns:+ Dict[str, List[Tuple[Predicate, Node, List[Tuple[Predicate, Node]]]]]: Mapping from each starting node UUID to a list of tuples containing+ a predicate to a neighbor node, the neighbor node itself, and a list of tuples for that neighbor's predicates and their connected nodes.+ """return super().get_2nd_degree_hops(from_, flattened, vector_store_adapter, brain_id)@@ -1362,7 +1424,16 @@ class Neo4jClient(GraphClient):brain_id: str,) -> bool:"""- Check if a node exists in the graph.+ Determine whether a node with the given UUID, name, and labels exists in the specified database.++ Parameters:+ uuid (str): Node identifier to match.+ name (str): Node name to match.+ labels (list[str]): All labels the node must have.+ brain_id (str): Target database name.++ Returns:+ bool: True if a node matching the UUID, name, and labels exists, False otherwise."""cypher_query = f"""MATCH (n:{":".join(self._clean_labels(labels))})@@ -1380,8 +1451,18 @@ class Neo4jClient(GraphClient):self, node: Node | str, depth: int, brain_id: str) -> list[dict]:"""- Get the neighborhood of a node up to a given depth.- Returns a nested structure where each neighbor contains its own neighbors.+ Retrieve the neighborhood of a node up to a specified depth as a nested structure.++ Parameters:+ node (Node | str): The starting node or its UUID.+ depth (int): Maximum number of hops to traverse; must be >= 1.+ brain_id (str): Identifier for the brain/graph to scope the query.++ Returns:+ list[dict]: A list of neighbor dictionaries. Each dictionary contains the keys+ `node` (the neighboring Node), `predicate` (the connecting Predicate),+ `direction` (relationship direction relative to the starting node), and+ `neighbors` (a list of child neighbor dictionaries with the same shape)."""if depth < 1:return []@@ -1392,8 +1473,19 @@ class Neo4jClient(GraphClient):self, node_uuid: str, depth: int, brain_id: str, path_visited: set[str]) -> list[dict]:"""- Recursively get neighbors at each depth level.- Uses path_visited to prevent cycles in the current traversal path.+ Recursively collects neighboring nodes and their connecting predicates up to the specified depth.++ Parameters:+ node_uuid (str): UUID of the node to start traversal from.+ depth (int): Maximum number of hops to traverse; values less than 1 result in no neighbors.+ brain_id (str): Database/brain identifier to run the query against.+ path_visited (set[str]): Set of node UUIDs already visited in the current traversal path; used to prevent cycles.++ Returns:+ list[dict]: A list of neighbor entries. Each entry is a dict with keys:+ - "predicate": a Predicate instance describing the relationship from the current node to the neighbor.+ - "node": a Node instance representing the neighboring node.+ - "neighbors": a list of nested neighbor entries (same structure) for further hops."""if depth < 1 or node_uuid in path_visited:return []@@ -1463,7 +1555,15 @@ class Neo4jClient(GraphClient):self, predicate_uuid: str, flow_key: str, brain_id: str) -> List[Tuple[Node, Predicate, Node]]:"""- Get the next node by the flow key.+ Finds subsequent nodes in a flow that follow a relationship identified by a predicate UUID and share the given flow key.++ Parameters:+ predicate_uuid (str): UUID of the reference relationship whose adjacent segment is the starting point.+ flow_key (str): Flow key used to match the subsequent relationship.+ brain_id (str): Database name (brain) to execute the query against.++ Returns:+ List[Tuple[Node, Predicate, Node]]: A list of tuples each containing the middle node, the matching relationship (predicate) that has the flow_key, and the connected target node. Each tuple represents a directed hop from the middle node through the matched predicate to the target node; the predicate includes its direction and properties."""cypher_query = f"""MATCH ()-[r]-(m)-[r2]-(b)@@ -1509,4 +1609,4 @@ class Neo4jClient(GraphClient):]-_neo4j_client = Neo4jClient()+_neo4j_client = Neo4jClient()\ No newline at end of filediff --git a/src/services/api/controllers/entities.py b/src/services/api/controllers/entities.pyindex 826a400..0991315 100644--- a/src/services/api/controllers/entities.py+++ b/src/services/api/controllers/entities.py@@ -28,7 +28,16 @@ async def get_entity_info(target: str, query: str, max_depth: int = 3, brain_id: str = "default") -> GetEntityInfoResponse:"""- Get the entity info for a given query.+ Retrieve matching event paths for a target and query up to a specified traversal depth.++ Parameters:+ target (str): The entity identifier or text to locate.+ query (str): The query text used to find relevant event matches.+ max_depth (int): Maximum path traversal depth to consider when retrieving matches.+ brain_id (str): Brain/workspace identifier to scope the retrieval.++ Returns:+ GetEntityInfoResponse: Contains the located target node (`target_node`) and the retrieved paths (`path`)."""event_synergy_retriever = EventSynergyRetriever(brain_id)paths = event_synergy_retriever.retrieve_matches(target, query, max_depth)@@ -40,7 +49,19 @@ async def get_entity_context(target: str, context_depth: int = 3, brain_id: str = "default") -> GetEntityContextResponse:"""- Get the entity context for a given target.+ Retrieve contextual information for the specified entity target.++ Parameters:+ target (str): The entity identifier or text to retrieve context for.+ context_depth (int): Maximum graph depth (number of hops) to include in the neighborhood.+ brain_id (str): Identifier of the brain/workspace to query.++ Returns:+ GetEntityContextResponse: Response with the following fields:+ target_node: The node representing the target entity.+ neighborhood: Nearby nodes and relationships up to `context_depth`.+ text_contexts: Relevant text excerpts or documents associated with the target and neighborhood.+ natural_language_web: A natural-language representation or summary of the surrounding context."""entity_context = EntityContext(target, brain_id)target_node, neighborhood, text_contexts, natural_language_web = (@@ -60,7 +81,13 @@ async def get_entity_sibilings(brain_id: str = "default",) -> GetEntitySibilingsResponse:"""- Get the entity siblings for a given target.+ Retrieve sibling entities (synergies) for a target entity.++ Parameters:+ polarity (Literal["same", "opposite"]): Which polarity of siblings to return — "same" for similar entities, "opposite" for contrasted entities.++ Returns:+ GetEntitySibilingsResponse: Object containing the resolved target node and its list of synergies."""entity_sibilings = EntitySinergyRetriever(brain_id)target_node, synergies = entity_sibilings.retrieve_sibilings(target, polarity)@@ -76,7 +103,15 @@ async def get_entity_status(brain_id: str = "default",) -> GetEntityStatusResponse:"""- Get the entity status for a given target.+ Retrieve status information for an entity matching the provided target text.++ Parameters:+ target (str): Text used to locate the entity.+ types (List[str]): Optional list of node label types to filter matches; if provided, the first matching node whose labels intersect `types` is chosen.+ brain_id (str): Identifier of the brain/workspace to query.++ Returns:+ GetEntityStatusResponse: Response containing the matched node (or `None` if not found), `exists` indicating presence, `has_relationships` indicating whether the node has neighbors, `relationships` listing neighbor tuples, and `observations` associated with the node. When no matching node is found, `exists` is `False` and `relationships` and `observations` are empty."""target_embeddings = embeddings_adapter.embed_text(target)@@ -117,4 +152,4 @@ async def get_entity_status(has_relationships=len(rel_tuples[target_node.uuid]) > 0,relationships=rel_tuples[target_node.uuid],observations=observations,- )+ )\ No newline at end of filediff --git a/src/services/api/controllers/retrieve.py b/src/services/api/controllers/retrieve.pyindex 5d4faa5..d886376 100644--- a/src/services/api/controllers/retrieve.py+++ b/src/services/api/controllers/retrieve.py@@ -98,6 +98,27 @@ async def retrieve_neighbors(limit: int = 10,brain_id: str = "default",) -> RetrieveNeighborsRequestResponse:+ """+ Retrieve neighboring nodes related to a specified main node.++ If `uuid` is provided it is used to locate the main node; otherwise `identification_params` is used. Optionally filters first-degree neighbors by semantic similarity to `look_for`, expands those matches to similar nodes, and returns a deduplicated list of neighbor nodes (up to `limit`) with their relationship and the most common matching similar node.++ Parameters:+ uuid (Optional[str]): UUID of the main node to retrieve neighbors for. If omitted, `identification_params` must be provided.+ look_for (Optional[str]): Text used to filter first-degree neighbors by embedding similarity before expanding to similar nodes.+ identification_params (Optional[IdentificationParams]): Identification parameters used to find the main node when `uuid` is not provided.+ limit (int): Maximum number of neighbor results to include in the response.+ brain_id (str): Identifier of the brain / dataset to query.++ Returns:+ RetrieveNeighborsRequestResponse: Object containing:+ - count: total number of unique neighbors found,+ - main_node: the resolved main Node,+ - neighbors: list of RetrievedNeighborNode objects (neighbor, relationship, most_common) limited to `limit`.++ Raises:+ HTTPException: 404 if the main node cannot be found.+ """async def _get_neighbors():# ---------------------------------------------------------@@ -342,4 +363,4 @@ async def get_entities("entities": [e.model_dump(mode="json") for e in entities.results],"total": entities.total,}- )+ )\ No newline at end of filediff --git a/src/services/api/routes/retrieve.py b/src/services/api/routes/retrieve.pyindex 759b76f..103ca90 100644--- a/src/services/api/routes/retrieve.py+++ b/src/services/api/routes/retrieve.py@@ -112,7 +112,16 @@ async def get_neighbors_ai_mode(),):"""- Get the neighbors of an entity in AI mode.+ Retrieve neighboring entities using AI-mode identification parameters.++ Parameters:+ request (RetrieveNeighborsAiModeRequestBody): Request body containing:+ - identification_params: parameters that identify the target entity or entities.+ - looking_for: description of the desired neighbors or relation types.+ - limit: maximum number of neighbor results to return.++ Returns:+ list: Neighboring entities that match the AI-mode identification and search criteria."""return await retrieve_neighbors_ai_mode_controller(request.identification_params, request.looking_for, request.limit@@ -122,7 +131,13 @@ async def get_neighbors_ai_mode(@retrieve_router.get("/context")async def get_context(request):"""- Get the context of an entity.+ Handle an HTTP request to retrieve an entity's contextual information.++ Parameters:+ request: The incoming FastAPI request containing the parameters (query string or body) used to identify the target entity and any context options.++ Returns:+ The HTTP response payload to be returned to the client containing the entity context."""@@ -138,20 +153,20 @@ async def get_relationships(brain_id: str = "default",):"""- Retrieve relationships from the knowledge graph filtered by the provided criteria.-+ Retrieve relationships filtered by types, node labels, and query 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".-+ relationship_types (Optional[str]): Comma-separated relationship types to include.+ from_node_labels (Optional[str]): Comma-separated source node labels to filter.+ to_node_labels (Optional[str]): Comma-separated target node labels to filter.+ query_text (Optional[str]): Text to match against relationships or nodes.+ query_search_target (Optional[str]): Target of the text query, such as "all", "source", or "target".+ limit (int): Maximum number of relationships to return.+ skip (int): Number of relationships to skip.+ brain_id (str): Brain (dataset) identifier.+Returns:- A list of relationship records that match the provided filters.+ List of relationship records matching the filters."""if relationship_types:relationship_types = relationship_types.split(",")@@ -179,17 +194,15 @@ async def get_entities(brain_id: str = "default",):"""- Retrieve entities from the graph matching optional label and text filters.-+ Retrieve entities matching optional label and text filters with pagination.+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.+ node_labels (Optional[str]): Comma-separated node labels to filter by (e.g. "Person,Company"); when 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.+ list: A list of entity records that match the provided filters and pagination parameters."""if node_labels:node_labels = node_labels.split(",")@@ -311,14 +324,14 @@ async def get_changelog_by_id(brain_id: str = "default",):"""- Retrieve a changelog record by its identifier.-+ Retrieve a changelog entry by its unique identifier.+Parameters:- id (str): The changelog's unique identifier.- brain_id (str): Identifier of the brain to query; defaults to "default".-+ id (str): Unique identifier of the changelog entry.+ brain_id (str): Brain identifier to query. Defaults to "default".+Returns:- The changelog record matching `id`.+ The changelog entry corresponding to the specified identifier."""return await get_changelog_by_id_controller(id, brain_id)@@ -356,7 +369,16 @@ async def get_hops(brain_id: str = "default",): # noqa: F821"""- Get the hops in the graph for a given query.+ Compute graph hops for the given query.++ Parameters:+ query (str): Search text or entity identifier to start hop traversal from.+ degrees (int): Maximum number of hop degrees to traverse (default 2).+ flattened (bool): If True, return a flattened list of hops; otherwise preserve nested hop structure.+ brain_id (str): Identifier of the brain (knowledge graph) to query.++ Returns:+ list: Hops (paths) connecting matching entities up to the specified degree; the exact structure varies based on `flattened`."""return await get_hops_controller(query, degrees, flattened, brain_id)@@ -369,7 +391,16 @@ async def get_entity_info(brain_id: str = "default",):"""- Get the entity info for a given query.+ Retrieve detailed information for an entity identified by the given target and query.++ Parameters:+ target (str): Identifier or name of the target entity to retrieve.+ query (str): Query text used to refine or disambiguate the requested entity information.+ max_depth (int): Maximum graph depth to traverse when collecting related information.+ brain_id (str): Identifier of the brain/namespace to query.++ Returns:+ dict: A mapping containing the entity's attributes and related contextual information."""return await get_entity_info_controller(target, query, max_depth, brain_id)@@ -381,7 +412,15 @@ async def get_entity_context(brain_id: str = "default",):"""- Get the entity context for a given target.+ Retrieve contextual information for an entity identified by `target`.++ Parameters:+ target (str): Identifier or name of the target entity.+ context_depth (int): Maximum depth of related context to include.+ brain_id (str): Identifier of the brain/knowledge graph to query.++ Returns:+ dict: A mapping containing the entity's contextual information."""return await get_entity_context_controller(target, context_depth, brain_id)@@ -393,7 +432,15 @@ async def get_entity_synergies(brain_id: str = "default",):"""- Get the entity synergies for a given target.+ Retrieve synergies for a specified entity.++ Parameters:+ target (str): Identifier or name of the target entity.+ polarity (Literal["same", "opposite"]): Which type of synergies to return: "same" for similar/aligned synergies, "opposite" for contrasting/opposing synergies.+ brain_id (str): Identifier of the knowledge brain to query.++ Returns:+ list: A list of synergy records for the target entity matching the requested polarity."""return await get_entity_sibilings_controller(target, polarity, brain_id)@@ -405,6 +452,14 @@ async def get_entity_status(brain_id: str = "default",):"""- Get the entity status for a given target.+ Retrieve status information for a specified entity.++ Parameters:+ target (str): Identifier or name of the entity to inspect.+ types (Optional[List[str]]): Optional list of entity types to filter the status computation.+ brain_id (str): Identifier of the brain (knowledge graph) to query.++ Returns:+ status (dict): A dictionary containing the entity's status details."""- return await get_entity_status_controller(target, types, brain_id)+ return await get_entity_status_controller(target, types, brain_id)\ No newline at end of filediff --git a/src/utils/tokens.py b/src/utils/tokens.pyindex 76b9cd6..5575e23 100644--- a/src/utils/tokens.py+++ b/src/utils/tokens.py@@ -13,6 +13,15 @@ from src.constants.agents import TokenDetail, TokenInputDetail, TokenOutputDetaidef merge_token_details(token_details: list[TokenDetail]) -> TokenDetail:+ """+ Aggregate a list of TokenDetail objects into a single merged TokenDetail.++ Parameters:+ token_details (list[TokenDetail]): List of TokenDetail objects to merge. None entries are ignored; if the list is empty or contains only None, a TokenDetail with all zero/default fields is returned.++ Returns:+ TokenDetail: A merged TokenDetail where input and output counts are summed across entries, cache_percentage is (total cached / total input * 100) or 0.0 if total input is zero, reasoning_percentage is (total reasoning / total output * 100) or 0.0 if total output is zero, and grand_total and effective_total are the sums of their respective values.+ """if not token_details:return TokenDetail(input=TokenInputDetail(total=0, uncached=0, cached=0, cache_percentage=0.0),@@ -70,6 +79,22 @@ def merge_token_details(token_details: list[TokenDetail]) -> TokenDetail:def token_detail_from_token_counts(input_tokens: int, output_tokens: int, cached_tokens: int, reasoning_tokens: int) -> TokenDetail:+ """+ Constructs a TokenDetail summarizing input and output token counts with cached and reasoning breakdowns.++ Parameters:+ input_tokens (int): Total number of input tokens.+ output_tokens (int): Total number of output tokens.+ cached_tokens (int): Number of input tokens served from cache.+ reasoning_tokens (int): Number of output tokens classified as reasoning.++ Returns:+ TokenDetail: Aggregated token details containing:+ - input: TokenInputDetail with total, uncached, cached, and cache_percentage.+ - output: TokenOutputDetail with total, regular, reasoning, and reasoning_percentage.+ - grand_total: Sum of input and output tokens.+ - effective_total: Sum of output tokens plus input tokens not served from cache.+ """return TokenDetail(input=TokenInputDetail(total=input_tokens,@@ -89,4 +114,4 @@ def token_detail_from_token_counts(),grand_total=input_tokens + output_tokens,effective_total=input_tokens - cached_tokens + output_tokens,- )+ )\ No newline at end of filediff --git a/src/workers/tasks/ingestion.py b/src/workers/tasks/ingestion.pyindex f374fca..13a7695 100644--- a/src/workers/tasks/ingestion.py+++ b/src/workers/tasks/ingestion.py@@ -70,7 +70,13 @@ def format_textual_data(data: dict, include_keys: bool = True) -> str:@ingestion_app.task(bind=True)def ingest_data(self, args: dict):"""- Ingest data into the database.+ Ingest a payload into the system, persist its content and metadata, generate embeddings and observations, and trigger knowledge-graph enrichment.++ Parameters:+ args (dict): Raw task arguments parsed into an IngestionTaskArgs model; must include a brain_id and data payload.++ Returns:+ task_id (str): The identifier of the ingestion task (Celery request id) that was created/updated."""payload = Nonetry:@@ -187,7 +193,21 @@ def ingest_data(self, args: dict):@ingestion_app.task(bind=True)def process_architect_relationships(self, args: dict):"""- Process architect relationships.+ Process a batch of architect relationships and ingest corresponding nodes, vectors, and graph edges.++ Parameters:+ args (dict): Task payload containing:+ - "relationships" (List[dict]): List of relationship payloads convertible to ArchitectAgentRelationship.+ - "brain_id" (str, optional): Target brain identifier; defaults to "default".++ Description:+ For each relationship in `args["relationships"]`, the task generates embeddings for the relationship (and for any missing subject/object nodes), creates or updates graph nodes, and adds the relationship edge to the knowledge graph. Progress and final status are stored in the task cache under the current task id. Individual relationship or node failures (including timeouts) are skipped so remaining items continue processing.++ Returns:+ str: The Celery task id for the ingestion run.++ Raises:+ Exception: Any unhandled exception is recorded to the task cache with status "failed" and then re-raised."""print(@@ -397,7 +417,25 @@ def process_architect_relationships(self, args: dict):@ingestion_app.task(bind=True)def ingest_structured_data(self, args: dict):"""- Ingest structured data into the database.+ Ingest structured elements into the knowledge graph by creating nodes, embedding and storing vectors, generating observations, and saving structured-data records.++ Parses `args` into an IngestionStructuredRequestBody and for each element:+ - creates a graph node with properties and metadata,+ - records node property change logs (KG changes),+ - embeds and stores node and element vectors in the vector store,+ - generates and stores observations (vectors and Observation records),+ - merges and saves structured-data records,+ - calls knowledge-graph enrichment for the element,+ and updates a task status cache with "started" and "completed" entries.++ Parameters:+ args (dict): The raw task payload parsed into IngestionStructuredRequestBody (must include brain_id and data elements).++ Returns:+ str: The task id for this ingestion (self.request.id).++ Exceptions:+ On exception, stores a "failed" task status with error details in the cache and re-raises the exception."""payload = Nonetry:@@ -616,4 +654,4 @@ def ingest_structured_data(self, args: dict):expires_in=3600 * 24 * 7,)- raise+ raise\ No newline at end of file