BrainAPI is a knowledge graph–powered AI memory layer that transforms unstructured data into structured knowledge, enabling intelligent search, recommendations, and contextual memory for AI agents and applications.
Python ai-agentsai-memoryknowledge-graphknowledge-managementknowledge-representationreccomendation-system
feat(retrieval): entities context + entities info
Christian83bba28ae9f8
diff --git a/src/adapters/graph.py b/src/adapters/graph.pyindex 5874925..58d2979 100644--- a/src/adapters/graph.py+++ b/src/adapters/graph.py@@ -522,5 +522,14 @@ class GraphAdapter:"""return self.graph.check_node_existence(uuid, name, labels, brain_id)+ def get_neighborhood(+ self, node: Node | str, depth: int, brain_id: str = "default"+ ) -> list[dict]:+ """+ Get the neighborhood of a node up to a given depth.+ Returns a nested structure where each neighbor contains its own neighbors.+ """+ return self.graph.get_neighborhood(node, depth, brain_id)+_graph_adapter = GraphAdapter()diff --git a/src/adapters/interfaces/graph.py b/src/adapters/interfaces/graph.pyindex d33238f..2d11ced 100644--- a/src/adapters/interfaces/graph.py+++ b/src/adapters/interfaces/graph.py@@ -400,3 +400,13 @@ class GraphClient(ABC):Check if a node exists in the graph."""raise NotImplementedError("check_node_existence method not implemented")++ @abstractmethod+ def get_neighborhood(+ 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.+ """+ raise NotImplementedError("get_neighborhood method not implemented")diff --git a/src/constants/agents.py b/src/constants/agents.pyindex 9d2bbb3..7a915d7 100644--- a/src/constants/agents.py+++ b/src/constants/agents.py@@ -21,10 +21,6 @@ class ArchitectAgentEntity(BaseModel):uuid: strname: strtype: str- flow_key: Optional[str] = Field(- default=None,- description="Unique identitier for contextualizing the entity into the context flow",- )happened_at: Optional[str | None] = Field(default=None,description="The date and time the entity happened at if known otherwise None. Mostly used for event entities.",diff --git a/src/constants/kg.py b/src/constants/kg.pyindex a4d618a..4d91435 100644--- a/src/constants/kg.py+++ b/src/constants/kg.py@@ -26,12 +26,8 @@ class Node(BaseModel):name: strdescription: Optional[str] = Noneproperties: dict = Field(default_factory=dict)- flow_key: Optional[str] = Field(- default=None,- description="Unique identitier for contextualizing the node into the context flow",- )- happened_at: Optional[datetime | None] = Field(+ happened_at: Optional[str | None] = Field(default=None,description="The date and time the node happened at if known otherwise None. Mostly used for event nodes.",)diff --git a/src/core/agents/janitor_agent.py b/src/core/agents/janitor_agent.pyindex 87d8eed..8d0c04b 100644--- a/src/core/agents/janitor_agent.py+++ b/src/core/agents/janitor_agent.py@@ -232,7 +232,7 @@ class JanitorAgent:return self.agent.invoke({"messages": messages_list},- config={"recursion_limit": 25},+ config={"recursion_limit": 100},)@retry(@@ -344,7 +344,7 @@ class JanitorAgent:return self.agent.invoke({"messages": messages_list},- config={"recursion_limit": 25},+ config={"recursion_limit": 100},)@retry(@@ -473,7 +473,7 @@ class JanitorAgent:return self.agent.invoke({"messages": messages_list},- config={"recursion_limit": 25},+ config={"recursion_limit": 100},)@retry(diff --git a/src/core/agents/kg_agent.py b/src/core/agents/kg_agent.pyindex 16c48b5..7353949 100644--- a/src/core/agents/kg_agent.py+++ b/src/core/agents/kg_agent.py@@ -3,8 +3,8 @@ File: /kg_agent.pyCreated Date: Sunday October 19th 2025Author: Christian Nonis <[email protected]>------Last Modified: Sunday October 19th 2025 9:42:00 am-Modified By: the developer formerly known as Christian Nonis at <[email protected]>+Last Modified: Monday January 12th 2026 8:26:26 pm+Modified By: Christian Nonis <[email protected]>-----"""@@ -36,7 +36,7 @@ from src.adapters.embeddings import EmbeddingsAdapter, VectorStoreAdapterclass KGAgent:"""- Knowledge Graph Agent. Used to update the knowledge graph with new information.+ Knowledge Graph Agent. Used to operate with the knowledge graph with new information.Not used for batch updates."""diff --git a/src/core/agents/tools/architect_agent/ArchitectAgentCreateRelationshipTool.py b/src/core/agents/tools/architect_agent/ArchitectAgentCreateRelationshipTool.pyindex ea5e496..d26b629 100644--- a/src/core/agents/tools/architect_agent/ArchitectAgentCreateRelationshipTool.py+++ b/src/core/agents/tools/architect_agent/ArchitectAgentCreateRelationshipTool.py@@ -150,7 +150,6 @@ class ArchitectAgentCreateRelationshipTool(BaseTool):uuid=subj_entity.uuid,name=subj_entity.name,type=subj_entity.type,- **({"flow_key": rel_key} if subj_entity.type != "EVENT" else {}),description=subj_entity.description,**({"happened_at": subj_entity.properties.get("happened_at")}@@ -163,7 +162,6 @@ class ArchitectAgentCreateRelationshipTool(BaseTool):uuid=obj_entity.uuid,name=obj_entity.name,type=obj_entity.type,- **({"flow_key": rel_key} if obj_entity.type != "EVENT" else {}),description=obj_entity.description,**({"happened_at": obj_entity.properties.get("happened_at")}diff --git a/src/core/search/entities.py b/src/core/search/entities.pyindex 24a437c..9690e16 100644--- a/src/core/search/entities.py+++ b/src/core/search/entities.py@@ -3,16 +3,243 @@ File: /entities.pyCreated Date: Friday November 7th 2025Author: Christian Nonis <[email protected]>------Last Modified: Friday November 7th 2025 8:13:02 pm-Modified By: the developer formerly known as Christian Nonis at <[email protected]>+Last Modified: Monday January 12th 2026 8:26:26 pm+Modified By: Christian Nonis <[email protected]>-----"""-from typing import Optional+from typing import List, Optionalfrom src.constants.kg import SearchEntitiesResultfrom src.services.kg_agent.main import graph_adapter+import re+import unicodedata+++def extract_str_entities_from_text(text: str) -> List[str]:+ """+ Decompose a text into string entity elements.+ """+ if not text or not text.strip():+ return []++ text = unicodedata.normalize("NFKC", text)++ multilingual_stop_words = {+ "a",+ "an",+ "the",+ "in",+ "on",+ "at",+ "by",+ "for",+ "to",+ "of",+ "and",+ "or",+ "but",+ "is",+ "was",+ "are",+ "were",+ "been",+ "be",+ "have",+ "has",+ "had",+ "do",+ "does",+ "did",+ "will",+ "would",+ "should",+ "could",+ "may",+ "might",+ "must",+ "can",+ "it",+ "this",+ "that",+ "these",+ "those",+ "i",+ "you",+ "he",+ "she",+ "we",+ "they",+ "his",+ "her",+ "its",+ "our",+ "their",+ "me",+ "him",+ "us",+ "them",+ "der",+ "die",+ "das",+ "den",+ "dem",+ "des",+ "ein",+ "eine",+ "einer",+ "eines",+ "einem",+ "einen",+ "und",+ "oder",+ "aber",+ "ist",+ "sind",+ "war",+ "waren",+ "wird",+ "wurde",+ "wurden",+ "hat",+ "haben",+ "hatte",+ "hatten",+ "le",+ "la",+ "les",+ "un",+ "une",+ "des",+ "du",+ "de",+ "de la",+ "et",+ "ou",+ "mais",+ "est",+ "sont",+ "était",+ "étaient",+ "sera",+ "seront",+ "a",+ "ont",+ "avait",+ "avaient",+ "el",+ "la",+ "los",+ "las",+ "un",+ "una",+ "unos",+ "unas",+ "y",+ "o",+ "pero",+ "es",+ "son",+ "era",+ "eran",+ "será",+ "serán",+ "tiene",+ "tienen",+ "tenía",+ "tenían",+ "il",+ "lo",+ "gli",+ "le",+ "un",+ "una",+ "uno",+ "e",+ "o",+ "ma",+ "è",+ "sono",+ "era",+ "erano",+ "sarà",+ "saranno",+ "ha",+ "hanno",+ "aveva",+ "avevano",+ "de",+ "het",+ "een",+ "en",+ "of",+ "maar",+ "is",+ "zijn",+ "was",+ "waren",+ "zal",+ "zullen",+ "heeft",+ "hebben",+ "had",+ "hadden",+ "o",+ "a",+ "os",+ "as",+ "um",+ "uma",+ "uns",+ "umas",+ "e",+ "ou",+ "mas",+ "é",+ "são",+ "era",+ "eram",+ "será",+ "serão",+ "tem",+ "têm",+ "tinha",+ "tinham",+ }++ words_pattern = re.compile(r"\b[^\W\d_]+\b", re.UNICODE)++ words = words_pattern.findall(text)++ entities = []+ seen = set()++ for word in words:+ word_lower = word.lower()++ if word_lower in multilingual_stop_words:+ continue++ if len(word_lower) < 2:+ continue++ if word_lower in seen:+ continue++ if not any(c.isalpha() for c in word):+ continue++ seen.add(word_lower)++ if word and word[0].isupper():+ entities.append(word)+ else:+ entities.append(word.capitalize())++ return entities++def search_entities(limit: int = 10,skip: int = 0,@@ -22,18 +249,18 @@ def search_entities() -> SearchEntitiesResult:"""Search entities in the knowledge graph.-+Parameters:limit (int): Maximum number of entities to return.skip (int): Number of entities to skip (offset) for pagination.node_labels (Optional[list[str]]): Filter results to nodes matching any of these labels.query_text (Optional[str]): Text to match against entity properties or content.brain_id (str): Identifier of the graph/brain to query.-+Returns:SearchEntitiesResult: Result object containing matched entities and pagination metadata."""result = graph_adapter.search_entities(brain_id, limit, skip, node_labels, query_text)- return result\ No newline at end of file+ return resultdiff --git a/src/core/search/entity_context.py b/src/core/search/entity_context.pyindex b04fae4..2f86e90 100644--- a/src/core/search/entity_context.py+++ b/src/core/search/entity_context.py@@ -3,7 +3,87 @@ File: /entity_context.pyCreated Date: Sunday January 11th 2026Author: Christian Nonis <[email protected]>------Last Modified: Sunday January 11th 2026 9:53:12 pm-Modified By: the developer formerly known as Christian Nonis at <[email protected]>+Last Modified: Monday January 12th 2026 8:31:46 pm+Modified By: Christian Nonis <[email protected]>-----"""++from typing import Tuple+from src.constants.kg import Node+from src.services.kg_agent.main import (+ embeddings_adapter,+ vector_store_adapter,+ graph_adapter,+)+++class EntityContext:+ def __init__(self, target: str, brain_id: str = "default"):+ self.target = target+ self.brain_id = brain_id++ def get_context(+ self, context_depth: int = 3+ ) -> Tuple[Node, list[dict], list[dict]]:+ """+ Gets context around an entity.+ """++ text_contexts = set()+ natural_language_web = list()++ target_embedding = embeddings_adapter.embed_text(self.target)+ target_node_vs = vector_store_adapter.search_vectors(+ target_embedding.embeddings, store="nodes", brain_id=self.brain_id+ )++ if not target_node_vs:+ return (None, [])++ target_node_v = target_node_vs[0]+ target_node_id = target_node_v.metadata.get("uuid")++ target_node = graph_adapter.get_by_uuid(target_node_id, brain_id=self.brain_id)++ if not target_node:+ return (None, [])++ neighborhood = graph_adapter.get_neighborhood(+ target_node_id, context_depth, brain_id=self.brain_id+ )++ def _get_text_context(+ neighbors: list[dict], append_to_web: bool = False+ ) -> list[dict]:+ entries = []+ for nn in neighbors:+ node = nn.get("node")+ if node and hasattr(node, "description") and node.description:+ text_contexts.add(node.description)+ predicate = nn.get("predicate")+ if (+ predicate+ and hasattr(predicate, "description")+ and predicate.description+ ):+ text_contexts.add(predicate.description)+ nested_neighbors = nn.get("neighbors")+ nested_info = (+ _get_text_context(nested_neighbors) if nested_neighbors else None+ )+ entry = {+ "description": predicate.description,+ "information_direction": predicate.direction,+ predicate.name: {+ node.name: node.description,+ "info": nested_info,+ },+ }+ if append_to_web:+ natural_language_web.append(entry)+ entries.append(entry)+ return entries if entries else None++ _get_text_context(neighborhood, append_to_web=True)++ return (target_node, neighborhood, list(text_contexts), natural_language_web)diff --git a/src/core/search/entity_info.py b/src/core/search/entity_info.pyindex 1dde2a5..c7ae5dc 100644--- a/src/core/search/entity_info.py+++ b/src/core/search/entity_info.py@@ -3,34 +3,43 @@ File: /entity_info.pyCreated Date: Sunday January 11th 2026Author: Christian Nonis <[email protected]>------Last Modified: Sunday January 11th 2026 9:52:59 pm-Modified By: the developer formerly known as Christian Nonis at <[email protected]>+Last Modified: Monday January 12th 2026 8:31:46 pm+Modified By: Christian Nonis <[email protected]>-----"""-from typing import List, Set+from __future__ import annotations++from typing import List, Set, Tuple, Optionalfrom datetime import datetimeimport numpy as np+from pydantic import BaseModel, Field-from services.kg_agent.main import (- embeddings_adapter,- graph_adapter,- vector_store_adapter,-)-from src.constants.kg import EntityInfo+from src.constants.kg import Node, Predicate+from src.services.kg_agent.main import graph_adapter+from src.services.kg_agent.main import embeddings_adapter+from src.services.kg_agent.main import vector_store_adapterfrom src.utils.similarity.vectors import cosine_similarity# ================================================================-# NOTE Currently not directly supported by the Event-Centric v2 kg+# NOTE Currently not fully supported by the Event-Centric v2 kg# Need to figure out how to handle this.+# Currently kinda works but it's raw, unprecise and w/ poor devx# ================================================================+class MatchPath(BaseModel):+ target_node: Optional[Node] = None+ path: Tuple[Predicate, Optional[Node]]+ similarity: float+ children: List["MatchPath"] = Field(default_factory=list)++class EventSynergyRetriever:def __init__(self, memory_id: str):self.memory_id = memory_id- self.graph_adapter = graph_adapter+ self.brain_id = memory_iddef _recursive_explorer(self,@@ -38,6 +47,9 @@ class EventSynergyRetriever:query_embedding: List[float],depth: int,visited_ids: Set[str],+ most_similar_conn_rel_tuple: Optional[+ Tuple[Tuple[Predicate, Node], float]+ ] = None,):# -> List[SynergyPath]:"""@@ -47,67 +59,174 @@ class EventSynergyRetriever:if depth <= 0:return []- neighbors = self.graph_adapter.fetch_entity_with_relevant_nodes(- current_node_id, list(visited_ids)+ if current_node_id in visited_ids:+ return []++ visited_ids.add(current_node_id)++ neighbors = graph_adapter.get_neighbors(+ [current_node_id], brain_id=self.brain_id)- found_paths = []+ if not neighbors or current_node_id not in neighbors:+ return []++ conn_rels: List[Tuple[Predicate, Node]] = neighbors[current_node_id]++ conn_rels_w_embeddings: List[Tuple[Tuple[Predicate, Node], List[float]]] = []++ for rel_tuple in conn_rels:+ cr = rel_tuple[0]+ v_id = cr.properties.get("v_id")+ if v_id is None:+ continue+ cr_vs = vector_store_adapter.get_by_ids(+ [v_id],+ store="relationships",+ brain_id=self.brain_id,+ )+ if cr_vs:+ conn_rels_w_embeddings.append((rel_tuple, cr_vs[0].embeddings))+ if not conn_rels_w_embeddings:+ return []++ conn_rels_similarities: List[Tuple[Tuple[Predicate, Node], float]] = [+ (rel_tuple, cosine_similarity(cr_embedding, query_embedding))+ for rel_tuple, cr_embedding in conn_rels_w_embeddings+ ]++ conn_rels_similarities_sorted = sorted(+ conn_rels_similarities, key=lambda x: x[1], reverse=True+ )- neighbor_v_ids = [n.node.properties["v_id"] for n in neighbors.relationships]- if not neighbor_v_ids:+ if not conn_rels_similarities_sorted:return []- similarities = self._batch_measure_similarity(neighbor_v_ids, query_embedding)-- for i, rel in enumerate(neighbors.relationships):- sim = similarities[i]- target_node = rel.to_node-- # if sim > 0.4:- # new_visited = visited_ids | {current_node_id}-- # child_paths = self._recursive_explorer(- # target_node.id, query_embedding, depth - 1, new_visited- # )-- # found_paths.append(- # SynergyPath(- # node=target_node,- # relationship=Relationship(- # **rel.model_dump(),- # similarity=sim,- # # Incorporate Recency and Amount into the relationship- # # if it's an Event or Transaction link- # ),- # similarity=sim,- # depth=depth,- # children=child_paths,- # )- # )-- return sorted(found_paths, key=lambda x: x.similarity, reverse=True)-- def retrieve_matches(self, member_uuid: str, query: str, max_depth: int = 3):+ current_best = conn_rels_similarities_sorted[0]++ predicate, node = current_best[0]+ if not node or not predicate:+ return []++ if (+ most_similar_conn_rel_tuple is None+ or current_best[1] > most_similar_conn_rel_tuple[1]+ ):+ most_similar_conn_rel_tuple = current_best++ next_node = current_best[0][1]+ if not next_node or not next_node.uuid:+ return [most_similar_conn_rel_tuple] if most_similar_conn_rel_tuple else []++ results = self._recursive_explorer(+ next_node.uuid,+ query_embedding,+ depth - 1,+ visited_ids,+ most_similar_conn_rel_tuple,+ )++ if results:+ return results+ else:+ return [most_similar_conn_rel_tuple] if most_similar_conn_rel_tuple else []++ def retrieve_matches(+ self, target: str, query: str, max_depth: int = 3+ ) -> MatchPath:"""Starts from a Member and recursively finds the most relevantsynergy paths in the graph."""query_embedding = embeddings_adapter.embed_text(query)+ target_embedding = embeddings_adapter.embed_text(target)- synergy_paths = self._recursive_explorer(- member_uuid, query_embedding, depth=max_depth, visited_ids=set()+ target_node_vs = vector_store_adapter.search_vectors(+ target_embedding.embeddings, store="nodes", brain_id=self.brain_id)- scored_results = []- for path in synergy_paths:- child_bonus = sum([c.similarity for c in path.children]) * 0.1-- days_ago = (datetime.now() - path.relationship.happened_at).days- recency = 1 / (1 + np.log1p(days_ago))-- total_score = (path.similarity * 0.6) + (recency * 0.2) + child_bonus+ if not target_node_vs:+ return MatchPath(+ target_node=None,+ path=(Predicate(name="", description=""), None),+ similarity=0.0,+ children=[],+ )++ target_node_v = target_node_vs[0]+ target_node_id = target_node_v.metadata.get("uuid")++ if not target_node_id:+ return MatchPath(+ target_node=None,+ path=(Predicate(name="", description=""), None),+ similarity=0.0,+ children=[],+ )++ target_node = graph_adapter.get_by_uuid(target_node_id, brain_id=self.brain_id)++ if not target_node:+ return MatchPath(+ target_node=None,+ path=(Predicate(name="", description=""), None),+ similarity=0.0,+ children=[],+ )- scored_results.append({"path": path, "score": total_score})+ synergy_paths = self._recursive_explorer(+ target_node_id,+ query_embedding.embeddings,+ depth=max_depth,+ visited_ids=set(),+ )- return sorted(scored_results, key=lambda x: x["score"], reverse=True)+ if not synergy_paths:+ return MatchPath(+ target_node=target_node,+ path=(Predicate(name="", description=""), target_node),+ similarity=0.0,+ children=[],+ )++ synergy_paths = list(reversed(synergy_paths))++ match_paths = []+ for path_tuple, similarity in synergy_paths:+ predicate, node = path_tuple+ if not node or not predicate:+ continue++ days_ago = 0+ if node.happened_at:+ days_ago = (datetime.now() - node.happened_at).days++ recency = 1 / (1 + np.log1p(days_ago)) if days_ago > 0 else 1.0+ base_score = similarity * 0.6 + recency * 0.2++ match_path = MatchPath(+ target_node=target_node,+ path=path_tuple,+ similarity=base_score,+ children=[],+ )+ match_paths.append(match_path)++ if not match_paths:+ return MatchPath(+ target_node=target_node,+ path=(Predicate(name="", description=""), target_node),+ similarity=0.0,+ children=[],+ )++ root_path = match_paths[0]+ current_path = root_path+ for i in range(1, len(match_paths)):+ child_bonus = match_paths[i].similarity * 0.1+ root_path.similarity += child_bonus+ current_path.children.append(match_paths[i])+ current_path = match_paths[i]++ return root_pathdiff --git a/src/lib/llm/client_small.py b/src/lib/llm/client_small.pyindex 471b3ec..1a0e01d 100644--- a/src/lib/llm/client_small.py+++ b/src/lib/llm/client_small.py@@ -3,8 +3,8 @@ File: /client_small.pyCreated Date: Sunday December 21st 2025Author: Christian Nonis <[email protected]>------Last Modified: Sunday December 21st 2025 3:43:44 pm-Modified By: the developer formerly known as Christian Nonis at <[email protected]>+Last Modified: Tuesday December 23rd 2025 9:24:20 pm+Modified By: Christian Nonis <[email protected]>-----"""@@ -96,7 +96,7 @@ class LLMClientSmall(LLM):return self._langchain_modeldef generate_text(- self, prompt: str, max_new_tokens: int = None, timeout: int = None+ self, prompt: str, max_new_tokens: int = 100000, timeout: int = None) -> str:if not prompt or len(prompt.strip()) == 0:return "Input prompt is empty"@@ -110,7 +110,7 @@ class LLMClientSmall(LLM):contents=[prompt],config=GenerateContentConfig(response_mime_type="text/plain",- **({"max_new_tokens": max_new_tokens} if max_new_tokens else {}),+ **({"max_output_tokens": max_new_tokens} if max_new_tokens else {}),),)@@ -151,7 +151,7 @@ class LLMClientSmall(LLM):def generate_json(self,prompt: str,- max_new_tokens: int = None,+ max_new_tokens: int = 100000,max_retries: int = 3,timeout: int = None,) -> dict:@@ -162,10 +162,9 @@ class LLMClientSmall(LLM):_response = self.client.models.generate_content(model=self.model,contents=[prompt],- max_new_tokens=max_new_tokens,config=GenerateContentConfig(response_mime_type="application/json",- **({"max_new_tokens": max_new_tokens} if max_new_tokens else {}),+ **({"max_output_tokens": max_new_tokens} if max_new_tokens else {}),),)_response = _response.text.strip("").strip("```")diff --git a/src/lib/milvus/readme.txt b/src/lib/milvus/readme.txtindex bb2c821..b11dd08 100644--- a/src/lib/milvus/readme.txt+++ b/src/lib/milvus/readme.txt@@ -1,5 +1,5 @@Attu Official:```-docker run -p 8000:3000 -e MILVUS_URL={your-milvus-ip}:19530 zilliz/attu:latest+docker run -p 3500:3000 --network milvus -e MILVUS_URL=standalone:19530 zilliz/attu:latest```\ No newline at end of filediff --git a/src/lib/neo4j/client.py b/src/lib/neo4j/client.pyindex 70c2426..8ffc5e4 100644--- a/src/lib/neo4j/client.py+++ b/src/lib/neo4j/client.py@@ -588,7 +588,7 @@ class Neo4jClient(GraphClient):cypher_query += """RETURN n.uuid AS uuid, n.name AS name, labels(n) AS labels, n.description AS description, properties(n) AS properties, r AS rel,CASE WHEN startNode(r) = n THEN 'out' ELSE 'in' END AS direction,- type(r) AS rel_type, r.description AS rel_description,+ type(r) AS rel_type, r.description AS rel_description, properties(r) AS rel_properties,c.uuid AS c_uuid, c.name AS c_name, labels(c) AS c_labels, c.description AS c_description, properties(c) AS c_properties"""@@ -609,6 +609,7 @@ class Neo4jClient(GraphClient):name=record.get("rel_type", "") or "",description=record.get("rel_description", "") or "",direction=record.get("direction", "neutral"),+ properties=record.get("rel_properties", {}) or {},),Node(uuid=record.get("c_uuid", ""),@@ -1350,5 +1351,88 @@ class Neo4jClient(GraphClient):)return len(result.records) > 0+ def get_neighborhood(+ 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.+ """+ if depth < 1:+ return []+ node_uuid = node.uuid if isinstance(node, Node) else node+ return self._get_neighborhood_recursive(node_uuid, depth, brain_id, set())++ def _get_neighborhood_recursive(+ 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.+ """+ if depth < 1 or node_uuid in path_visited:+ return []++ path_visited = path_visited.copy()+ path_visited.add(node_uuid)++ cypher_query = """+ MATCH (n)-[r]-(m)+ WHERE n.uuid = $uuid+ RETURN+ r as rel,+ type(r) as rel_type,+ r.description as rel_description,+ properties(r) as rel_properties,+ CASE WHEN startNode(r) = n THEN 'out' ELSE 'in' END AS direction,+ m.uuid as m_uuid,+ m.name as m_name,+ labels(m) as m_labels,+ m.description as m_description,+ properties(m) as m_properties+ """++ self.ensure_database(brain_id)+ result = self.driver.execute_query(+ cypher_query,+ parameters_={"uuid": node_uuid},+ database_=brain_id,+ )++ neighbors = []+ for record in result.records:+ neighbor_node_uuid = record.get("m_uuid", "")+ if neighbor_node_uuid in path_visited:+ continue++ neighbor_node = Node(+ uuid=neighbor_node_uuid,+ name=record.get("m_name", "") or "",+ labels=record.get("m_labels", []) or [],+ description=record.get("m_description", "") or "",+ properties=record.get("m_properties", {}) or {},+ )++ predicate = Predicate(+ name=record.get("rel_type", "") or "",+ description=record.get("rel_description", "") or "",+ direction=record.get("direction", "neutral"),+ properties=record.get("rel_properties", {}) or {},+ )++ nested_neighbors = self._get_neighborhood_recursive(+ neighbor_node_uuid, depth - 1, brain_id, path_visited+ )++ neighbors.append(+ {+ "predicate": predicate,+ "node": neighbor_node,+ "neighbors": nested_neighbors,+ }+ )++ return neighbors+_neo4j_client = Neo4jClient()diff --git a/src/services/api/constants/requests.py b/src/services/api/constants/requests.pyindex 383c933..d5d6933 100644--- a/src/services/api/constants/requests.py+++ b/src/services/api/constants/requests.py@@ -3,16 +3,17 @@ File: /requests.pyCreated Date: Monday October 20th 2025Author: Christian Nonis <[email protected]>------Last Modified: Saturday December 27th 2025-Modified By: the developer formerly known as Christian Nonis at <[email protected]>+Last Modified: Monday January 12th 2026 8:26:26 pm+Modified By: Christian Nonis <[email protected]>-----"""-from typing import List, Any, Optional+from typing import List, Any, Optional, Tuplefrom pydantic import BaseModel, Field, field_serializerfrom src.constants.data import Observation, TextChunkfrom src.constants.kg import IdentificationParams, Node, Predicatefrom src.constants.tasks.ingestion import IngestionTaskArgs+from src.core.search.entity_info import MatchPathclass IngestionRequestBody(IngestionTaskArgs):@@ -185,8 +186,10 @@ class CreateBrainRequest(BaseModel):brain_id: str+class AddEntityRequest(BaseModel):"""Request model for adding a new entity to the graph."""+name: strbrain_id: str = "default"labels: list[str] = []@@ -198,6 +201,7 @@ class AddEntityRequest(BaseModel):class UpdateEntityRequest(BaseModel):"""Request model for updating an existing entity in the graph."""+uuid: strbrain_id: str = "default"new_name: Optional[str] = None@@ -209,6 +213,7 @@ class UpdateEntityRequest(BaseModel):class AddRelationshipRequest(BaseModel):"""Request model for adding a new relationship between two entities."""+subject_uuid: strpredicate_name: strpredicate_description: str@@ -218,7 +223,24 @@ class AddRelationshipRequest(BaseModel):class UpdateRelationshipRequest(BaseModel):"""Request model for updating an existing relationship's properties."""+uuid: strbrain_id: str = "default"new_properties: Optional[dict] = None- properties_to_remove: Optional[list[str]] = None\ No newline at end of file+ properties_to_remove: Optional[list[str]] = None+++class GetEntityInfoResponse(BaseModel):+ """Response model for the get entity info endpoint."""++ target_node: Optional[Node] = None+ path: MatchPath+++class GetEntityContextResponse(BaseModel):+ """Response model for the get entity context endpoint."""++ neighborhood: list[dict]+ target_node: Optional[Node] = None+ text_contexts: list[str] = []+ natural_language_web: list[dict] = []diff --git a/src/services/api/controllers/entities.py b/src/services/api/controllers/entities.pynew file mode 100644index 0000000..d864bce--- /dev/null+++ b/src/services/api/controllers/entities.py@@ -0,0 +1,47 @@+"""+File: /entities.py+Project: controllers+Created Date: Sunday January 18th 2026+Author: Christian Nonis <[email protected]>+-----+Last Modified: Sunday January 18th 2026 9:38:31 pm+Modified By: Christian Nonis <[email protected]>+-----+"""++from src.core.search.entity_context import EntityContext+from src.core.search.entity_info import EventSynergyRetriever+from src.services.api.constants.requests import (+ GetEntityInfoResponse,+ GetEntityContextResponse,+)+++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.+ """+ event_synergy_retriever = EventSynergyRetriever(brain_id)+ paths = event_synergy_retriever.retrieve_matches(target, query, max_depth)++ return GetEntityInfoResponse(target_node=paths.target_node, path=paths)+++async def get_entity_context(+ target: str, context_depth: int = 3, brain_id: str = "default"+) -> GetEntityContextResponse:+ """+ Get the entity context for a given target.+ """+ entity_context = EntityContext(target, brain_id)+ target_node, neighborhood, text_contexts, natural_language_web = (+ entity_context.get_context(context_depth=context_depth)+ )+ return GetEntityContextResponse(+ target_node=target_node,+ neighborhood=neighborhood,+ text_contexts=text_contexts,+ natural_language_web=natural_language_web,+ )diff --git a/src/services/api/routes/retrieve.py b/src/services/api/routes/retrieve.pyindex 2865978..083297a 100644--- a/src/services/api/routes/retrieve.py+++ b/src/services/api/routes/retrieve.py@@ -3,8 +3,8 @@ File: /retrieve.pyCreated Date: Saturday October 25th 2025Author: Christian Nonis <[email protected]>------Last Modified: Saturday December 27th 2025-Modified By: the developer formerly known as Christian Nonis at <[email protected]>+Last Modified: Monday January 12th 2026 8:26:26 pm+Modified By: Christian Nonis <[email protected]>-----"""@@ -24,7 +24,7 @@ from src.services.api.controllers.retrieve import ()from src.services.api.controllers.kg import get_hops as get_hops_controllerfrom src.services.api.controllers.retrieve import (- retrieve_data as retrieve_data_controller+ retrieve_data as retrieve_data_controller,)from src.services.api.controllers.structured_data import (get_structured_data_by_id as get_structured_data_by_id_controller,@@ -41,6 +41,10 @@ from src.services.api.controllers.changelogs import (get_changelogs_list as get_changelogs_list_controller,get_changelog_types as get_changelog_types_controller,)+from src.services.api.controllers.entities import (+ get_entity_info as get_entity_info_controller,+ get_entity_context as get_entity_context_controller,+)retrieve_router = APIRouter(prefix="/retrieve", tags=["retrieve"])@@ -133,7 +137,7 @@ async def get_relationships():"""Retrieve relationships from the knowledge graph filtered by the provided criteria.-+Parameters:relationship_types (Optional[str]): Comma-separated relationship types to include; will be split into a list if provided.from_node_labels (Optional[str]): Comma-separated source node labels to filter by; will be split into a list if provided.@@ -143,7 +147,7 @@ async def get_relationships(limit (int): Maximum number of relationships to return; defaults to 10.skip (int): Number of relationships to skip (offset); defaults to 0.brain_id (str): Identifier of the brain (dataset) to query; defaults to "default".-+Returns:A list of relationship records that match the provided filters."""@@ -163,6 +167,7 @@ async def get_relationships(query_search_target,)+@retrieve_router.get(path="/entities")async def get_entities(limit: int = 10,@@ -173,14 +178,14 @@ async def get_entities():"""Retrieve entities from the graph matching optional label and text filters.-+Parameters:limit (int): Maximum number of entities to return.skip (int): Number of entities to skip (offset).node_labels (Optional[str]): Comma-separated node labels to filter by (e.g. "Person,Company"); if provided, only entities with any of these labels are returned.query_text (Optional[str]): Free-text filter to match entity properties or content.brain_id (str): Identifier of the brain/knowledge store to query.-+Returns:A collection of entities that match the provided filters and pagination parameters."""@@ -262,7 +267,7 @@ async def get_observations_list():"""Retrieve a list of observations filtered by the provided parameters.-+Parameters:limit (int): Maximum number of observations to return.skip (int): Number of observations to skip (offset).@@ -270,14 +275,17 @@ async def get_observations_list(labels (Optional[str]): Comma-separated observation labels to filter by; when provided, labels are treated as a list of strings.query_text (Optional[str]): Full-text query to filter observations.brain_id (str): Identifier of the brain/tenant to query.-+Returns:list: A list of observation records that match the provided filters."""if labels:labels = labels.split(",")-- return await get_observations_list_controller(limit, skip, resource_id, labels, query_text, brain_id)++ return await get_observations_list_controller(+ limit, skip, resource_id, labels, query_text, brain_id+ )+@retrieve_router.get(path="/changelogs/types")async def get_changelog_types(@@ -285,15 +293,16 @@ async def get_changelog_types():"""Retrieve all unique changelog types for the specified brain.-+Parameters:brain_id (str): Identifier of the brain to query; defaults to "default".-+Returns:list[str]: List of unique changelog type names."""return await get_changelog_types_controller(brain_id)+@retrieve_router.get(path="/changelogs/{id}")async def get_changelog_by_id(id: str,@@ -301,16 +310,17 @@ async def get_changelog_by_id():"""Retrieve a changelog record by its identifier.-+Parameters:id (str): The changelog's unique identifier.brain_id (str): Identifier of the brain to query; defaults to "default".-+Returns:The changelog record matching `id`."""return await get_changelog_by_id_controller(id, brain_id)+@retrieve_router.get(path="/changelogs")async def get_changelogs_list(limit: int = 10,@@ -321,17 +331,19 @@ async def get_changelogs_list():"""Retrieve a paginated list of changelogs.-+Parameters:types (Optional[str]): Optional comma-separated changelog types to filter by; each type will be applied as a filter.query_text (Optional[str]): Optional text used to filter changelogs by content or metadata.-+Returns:list: Changelog records matching the provided filters, constrained by `limit` and `skip`."""if types:types = types.split(",")- return await get_changelogs_list_controller(limit, skip, types, query_text, brain_id)+ return await get_changelogs_list_controller(+ limit, skip, types, query_text, brain_id+ )@retrieve_router.get(path="/hops")@@ -345,3 +357,28 @@ async def get_hops(Get the hops in the graph for a given query."""return await get_hops_controller(query, degrees, flattened, brain_id)+++@retrieve_router.get(path="/entity/info")+async def get_entity_info(+ target: str,+ query: str,+ max_depth: int = 3,+ brain_id: str = "default",+):+ """+ Get the entity info for a given query.+ """+ return await get_entity_info_controller(target, query, max_depth, brain_id)+++@retrieve_router.get(path="/entity/context")+async def get_entity_context(+ target: str,+ context_depth: int = 3,+ brain_id: str = "default",+):+ """+ Get the entity context for a given target.+ """+ return await get_entity_context_controller(target, context_depth, brain_id)diff --git a/src/services/chat/__init__.py b/src/services/chat/__init__.pynew file mode 100644index 0000000..db1951f--- /dev/null+++ b/src/services/chat/__init__.py@@ -0,0 +1,10 @@+"""+File: /__init__.py+Project: chat+Created Date: Sunday January 18th 2026+Author: Christian Nonis <[email protected]>+-----+Last Modified: Sunday January 18th 2026 9:03:52 pm+Modified By: Christian Nonis <[email protected]>+-----+"""