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(neighbors)
Christian0b11899ed4d2
diff --git a/Makefile b/Makefileindex 311627e..cd7e04a 100644--- a/Makefile+++ b/Makefile@@ -50,11 +50,12 @@ start-api:stop-api:pkill -f uvicorn+DEBUG_ENVS := LANGCHAIN_DEBUG="true" LANGCHAIN_VERBOSE="true" DEBUG="true"start-all:- if [ "$1" = "debug" ]; then \- export LANGCHAIN_DEBUG="true"; \- export LANGCHAIN_VERBOSE="true"; \+ @if [ "$$DEBUG" = "true" ]; then \+ echo "DEBUG mode enabled"; \+ export $(DEBUG_ENVS); \fiexport ENV=developmentmake start-milvus &@@ -63,7 +64,10 @@ start-all:make start-neo4j &make start-mongo &make start-api &- @bash -c "poetry run celery -A src.workers.app worker --loglevel=info"+ @bash -c "if [ "$$DEBUG" = "true" ]; then export $(DEBUG_ENVS) && poetry run celery -A src.workers.app worker --loglevel=info; else poetry run celery -A src.workers.app worker --loglevel=info; fi"++debug:+ @:stop-all:make stop-milvusdiff --git a/src/adapters/graph.py b/src/adapters/graph.pyindex 98831c7..4fe9ed6 100644--- a/src/adapters/graph.py+++ b/src/adapters/graph.py@@ -8,9 +8,9 @@ Modified By: the developer formerly known as Christian Nonis at <alch.infoemail@-----"""-from typing import Optional+from typing import Optional, Tuplefrom src.adapters.interfaces.graph import GraphClient-from src.constants.kg import IdentificationParams, Node, Predicate+from src.constants.kg import IdentificationParams, Node, Predicate, Tripleclass GraphAdapter:@@ -152,11 +152,43 @@ class GraphAdapter:identification_params, entity_types)- def get_neighbors(self, node: Node, limit: int) -> list[Node]:+ def get_neighbors(+ self, node: Node, limit: int+ ) -> list[Tuple[Node, Predicate, Node]]:"""Get the neighbors of a node."""return self.graph.get_neighbors(node, limit)+ def get_node_with_rel_by_uuid(+ self, rel_ids_with_node_ids: list[tuple[str, str]]+ ) -> list[dict]:+ """+ Get the node with the relationships by their UUIDs.+ """+ return self.graph.get_node_with_rel_by_uuid(rel_ids_with_node_ids)++ def get_neighbor_node_tuples(+ self, a_uuid: str, b_uuids: list[str]+ ) -> list[Tuple[Node, Predicate, Node]]:+ """+ Get the neighbor node tuples by their UUIDs.+ """+ return self.graph.get_neighbor_node_tuples(a_uuid, b_uuids)++ def get_connected_nodes(+ self,+ node: Optional[Node] = None,+ uuids: Optional[list[str]] = None,+ limit: Optional[int] = 10,+ with_labels: Optional[list[str]] = None,+ ) -> list[Tuple[Node, Predicate, Node]]:+ """+ Get the connected nodes by their UUIDs.+ """+ return self.graph.get_connected_nodes(+ node=node, uuids=uuids, limit=limit, with_labels=with_labels+ )+_graph_adapter = GraphAdapter()diff --git a/src/adapters/interfaces/graph.py b/src/adapters/interfaces/graph.pyindex e7e9673..37c3688 100644--- a/src/adapters/interfaces/graph.py+++ b/src/adapters/interfaces/graph.py@@ -9,9 +9,9 @@ Modified By: the developer formerly known as Christian Nonis at <alch.infoemail@"""from abc import ABC, abstractmethod-from typing import Optional+from typing import Optional, Tuple-from src.constants.kg import IdentificationParams, Node, Predicate+from src.constants.kg import IdentificationParams, Node, Predicate, Tripleclass GraphClient(ABC):@@ -155,8 +155,42 @@ class GraphClient(ABC):self,node: Node,limit: int,- ) -> list[Node]:+ ) -> list[Tuple[Node, Predicate, Node]]:"""Get the neighbors of a node."""raise NotImplementedError("get_neighbors method not implemented")++ @abstractmethod+ def get_node_with_rel_by_uuid(+ self,+ rel_ids_with_node_ids: list[tuple[str, str]],+ ) -> list[dict]:+ """+ Get the node with the relationships by their UUIDs.+ """+ raise NotImplementedError("get_node_with_rel_by_uuid method not implemented")++ @abstractmethod+ def get_neighbor_node_tuples(+ self,+ a_uuid: str,+ b_uuids: list[str],+ ) -> list[Tuple[Node, Predicate, Node]]:+ """+ Get the neighbor node tuples by their UUIDs.+ """+ raise NotImplementedError("get_neighbor_node_tuples method not implemented")++ @abstractmethod+ def get_connected_nodes(+ self,+ node: Optional[Node] = None,+ uuids: Optional[list[str]] = None,+ limit: Optional[int] = 10,+ with_labels: Optional[list[str]] = None,+ ) -> list[Tuple[Node, Predicate, Node]]:+ """+ Get the connected nodes by their UUIDs.+ """+ raise NotImplementedError("get_connected_nodes method not implemented")diff --git a/src/constants/kg.py b/src/constants/kg.pyindex 519226a..db9f1c5 100644--- a/src/constants/kg.py+++ b/src/constants/kg.py@@ -13,6 +13,8 @@ from typing import List, Literal, Optionalimport uuidfrom pydantic import BaseModel, Extra, Field+from src.constants.data import Observation+class Node(BaseModel):"""@@ -29,6 +31,10 @@ class Node(BaseModel):description="The date and time the node was last updated.",)+ observations: Optional[List[Observation]] = Field(+ default=None, description="The observations of the node."+ )+class Meta:"""Allow extra properties to be added to the node.@@ -52,11 +58,25 @@ class Predicate(BaseModel):default=False, description="Whether the predicate is deprecated.")- direction: Optional[Literal["in", "out"]] = Field(- default="out",+ direction: Optional[Literal["in", "out", "neutral"]] = Field(+ default="neutral",description="The direction of the predicate.",)+ observations: Optional[List[Observation]] = Field(+ default=None, description="The observations of the predicate."+ )++ level: Optional[Literal["1", "2", "3"]] = Field(+ default=None,+ description=(+ "The level of the predicate. "+ "1: directly connected to the main node. "+ "2: connected to similar nodes of same label, not directly connected."+ "3: connected to similar nodes of different label, not directly connected."+ ),+ )+class Triple(BaseModel):"""@@ -73,7 +93,7 @@ class Relationship(BaseModel):Relationship model."""- direction: Literal["in", "out"]+ direction: Literal["in", "out", "neutral"]predicate: Predicatediff --git a/src/lib/milvus/client.py b/src/lib/milvus/client.pyindex 8ba2149..2d20c3a 100644--- a/src/lib/milvus/client.py+++ b/src/lib/milvus/client.py@@ -55,7 +55,6 @@ class MilvusClient(VectorStoreClient):with self._get_lock():if self._client is None:if config.milvus.uri and config.milvus.token:- print("using uri", config.milvus.uri)self._client = Milvus(uri=config.milvus.uri,token=config.milvus.token,diff --git a/src/lib/neo4j/client.py b/src/lib/neo4j/client.pyindex c6253ae..382df22 100644--- a/src/lib/neo4j/client.py+++ b/src/lib/neo4j/client.py@@ -8,6 +8,7 @@ Modified By: the developer formerly known as Christian Nonis at <alch.infoemail@-----"""+import osfrom typing import Optional, Tuplefrom neo4j import GraphDatabasefrom src.adapters.interfaces.graph import GraphClient@@ -248,11 +249,12 @@ 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+ RETURN+ n.uuid as uuid, n.name as name, labels(n) as labels, n.description as description, properties(n) as properties"""if with_relationships:- cypher_query += ", r, m"+ cypher_query += ", r, 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"result = self.driver.execute_query(cypher_query)@@ -267,7 +269,17 @@ class Neo4jClient(GraphClient):properties=record["properties"],),"relationships": record["r"] if record["r"] else None,- "related_nodes": record["m"] if record["m"] else None,+ "related_nodes": (+ Node(+ uuid=record["m_uuid"],+ name=record["m_name"],+ labels=record["m_labels"],+ description=record["m_description"],+ properties=record["m_properties"],+ )+ if record["m_uuid"]+ else None+ ),}for record in result.records]@@ -392,7 +404,9 @@ class Neo4jClient(GraphClient):result = self.driver.execute_query(cypher_query)return [record["propertyKey"] for record in result.records]- def get_neighbors(self, node: Node, limit: int) -> list[Tuple[Node, Predicate]]:+ def get_neighbors(+ self, node: Node, limit: int+ ) -> list[Tuple[Node, Predicate, Node]]:"""Get the neighbors of a node."""@@ -400,7 +414,8 @@ class Neo4jClient(GraphClient):cypher_query = f"""MATCH (n {{uuid: '{node.uuid}'}})-[r]-(c)-[r2]-(m)WHERE size([l IN labels(n) WHERE l IN labels(m)]) > 0- RETURN m.uuid AS uuid, m.name AS name, labels(m) AS labels, m.description AS description, properties(m) AS properties, r2 AS rel+ RETURN m.uuid AS uuid, m.name AS name, labels(m) AS labels, m.description AS description, properties(m) AS properties, r2 AS rel,+ CASE WHEN startNode(r2) = c THEN 'out' ELSE 'in' END AS direction"""result = self.driver.execute_query(cypher_query)@@ -410,12 +425,86 @@ class Neo4jClient(GraphClient):rel_type = getattr(rel, "type", None)rel_desc = ""try:- rel_desc = rel.get("description", "") # for mapping-like access+ rel_desc = rel.get("description", "")except Exception:try:rel_desc = rel["description"]except Exception:rel_desc = ""+ direction = record.get("direction", "out")++ neighbors.append(+ (+ Node(+ uuid=record["uuid"],+ name=record["name"],+ labels=record["labels"],+ description=record["description"],+ properties=record["properties"],+ ),+ Predicate(+ name=rel_type or "",+ description=rel_desc or "",+ direction=direction,+ ),+ Node(+ uuid=node.uuid,+ name=node.name,+ labels=node.labels,+ description=node.description,+ properties=node.properties,+ ),+ )+ )+ return [(n, p, c) for n, p, c in neighbors]++ def get_node_with_rel_by_uuid(+ self, rel_ids_with_node_ids: list[tuple[str, str]]+ ) -> list[dict]:+ """+ Get the node with the relationships by their UUIDs.+ """++ def get_neighbor_node_tuples(+ self, a_uuid: str, b_uuids: list[str]+ ) -> list[Tuple[Node, Predicate, Node]]:+ """+ Get the neighbor node tuples by their UUIDs.+ """+ b_uuids_str = ",".join([f'"{nid}"' for nid in b_uuids])+ cypher_query = f"""+ MATCH (n)-[r]-(m)+ WHERE n.uuid = '{a_uuid}' AND m.uuid IN [{b_uuids_str}]+ RETURN+ n.uuid as n_uuid, n.name as n_name, labels(n) as n_labels,+ n.description as n_description, properties(n) as n_properties,+ 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, r as rel+ """+ result = self.driver.execute_query(cypher_query)++ if not result.records:+ if os.getenv("DEBUG") == "true":+ raise ValueError(+ f"No neighbor nodes found for UUID: {a_uuid} and b_uuids: {b_uuids}"+ )+ else:+ return []++ tuples = []+ for record in result.records:+ rel = record["rel"]++ rel_type = getattr(rel, "type", None) or ""+ rel_desc = ""+ try:+ rel_desc = rel.get("description", "")+ except Exception:+ try:+ rel_desc = rel["description"]+ except Exception:+ rel_desc = ""+direction = "out"try:start_node = rel.nodes[0]@@ -424,28 +513,92 @@ class Neo4jClient(GraphClient):start_uuid = start_node.get("uuid", None)except Exception:start_uuid = start_node["uuid"]- if start_uuid != node.uuid:+ if start_uuid != record["n_uuid"]:direction = "in"except Exception:direction = "out"- neighbors.append(+ tuples.append((Node(- uuid=record["uuid"],- name=record["name"],- labels=record["labels"],- description=record["description"],- properties=record["properties"],+ uuid=record["n_uuid"],+ name=record["n_name"],+ labels=record["n_labels"],+ description=record["n_description"],+ properties=record["n_properties"],),Predicate(- name=rel_type or "",- description=rel_desc or "",+ name=rel_type,+ description=rel_desc,direction=direction,),+ Node(+ uuid=record["m_uuid"],+ name=record["m_name"],+ labels=record["m_labels"],+ description=record["m_description"],+ properties=record["m_properties"],+ ),))- return neighbors++ return tuples++ def get_connected_nodes(+ self,+ node: Optional[Node] = None,+ uuids: Optional[list[str]] = None,+ limit: Optional[int] = 10,+ with_labels: Optional[list[str]] = None,+ ) -> list[Tuple[Node, Predicate, Node]]:+ """+ Get the connected nodes by their UUIDs.+ """+ labels_str = ""+ if with_labels:+ labels_list = ",".join([f"'{label}'" for label in with_labels])+ labels_str = f"AND ANY(l IN labels(m) WHERE l IN [{labels_list}])"+ identification_str = ""+ if node:+ identification_str = f"WHERE n.uuid = '{node.uuid}'"+ elif uuids:+ uuids_str = ",".join([f'"{uuid}"' for uuid in uuids])+ identification_str = f"WHERE n.uuid IN [{uuids_str}]"+ cypher_query = f"""+ MATCH (n)-[r]-(m)+ {identification_str}+ {labels_str}+ RETURN+ m.uuid as uuid, m.name as name, labels(m) as labels, m.description as description, properties(m) as properties,+ r as rel, type(r) as rel_type, r.description as rel_description,+ n.uuid as n_uuid, n.name as n_name, labels(n) as n_labels, n.description as n_description, properties(n) as n_properties,+ CASE WHEN startNode(r) = n THEN 'out' ELSE 'in' END AS direction+ """+ result = self.driver.execute_query(cypher_query)+ return [+ (+ Node(+ uuid=record["uuid"],+ name=record["name"],+ labels=record["labels"],+ description=record["description"],+ properties=record["properties"],+ ),+ Predicate(+ name=record["rel_type"] or "",+ description=record["rel_description"] or "",+ direction=record.get("direction", "neutral"),+ ),+ Node(+ uuid=record["n_uuid"],+ name=record["n_name"],+ labels=record["n_labels"],+ description=record["n_description"],+ properties=record["n_properties"],+ ),+ )+ for record in result.records+ ]_neo4j_client = Neo4jClient()diff --git a/src/services/api/constants/requests.py b/src/services/api/constants/requests.pyindex e24424c..b6d7b93 100644--- a/src/services/api/constants/requests.py+++ b/src/services/api/constants/requests.py@@ -12,7 +12,7 @@ from turtle import stfrom typing import List, Any, Optionalfrom pydantic import BaseModel, Field, field_serializerfrom src.constants.data import Observation, TextChunk-from src.constants.kg import IdentificationParams, Node, Relationship+from src.constants.kg import IdentificationParams, Node, Predicate, Relationshipfrom src.constants.tasks.ingestion import IngestionTaskArgs@@ -123,13 +123,14 @@ class RetrieveRequestResponse(BaseModel):return [_ser(v) for v in value] if value is not None else []-class RetrievedNeighborNode(Node):+class RetrievedNeighborNode(BaseModel):"""Node model for the retrieve neighbors endpoint."""- relation: Relationship- observations: List[str]+ neighbor: Node+ relationship: Predicate+ most_common: Nodeclass RetrieveNeighborsRequestResponse(BaseModel):@@ -137,6 +138,7 @@ class RetrieveNeighborsRequestResponse(BaseModel):Response for the retrieve neighbors endpoint."""+ count: int = Field(0, description="The number of neighbors found.")neighbors: List[RetrievedNeighborNode]diff --git a/src/services/api/controllers/retrieve.py b/src/services/api/controllers/retrieve.pyindex efac318..d405c3c 100644--- a/src/services/api/controllers/retrieve.py+++ b/src/services/api/controllers/retrieve.py@@ -9,11 +9,12 @@ Modified By: the developer formerly known as Christian Nonis at <alch.infoemail@"""import asyncio-from typing import Optional+import time+from typing import List, Optionalfrom fastapi import HTTPException-from src.constants.kg import IdentificationParams, Predicate, Relationship+from src.constants.kg import IdentificationParams, Node, Predicate, Relationshipfrom src.services.api.constants.requests import (RetrieveRequestResponse,RetrieveNeighborsRequestResponse,@@ -22,6 +23,7 @@ from src.services.api.constants.requests import (from src.services.kg_agent.main import graph_adapter, kg_agentfrom src.services.data.main import data_adapterfrom src.services.kg_agent.main import embeddings_adapter, vector_store_adapter+from src.utils.logging import log, logtasync def retrieve_data(@@ -38,7 +40,10 @@ async def retrieve_data(preferred_entities = []def _get_data():+ st1 = time.time()text_embeddings = embeddings_adapter.embed_text(text)+ et1 = time.time()+ print("[time1]", et1 - st1)data_vectors = vector_store_adapter.search_vectors(text_embeddings.embeddings, "data", limit)@@ -91,6 +96,8 @@ async def retrieve_neighbors(limit: int = 10,) -> RetrieveNeighborsRequestResponse:def _get_neighbors():++ # ================= GETTING THE MAIN NODE =================node = Noneif uuid:node = graph_adapter.get_by_uuid(uuid)@@ -101,12 +108,18 @@ async def retrieve_neighbors(if not node:raise HTTPException(status_code=404, detail="Entity not found")+ # ================= GETTING THE 2nd LEVEL NEIGHBORS =================+ # This gets the 2nd level neighbors (main)-[r1]-(common)-[r2]-(neighbor)+ # That share a common node with the main node+ # The neighbors are of the same type (share at least one label) of the+ # main noderaw = graph_adapter.get_neighbors(node, limit)- normalized = []+ normalized: List[RetrievedNeighborNode] = []+ print("[found direct neighbors]", len(raw))for item in raw:if isinstance(item, tuple) and len(item) >= 2:- n, pred = item[0], item[1]+ n, pred, common = itemelse:n, pred = item, None@@ -121,43 +134,149 @@ async def retrieve_neighbors()if not n.uuid == node.uuid:- # TODO: provide the common node too and maybe also observationsnormalized.append(RetrievedNeighborNode(- **n.model_dump(),- relation=relation,- observations=[],+ neighbor=Node(**n.model_dump()),+ relationship=Predicate(+ name=relation.predicate.name,+ description=relation.predicate.description,+ direction=relation.predicate.direction,+ observations=[],+ level="1",+ ),+ most_common=Node(**common.model_dump()),))+ # ================= GETTING THE SIMILAR NEIGHBORS =================+ # If not enough direct 2nd level connected neighbors are found,+ # Search for nodes that are similar to the 1st level connected nodes of the+ # main node and than get the connected nodes that share+ # at least one label with the main nodeif len(normalized) < limit:neighbor_nodes = graph_adapter.get_nodes_by_uuid(- uuids=[n.uuid for n in normalized], with_relationships=True+ uuids=[node.uuid], with_relationships=True)++ # Mapping the ids and the nodes into a dictionary and ids array+ related_nodes = {}+ related_node_ids = []+ for n_dict in neighbor_nodes:+ k = n_dict.get("related_nodes").uuid+ rel_node = n_dict.get("related_nodes")+ related_nodes[k] = rel_node+ related_node_ids.append(k)++ # Searching for similar nodes of the 1st level connected nodes+ # Returns a dictionary where the keys are the searched ids+ # And the values are the similar nodes found, respectivelyv_neighbors = vector_store_adapter.search_similar_by_ids(- vector_ids=[n.get("node").uuid for n in neighbor_nodes],+ vector_ids=related_node_ids,store="nodes",- min_similarity=0.5,- limit=limit - len(normalized),+ min_similarity=0.2,+ limit=(limit - len(normalized)) * 10,)- print("[v_neighbors]", v_neighbors)- # TODO: get v_neighbor nodes by ids and the k (the common)- # TODO + push to normalized- # TODO (directly the nodes with label same as main, the others search for neighbors with same label of main)+ node_labels_lower = [n.lower() for n in node.labels]+ same_main_labels_v_neighbors = {}+ others_v_neighbors = {}- if len(normalized) < limit:- v_data = vector_store_adapter.search_similar_by_ids(- vector_ids=[n.uuid for n in normalized],- store="data",- min_similarity=0.5,- limit=limit - len(normalized),- )- print("[v_data]", v_data)- # TODO: get v_neighbor nodes by ids and the k (the common)- # TODO + push to normalized- # TODO (directly the nodes with label same as main, the others search for neighbors with same label of main)+ for k, vectors in v_neighbors.items():+ # Filtering the vectors that are of the same labels as the main node+ # Directly similar nodes to the directly 1st level connected nodes+ matching_vectors = [+ vector+ for vector in vectors+ if any(+ label.lower() in node_labels_lower+ for label in vector.metadata.get("labels", [])+ )+ ]+ log("[found same label vectors]", len(matching_vectors))++ # Filtering the vectors that are NOT of the same labels as the main node+ # Similar nodes to the directly 1st level, a step to get the connected nodes+ # of the same label as the main node is needed+ non_matching_vectors = [+ vector+ for vector in vectors+ if not any(+ label.lower() in node_labels_lower+ for label in vector.metadata.get("labels", [])+ )+ ]+ log("[found non same label vectors]", len(non_matching_vectors))++ if matching_vectors:+ same_main_labels_v_neighbors[k] = matching_vectors+ if non_matching_vectors:+ others_v_neighbors[k] = non_matching_vectors++ # Getting and adding directly the similar nodes of same label as the main node+ for k, v in same_main_labels_v_neighbors.items():+ neighbor_nodes = graph_adapter.get_by_uuids(+ uuids=[vector.metadata.get("uuid") for vector in v],+ )+ normalized.extend(+ RetrievedNeighborNode(+ neighbor=Node(**n.model_dump()),+ relationship=Predicate(+ name="<SIMILAR_TO>",+ description=f"<SYS_DESCRIPTION>The neighbor and the most common are similar. Most common is directly connected to {node.name}.</SYS_DESCRIPTION>",+ direction="neutral",+ level="2",+ ),+ most_common=related_nodes[k],+ observations=[],+ )+ for n in neighbor_nodes+ if not any(+ [+ norm.neighbor.uuid == n.uuid+ or norm.most_common.uuid == related_nodes[k].uuid+ for norm in normalized+ ]+ )+ )++ # Getting the connected nodes of the similar nodes and filtering+ # the ones the are with same label as the main node+ for k, v in others_v_neighbors.items():+ neighbor_nodes = graph_adapter.get_connected_nodes(+ uuids=[vector.metadata.get("uuid") for vector in v],+ limit=limit - len(normalized),+ with_labels=node.labels,+ )+ normalized.extend(+ RetrievedNeighborNode(+ neighbor=Node(**n.model_dump()),+ relationship=Predicate(+ name=pred.name,+ description=pred.description,+ direction=pred.direction,+ level="3",+ ),+ most_common=Node(**common.model_dump()),+ )+ for n, pred, common in neighbor_nodes+ if not any([norm.neighbor.uuid == n.uuid for norm in normalized])+ )++ # if len(normalized) < limit:+ # v_data = vector_store_adapter.search_similar_by_ids(+ # vector_ids=[node.uuid],+ # store="data",+ # min_similarity=0.5,+ # limit=limit - len(normalized),+ # )+ # print("[v_data]", v_data) # === same as above ===+ # # TODO: get v_neighbor nodes by ids and the k (the common)+ # # TODO + push to normalized+ # # TODO (directly the nodes with label same as main, the others search for neighbors with same label of main)- return RetrieveNeighborsRequestResponse(neighbors=normalized)+ # Returning all the nodes found respecting the limit+ return RetrieveNeighborsRequestResponse(+ count=len(normalized), neighbors=normalized+ )return await asyncio.to_thread(_get_neighbors)diff --git a/src/utils/logging.py b/src/utils/logging.pynew file mode 100644index 0000000..746f1f2--- /dev/null+++ b/src/utils/logging.py@@ -0,0 +1,34 @@+"""+File: /logging.py+Created Date: Saturday November 1st 2025+Author: Christian Nonis <[email protected]>+-----+Last Modified: Saturday November 1st 2025 5:28:02 pm+Modified By: the developer formerly known as Christian Nonis at <[email protected]>+-----+"""++import logging+import os+import time+from typing import Callable++logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")+logger = logging.getLogger(__name__)+++def log(*args, **kwargs):+ if os.getenv("DEBUG") == "true":+ message = " ".join(str(arg) for arg in args)+ if kwargs:+ message += " " + " ".join(f"{k}={v}" for k, v in kwargs.items())+ logger.info(message)+++def logt(fn: Callable, context: str = "", *args, **kwargs):+ st = time.time()+ result = fn(*args, **kwargs)+ et = time.time()+ if os.getenv("DEBUG") == "true":+ logger.info(f"[{fn.__name__} -> {et-st}s] {context}")+ return result