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(synergies/matches): improved matching and migrated into synergies
Christian97eb6f6b81f8
diff --git a/src/core/search/entity_sibilings.py b/src/core/search/entity_sibilings.pyindex 3d83bfb..813f79f 100644--- a/src/core/search/entity_sibilings.py+++ b/src/core/search/entity_sibilings.py@@ -8,8 +8,7 @@ Modified By: Christian Nonis <[email protected]>-----"""-from dataclasses import dataclass-from typing import List, Literal, Tuple+from typing import Dict, List, Literal, Tupleimport numpy as npfrom src.adapters.interfaces.graph import PredicateWithFlowKey@@ -19,11 +18,21 @@ from src.services.kg_agent.main import (graph_adapter,vector_store_adapter,)+from src.utils.similarity.numbers import wmean, wsimfrom src.utils.similarity.vectors import cosine_similarity+# Strengthen the similarity between target and neighbor nodes that are directly connectedDIRECT_MULTIPLIER = 1.30++# Lowers the similarity between target and neighbor nodes that connected by similar nodes but not directly connectedREMOTE_MULTIPLIER = 0.70+# Weight to strengthen the similarity by the more things in common between the neighbor and the target+FACTORS_INCREMENTAL_WEIGHT = 0.3++# Weight to strengthen the similarity by the comparison of the neighbor+target descriptions+NODE_SIM_DESC_INCREMENTAL_WEIGHT = 0.5+class EntitySinergyRetriever:def __init__(self, brain_id: str = "default"):@@ -36,7 +45,12 @@ class EntitySinergyRetriever:self.brain_id = brain_iddef retrieve_sibilings(- self, target: str, polarity: Literal["same", "opposite"]+ self,+ target: str,+ polarity: Literal["same", "opposite"],+ do: bool = False,+ pa: bool = False,+ ppa: bool = False,) -> Tuple[Node, List[EntitySynergy], List[Node], List[Node]]:"""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.@@ -46,62 +60,65 @@ class EntitySinergyRetriever: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".+ do: If True, only direct synergies are returned.+ pa: If True, potential anchors are returned.+ ppa: If True, potential positive anchors are returned.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(- target_embedding.embeddings, store="nodes", brain_id=self.brain_id- )- if not target_node_vs:- return None, [], []- target_node_id = target_node_vs[0].metadata.get("uuid")- target_node = graph_adapter.get_by_uuid(target_node_id, brain_id=self.brain_id)- if not target_node:- return None, [], []-- _neighbors = graph_adapter.get_neighbors(- [target_node_id], brain_id=self.brain_id- )- neighbors = _neighbors[target_node_id]- positivep_connections: List[EntitySynergy] = []- seen_set = set([target_node.uuid])-- all_seed_nodes: List[Node] = []- all_similar_seeds: List[Node] = []-- target_vid = target_node.properties.get("v_id")- target_embedding = None- if target_vid:- _target_embedding = vector_store_adapter.get_by_ids(- [target_vid],- store="nodes",+ def _get_first_embedding(ids: List[str], store: str):+ _embeddings = vector_store_adapter.get_by_ids(+ ids,+ store=store,brain_id=self.brain_id,)- if _target_embedding:- target_embedding = _target_embedding[0].embeddings+ if not _embeddings:+ return None+ return _embeddings[0].embeddings- for neighbor in neighbors:+ def _association_score(tn_score, rel_score, multiplier):+ return (+ (np.mean([tn_score, rel_score], axis=0) * (multiplier))+ if tn_score and rel_score+ else 0.0+ )++ def _upsert_connection(seed_node: Node, neighbor_node: Node, score: float):+ if neighbor_node.uuid not in positivep_connections:+ positivep_connections[neighbor_node.uuid] = EntitySynergy(+ node=neighbor_node,+ connected_by=[seed_node],+ association_score=score,+ )+ else:+ pas = positivep_connections[neighbor_node.uuid].association_score+ nas = score+ n_association_score = wmean([pas, nas], FACTORS_INCREMENTAL_WEIGHT)+ positivep_connections[neighbor_node.uuid].connected_by.append(seed_node)+ positivep_connections[neighbor_node.uuid].association_score = (+ n_association_score+ )+ seen_set.add(seed_node.uuid)++ def _collect_seed_nodes_for_neighbor(neighbor):seed_nodes_for_neighbor = []target_embeddings = []- _neighbor_embeddings = vector_store_adapter.get_by_ids(+ neighbor_embeddings = _get_first_embedding([neighbor[0].properties.get("v_id")],store="relationships",- brain_id=self.brain_id,)- if not _neighbor_embeddings:- continue- neighbor_embeddings = _neighbor_embeddings[0].embeddings+ if neighbor_embeddings is None:+ return None, Noneif "EVENT" in neighbor[1].labels:flow_key = neighbor[0].flow_key or neighbor[0].properties.get("flow_key")if not flow_key:- continue+ return None, Nonenext_rels = graph_adapter.get_nexts_by_flow_key([PredicateWithFlowKey(@@ -111,223 +128,250 @@ class EntitySinergyRetriever:],brain_id=self.brain_id,)+ collected_embeddings = []for t in next_rels[neighbor[0].uuid]:if target_node.uuid in [t[2].uuid, t[0].uuid]:continuev_id = t[1].properties.get("v_id")if not v_id:continue- _target_embedding = vector_store_adapter.get_by_ids(+ target_embedding_for_edge = _get_first_embedding([v_id],store="relationships",- brain_id=self.brain_id,)- if not _target_embedding:+ if not target_embedding_for_edge:continue- target_embedding = _target_embedding[0].embeddings- target_embeddings.append(- np.mean(- [target_embedding, neighbor_embeddings],- axis=0,- )- )+ collected_embeddings.append(target_embedding_for_edge)seed_nodes_for_neighbor.append(t[2])+ if collected_embeddings:+ target_embeddings = np.mean(+ [neighbor_embeddings] + collected_embeddings,+ axis=0,+ )+ else:+ target_embeddings = neighbor_embeddingselse:seed_nodes_for_neighbor = [neighbor[1]]target_embeddings = neighbor_embeddings+ return seed_nodes_for_neighbor, target_embeddings- all_seed_nodes.extend(seed_nodes_for_neighbor)+ def _process_seed(seed_node: Node, direct: bool, target_embeddings):+ MULTIPLIER = DIRECT_MULTIPLIER if direct else REMOTE_MULTIPLIER- print(- f"[SEED NODES] {[n.name for n in seed_nodes_for_neighbor]}"- ) # PERFECT+ if seed_node.uuid in seen_set:+ return- def _process_seed(seed_node: Node, direct: bool):- _neighbors_direct = graph_adapter.get_neighbors(- [seed_node.uuid],- of_types=target_node.labels,- brain_id=self.brain_id,- )+ _neighbors_direct = graph_adapter.get_neighbors(+ [seed_node.uuid],+ of_types=target_node.labels,+ brain_id=self.brain_id,+ )- _neighbors_event_edges = graph_adapter.get_neighbors(- [seed_node.uuid],- of_types=["EVENT"],- brain_id=self.brain_id,- )- edges_map = {- edge[0].uuid: edge[0]- for edge in _neighbors_event_edges[seed_node.uuid]- }- _neighbors_event = graph_adapter.get_nexts_by_flow_key(- [- PredicateWithFlowKey(- predicate_uuid=edge_uuid,- flow_key=edges_map[edge_uuid].flow_key,- )- for edge_uuid in edges_map.keys()- ],- brain_id=self.brain_id,- )+ _neighbors_event_edges = graph_adapter.get_neighbors(+ [seed_node.uuid],+ of_types=["EVENT"],+ brain_id=self.brain_id,+ )+ edges_map = {+ edge[0].uuid: edge[0] for edge in _neighbors_event_edges[seed_node.uuid]+ }+ _neighbors_event = graph_adapter.get_nexts_by_flow_key(+ [+ PredicateWithFlowKey(+ predicate_uuid=edge_uuid,+ flow_key=edges_map[edge_uuid].flow_key,+ )+ for edge_uuid in edges_map.keys()+ ],+ brain_id=self.brain_id,+ )- _neighbors = []- for edge_uuid, n in _neighbors_event.items():- for e in n:- if e[2].uuid != target_node.uuid:- if e[2].uuid in seen_set:- continue- if not set(e[2].labels).intersection(target_node.labels):- continue- edge_vid = edges_map[edge_uuid].properties.get("v_id")- if not edge_vid:- continue- _edge_embedding = vector_store_adapter.get_by_ids(+ _neighbors = []+ for edge_uuid, n in _neighbors_event.items():+ for e in n:+ if e[2].uuid != target_node.uuid:+ tn_score = None+ rel_score = None+ if not set(e[2].labels).intersection(target_node.labels):+ continue+ edge_vid = edges_map[edge_uuid].properties.get("v_id")+ if edge_vid:+ edge_embedding = _get_first_embedding([edge_vid],store="relationships",- brain_id=self.brain_id,)- if not _edge_embedding:- continue- edge_embedding = _edge_embedding[0].embeddings- _en_embedding = vector_store_adapter.get_by_ids(- [e[1].properties.get("v_id")],- store="relationships",- brain_id=self.brain_id,- )- if not _en_embedding:- continue- en_embedding = _en_embedding[0].embeddings- found_embeddings = np.mean(- [- en_embedding,- edge_embedding,- ],- axis=0,- )- neighbor_vid = e[1].properties.get("v_id")- if not neighbor_vid:- continue- _neighbor_embedding = vector_store_adapter.get_by_ids(- [neighbor_vid],- store="relationships",- brain_id=self.brain_id,- )- if not _neighbor_embedding:- continue- neighbor_embedding = _neighbor_embedding[0].embeddings- tn_score = cosine_similarity(- neighbor_embedding, target_embedding- )- rel_score = cosine_similarity(- found_embeddings, target_embedding- )- print(- f"[{e[2].name}] tn_score: {tn_score}, rel_score: {rel_score}, {DIRECT_MULTIPLIER if direct else REMOTE_MULTIPLIER}"- )- _neighbors.append(- (- (- np.mean([tn_score, rel_score], axis=0)- * (- DIRECT_MULTIPLIER- if direct- else REMOTE_MULTIPLIER+ if edge_embedding is not None:+ en_vid = e[1].properties.get("v_id")+ if en_vid:+ en_embedding = _get_first_embedding(+ [en_vid],+ store="relationships",+ )+ if en_embedding is not None:+ found_embeddings = np.mean(+ [+ en_embedding,+ edge_embedding,+ ],+ axis=0,)- ),- e[2],- )+ neighbor_node_vid = e[2].properties.get("v_id")+ if neighbor_node_vid:+ neighbor_node_embedding = (+ _get_first_embedding(+ [neighbor_node_vid],+ store="nodes",+ )+ )+ tn_score = wsim(+ cosine_similarity(+ neighbor_node_embedding,+ target_embedding,+ ),+ NODE_SIM_DESC_INCREMENTAL_WEIGHT,+ )+ rel_score = cosine_similarity(+ found_embeddings,+ target_embeddings,+ )+ print(+ f"[{seed_node.name}] -> {tn_score} {rel_score}"+ )+ _neighbors.append(+ (+ _association_score(+ tn_score,+ rel_score,+ MULTIPLIER,+ ),+ e[2],)+ )- for dn in _neighbors_direct[seed_node.uuid]:- if dn[1].uuid != target_node.uuid:- if dn[1].uuid in seen_set:- continue- n_vid = dn[0].properties.get("v_id")- if not n_vid:- continue- _n_embedding = vector_store_adapter.get_by_ids(+ for dn in _neighbors_direct[seed_node.uuid]:+ if dn[1].uuid != target_node.uuid:+ n_vid = dn[0].properties.get("v_id")+ tn_score = None+ rel_score = None+ if n_vid:+ n_embedding = _get_first_embedding([n_vid],store="relationships",- brain_id=self.brain_id,)- if not _n_embedding:- continue- n_embedding = _n_embedding[0].embeddings- tn_score = cosine_similarity(n_embedding, target_embedding)- rel_vid = dn[0].properties.get("v_id")- if not rel_vid:- continue- _rel_embedding = vector_store_adapter.get_by_ids(- [rel_vid],- store="relationships",- brain_id=self.brain_id,- )- if not _rel_embedding:- continue- rel_embedding = _rel_embedding[0].embeddings- rel_score = cosine_similarity(rel_embedding, target_embedding)- _neighbors.append(- (- (- np.mean([tn_score, rel_score], axis=0)- * (- DIRECT_MULTIPLIER- if direct- else REMOTE_MULTIPLIER- )- ),- dn[1],+ if n_embedding is not None:+ tn_score = cosine_similarity(+ n_embedding,+ target_embedding,)+ rel_vid = dn[0].properties.get("v_id")+ if rel_vid:+ rel_embedding = _get_first_embedding(+ [rel_vid],+ store="relationships",+ )+ if rel_embedding is not None:+ rel_score = cosine_similarity(+ rel_embedding,+ target_embedding,+ )+ _neighbors.append(+ (+ _association_score(+ tn_score,+ rel_score,+ MULTIPLIER,+ ),+ dn[1],)+ )- if not _neighbors or len(_neighbors) == 0:- return+ if not _neighbors:+ return- for neighbor in _neighbors:- positivep_connections.append(- EntitySynergy(- node=neighbor[1],- connected_by=seed_node,- association_score=neighbor[0],- )- )- seen_set.add(neighbor[1].uuid)+ for neighbor in _neighbors:+ _upsert_connection(seed_node, neighbor[1], neighbor[0])++ target_embedding = embeddings_adapter.embed_text(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_id = target_node_vs[0].metadata.get("uuid")+ target_node = graph_adapter.get_by_uuid(target_node_id, brain_id=self.brain_id)+ if not target_node:+ return None, [], []++ _neighbors = graph_adapter.get_neighbors(+ [target_node_id], brain_id=self.brain_id+ )+ neighbors = _neighbors[target_node_id]++ positivep_connections: Dict[str, EntitySynergy] = {}+ seen_set = set([target_node.uuid])++ all_seed_nodes: List[Node] = []+ all_similar_seeds: List[Node] = []++ target_vid = target_node.properties.get("v_id")+ target_embedding = None+ if target_vid:+ target_embedding = _get_first_embedding([target_vid], store="nodes")++ for neighbor in neighbors:+ seed_nodes_for_neighbor, target_embeddings = (+ _collect_seed_nodes_for_neighbor(neighbor)+ )+ if seed_nodes_for_neighbor is None:+ continue++ all_seed_nodes.extend(seed_nodes_for_neighbor)for seed_node in seed_nodes_for_neighbor:- seed_vid = seed_node.properties.get("v_id")- if not seed_vid:- continue- _seed_embedding = vector_store_adapter.get_by_ids(- [seed_vid],- store="nodes",- brain_id=self.brain_id,- )- if not _seed_embedding:- continue- seed_embedding = _seed_embedding[0].embeddings+ if ppa or not do:+ seed_vid = seed_node.properties.get("v_id")+ if seed_vid:+ seed_embedding = _get_first_embedding(+ [seed_vid],+ store="nodes",+ )+ if seed_embedding is None:+ continue+ similar_seed_vs = vector_store_adapter.search_vectors(+ seed_embedding,+ store="nodes",+ brain_id=self.brain_id,+ )- similar_seed_vs = vector_store_adapter.search_vectors(- seed_embedding,- store="nodes",- brain_id=self.brain_id,- )+ similar_seeds = graph_adapter.get_by_uuids(+ [vs.metadata.get("uuid") for vs in similar_seed_vs],+ brain_id=self.brain_id,+ )- similar_seeds = graph_adapter.get_by_uuids(- [vs.metadata.get("uuid") for vs in similar_seed_vs],- brain_id=self.brain_id,+ _process_seed(+ seed_node, direct=True, target_embeddings=target_embeddings)- _process_seed(seed_node, direct=True)+ if pa or not do:+ all_similar_seeds.extend(similar_seeds)- all_similar_seeds.extend(similar_seeds)-- for similar_seed in similar_seeds:- _process_seed(similar_seed, direct=False)+ if not do:+ for similar_seed in similar_seeds:+ _process_seed(+ similar_seed,+ direct=False,+ target_embeddings=target_embeddings,+ )unique_seeds = {n.uuid: n for n in all_seed_nodes}return (target_node,sorted(- positivep_connections, key=lambda x: x.association_score, reverse=True+ positivep_connections.values(),+ key=lambda x: x.association_score,+ reverse=True,),list(unique_seeds.values()),all_similar_seeds,diff --git a/src/services/api/constants/requests.py b/src/services/api/constants/requests.pyindex d32a145..58436f3 100644--- a/src/services/api/constants/requests.py+++ b/src/services/api/constants/requests.py@@ -264,8 +264,8 @@ class GetEntitySibilingsResponse(BaseModel):target_node: Nodesynergies: List[EntitySynergy]- anchors: List[Node]- potential_anchors: List[Node]+ anchors: Optional[List[Node]] = None+ potential_anchors: Optional[List[Node]] = Noneclass GetEntityStatusResponse(BaseModel):diff --git a/src/services/api/controllers/entities.py b/src/services/api/controllers/entities.pyindex deaaf9f..1eaa4c8 100644--- a/src/services/api/controllers/entities.py+++ b/src/services/api/controllers/entities.py@@ -10,6 +10,8 @@ Modified By: Christian Nonis <[email protected]>"""from typing import List, Literal++from starlette.responses import JSONResponsefrom src.core.search.entity_context import EntityContextfrom src.core.search.entity_info import EventSynergyRetrieverfrom src.services.api.constants.requests import (@@ -78,6 +80,9 @@ async def get_entity_context(async def get_entity_sibilings(target: str,polarity: Literal["same", "opposite"] = "same",+ do: bool = False,+ pa: bool = False,+ ppa: bool = False,brain_id: str = "default",) -> GetEntitySibilingsResponse:"""@@ -85,19 +90,36 @@ async def get_entity_sibilings(Parameters:polarity (Literal["same", "opposite"]): Which polarity of siblings to return — "same" for similar entities, "opposite" for contrasted entities.+ do (bool): If True, only direct synergies are returned.+ pa (bool): If True, potential anchors are returned.+ ppa (bool): If True, potential positive anchors are returned.Returns:GetEntitySibilingsResponse: Object containing the resolved target node and its list of synergies."""entity_sibilings = EntitySinergyRetriever(brain_id)target_node, synergies, seed_nodes, potential_anchors = (- entity_sibilings.retrieve_sibilings(target, polarity)+ entity_sibilings.retrieve_sibilings(target, polarity, do, pa, ppa))- return GetEntitySibilingsResponse(- target_node=target_node,- synergies=synergies,- anchors=seed_nodes,- potential_anchors=potential_anchors,+ return JSONResponse(+ content={+ "target_node": target_node.model_dump(mode="json"),+ "synergies": [synergy.model_dump(mode="json") for synergy in synergies],+ **(+ {"anchors": [anchor.model_dump(mode="json") for anchor in seed_nodes]}+ if ppa and seed_nodes+ else {}+ ),+ **(+ {+ "potential_anchors": [+ anchor.model_dump(mode="json") for anchor in potential_anchors+ ]+ }+ if pa and potential_anchors+ else {}+ ),+ })diff --git a/src/services/api/routes/retrieve.py b/src/services/api/routes/retrieve.pyindex 103ca90..04d96e8 100644--- a/src/services/api/routes/retrieve.py+++ b/src/services/api/routes/retrieve.py@@ -3,7 +3,7 @@ File: /retrieve.pyCreated Date: Saturday October 25th 2025Author: Christian Nonis <[email protected]>------Last Modified: Monday January 12th 2026 8:26:26 pm+Last Modified: Thursday January 29th 2026 8:43:59 pmModified By: Christian Nonis <[email protected]>-----"""@@ -113,13 +113,13 @@ async def get_neighbors_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."""@@ -132,10 +132,10 @@ async def get_neighbors_ai_mode(async def get_context(request):"""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."""@@ -154,7 +154,7 @@ async def get_relationships():"""Retrieve relationships filtered by types, node labels, and query criteria.-+Parameters:relationship_types (Optional[str]): Comma-separated relationship types to include.from_node_labels (Optional[str]): Comma-separated source node labels to filter.@@ -164,7 +164,7 @@ async def get_relationships(limit (int): Maximum number of relationships to return.skip (int): Number of relationships to skip.brain_id (str): Brain (dataset) identifier.-+Returns:List of relationship records matching the filters."""@@ -195,12 +195,12 @@ async def get_entities():"""Retrieve entities matching optional label and text filters with pagination.-+Parameters: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:list: A list of entity records that match the provided filters and pagination parameters."""@@ -325,11 +325,11 @@ async def get_changelog_by_id():"""Retrieve a changelog entry by its unique identifier.-+Parameters:id (str): Unique identifier of the changelog entry.brain_id (str): Brain identifier to query. Defaults to "default".-+Returns:The changelog entry corresponding to the specified identifier."""@@ -370,13 +370,13 @@ async def get_hops(): # noqa: F821"""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`."""@@ -392,13 +392,13 @@ async def get_entity_info():"""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."""@@ -413,12 +413,12 @@ async def get_entity_context():"""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."""@@ -429,20 +429,28 @@ async def get_entity_context(async def get_entity_synergies(target: str,polarity: Literal["same", "opposite"] = "same",+ do: bool = False,+ pa: bool = False,+ ppa: bool = False,brain_id: str = "default",):"""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.-+ do (bool): If True, only direct synergies are returned.+ pa (bool): If True, potential anchors are returned.+ ppa (bool): If True, potential positive anchors are returned.+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)+ return await get_entity_sibilings_controller(+ target, polarity, do, pa, ppa, brain_id+ )@retrieve_router.get(path="/entity/status")@@ -453,13 +461,13 @@ async def get_entity_status():"""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.-+ 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.+ status (dict): A dictionary containing the entity's status details."""- return await get_entity_status_controller(target, types, brain_id)\ No newline at end of file+ return await get_entity_status_controller(target, types, brain_id)diff --git a/src/utils/similarity/numbers.py b/src/utils/similarity/numbers.pynew file mode 100644index 0000000..5c4344e--- /dev/null+++ b/src/utils/similarity/numbers.py@@ -0,0 +1,51 @@+"""+File: /numbers.py+Project: similarity+Created Date: Monday February 2nd 2026+Author: Christian Nonis <[email protected]>+-----+Last Modified: Monday February 2nd 2026 8:40:10 pm+Modified By: Christian Nonis <[email protected]>+-----+"""++from typing import List+++def wsim(similarity: float, weight: float) -> float:+ """+ Weighten the similarity by the weight.+ eg: similarity = 0.25, weight = 0.25 -> new similarity = 0.25^(1-0.25) = 0.35+ eg: similarity = 0.25, weight = 0.75 -> new similarity = 0.25^(1-0.75) = 0.71++ eg: similarity = 0.25, weight = -0.25 -> new similarity = 0.25^(1+0.25) = 0.18+ eg: similarity = 0.25, weight = -0.75 -> new similarity = 0.25^(1+0.75) = 0.09++ Arguments:+ similarity (float): The similarity to weighten.+ weight (float): 0.0 to 1.0 - The weight to weighten the similarity by.++ Returns:+ float: The weighted similarity.+ """+ return similarity ** (1 - weight)+++def wmean(values: List[float], weight: float) -> float:+ """+ Weighted mean of a list of values.+ """++ if not values:+ return 0.0+ if len(values) == 1:+ return values[0]+ n = len(values)+ # Modified: ensure effective_weight is not zero for n=2+ # The original was: weight * max(0, n - 2) / max(2, n)+ effective_weight = weight * max(1, n - 2) / max(2, n)+ transformed = [+ wsim(values[0], effective_weight),+ wsim(values[1], effective_weight),+ ] + list(values[2:])+ return sum(transformed) / len(transformed)