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
fix(brain_id): mismatch between middleware and route args
Christian1b8c5ca022ea
diff --git a/src/services/api/dependencies.py b/src/services/api/dependencies.pynew file mode 100644index 0000000..d2c9ee3--- /dev/null+++ b/src/services/api/dependencies.py@@ -0,0 +1,5 @@+from fastapi import Request+++def get_brain_id(request: Request) -> str:+ return request.state.brain_iddiff --git a/src/services/api/middlewares/brains.py b/src/services/api/middlewares/brains.pyindex 6edbaf2..0bd29f1 100644--- a/src/services/api/middlewares/brains.py+++ b/src/services/api/middlewares/brains.py@@ -3,7 +3,7 @@ File: /brains.pyCreated Date: Monday December 1st 2025Author: Christian Nonis <[email protected]>------Last Modified: Monday December 1st 2025 9:06:30 pm+Last Modified: Wednesday March 4th 2026 9:35:41 pmModified By: Christian Nonis <[email protected]>-----"""@@ -105,7 +105,7 @@ class BrainMiddleware(BaseHTTPMiddleware):if brain_id and not brain_id.isalnum():return JSONResponse(status_code=status.HTTP_400_BAD_REQUEST,- content={"detail": "Brain ID must be alphanumeric."},+ content={"detail": "Brain ID must be alphanumeric.", "value": brain_id},)try:diff --git a/src/services/api/routes/ingest.py b/src/services/api/routes/ingest.pyindex 0e81da7..2f30879 100644--- a/src/services/api/routes/ingest.py+++ b/src/services/api/routes/ingest.py@@ -15,11 +15,12 @@ from uuid import uuid4import requestsfrom celery.exceptions import OperationalError-from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile+from fastapi import APIRouter, Depends, File, HTTPException, Request, UploadFilefrom starlette.responses import JSONResponsefrom typing_extensions import Annotatedfrom src.config import config+from src.services.api.dependencies import get_brain_idfrom src.services.api.constants.requests import (IngestionRequestBody,IngestionStructuredRequestBody,@@ -38,10 +39,16 @@ ingest_router = APIRouter(prefix="/ingest", tags=["ingest"])@ingest_router.post(path="/")-async def ingest_data(data: IngestionRequestBody, request: Request):+async def ingest_data(+ data: IngestionRequestBody,+ request: Request,+ brain_id: str = Depends(get_brain_id),+):"""Ingest data to the processing pipeline and save to the memory."""+ data.brain_id = brain_id+ print("[Ingest] received task for brain: ", brain_id)flow_task_identifier = None@@ -75,10 +82,15 @@ async def ingest_data(data: IngestionRequestBody, request: Request):@ingest_router.post(path="/structured")-async def ingest_structured_data(data: IngestionStructuredRequestBody):+async def ingest_structured_data(+ data: IngestionStructuredRequestBody,+ brain_id: str = Depends(get_brain_id),+):"""Ingest structured data to the processing pipeline and save to the memory."""+ data.brain_id = brain_id+ print("[IngestStructured] received task for brain: ", brain_id)task = Nonefor attempt in range(MAX_TASK_RETRIES):try:@@ -105,11 +117,12 @@ async def ingest_structured_data(data: IngestionStructuredRequestBody):async def ingest_file(request: Request,file: Annotated[UploadFile, File()],- brain_id: str = Form(default="default"),+ brain_id: str = Depends(get_brain_id),):"""Ingest a file into the processing pipeline and save to the memory."""+ print("[IngestFile] received task for brain: ", brain_id)task = str(uuid4())@@ -143,9 +156,16 @@ async def ingest_file("task_id": task,}else:- forwarded_proto = request.headers.get("X-Forwarded-Proto") or request.url.scheme- forwarded_host = request.headers.get("X-Forwarded-Host") or request.headers.get("Host") or request.base_url.netloc+ forwarded_proto = (+ request.headers.get("X-Forwarded-Proto") or request.url.scheme+ )+ forwarded_host = (+ request.headers.get("X-Forwarded-Host")+ or request.headers.get("Host")+ or request.base_url.netloc+ )app_host = f"{forwarded_proto}://{forwarded_host}".rstrip("/")+ print(f"app_host: {app_host}")cache_adapter.set(key=f"task:{task}",value=json.dumps({"status": "queued", "task_id": task}),diff --git a/src/services/api/routes/meta.py b/src/services/api/routes/meta.pyindex ed13c3c..96c4162 100644--- a/src/services/api/routes/meta.py+++ b/src/services/api/routes/meta.py@@ -8,8 +8,9 @@ Modified By: the developer formerly known as Christian Nonis at <alch.infoemail@-----"""-from fastapi import APIRouter+from fastapi import APIRouter, Depends+from src.services.api.dependencies import get_brain_idfrom src.services.api.controllers.meta import (get_entities_labels as get_entities_labels_controller,get_relationships_properties as get_relationships_properties_controller,@@ -20,7 +21,7 @@ meta_router = APIRouter(prefix="/meta", tags=["meta"])@meta_router.get(path="/relationships-properties")async def get_relationships_properties(- brain_id: str = "default",+ brain_id: str = Depends(get_brain_id),):"""Retrieve all unique relationship types present in the graph for the specified brain.@@ -35,7 +36,7 @@ async def get_relationships_properties(@meta_router.get(path="/entity-labels")async def get_entities_labels(- brain_id: str = "default",+ brain_id: str = Depends(get_brain_id),):"""Retrieve all unique node labels present in the graph.@@ -50,7 +51,7 @@ async def get_entities_labels(@meta_router.get(path="/entity-properties")async def get_entity_properties(- brain_id: str = "default",+ brain_id: str = Depends(get_brain_id),):"""Retrieve all unique property keys used by entities in the specified brain/graph.diff --git a/src/services/api/routes/model.py b/src/services/api/routes/model.pyindex d2bf2fb..c676509 100644--- a/src/services/api/routes/model.py+++ b/src/services/api/routes/model.py@@ -8,8 +8,9 @@ Modified By: the developer formerly known as Christian Nonis at <alch.infoemail@-----"""-from fastapi import APIRouter+from fastapi import APIRouter, Depends+from src.services.api.dependencies import get_brain_idfrom src.services.api.constants.requests import (AddEntityRequest,UpdateEntityRequest,@@ -27,13 +28,17 @@ model_router = APIRouter(prefix="/model", tags=["model"])@model_router.post(path="/entity")-async def add_entity(request: AddEntityRequest):+async def add_entity(+ request: AddEntityRequest,+ brain_id: str = Depends(get_brain_id),+):"""Create a new entity (node) in the knowledge graph.Returns:Response payload containing details of the created node."""+ request.brain_id = brain_idproperties = request.properties or {}return await add_nodes_controller(@@ -50,12 +55,16 @@ async def add_entity(request: AddEntityRequest):@model_router.put(path="/entity")-async def update_entity(request: UpdateEntityRequest):+async def update_entity(+ request: UpdateEntityRequest,+ brain_id: str = Depends(get_brain_id),+):"""Update an entity (node) in the graph.@returns The controller's response containing the updated node representation or an operation result."""+ request.brain_id = brain_idreturn await update_node_controller(uuid=request.uuid,brain_id=request.brain_id,@@ -68,13 +77,17 @@ async def update_entity(request: UpdateEntityRequest):@model_router.post(path="/relationship")-async def add_relationship(request: AddRelationshipRequest):+async def add_relationship(+ request: AddRelationshipRequest,+ brain_id: str = Depends(get_brain_id),+):"""Create a relationship linking two nodes in the graph.Returns:relationship (dict): Representation of the created relationship."""+ request.brain_id = brain_idreturn await add_relationship_controller(subject_uuid=request.subject_uuid,predicate_name=request.predicate_name,@@ -85,7 +98,10 @@ async def add_relationship(request: AddRelationshipRequest):@model_router.put(path="/relationship")-async def update_relationship(request: UpdateRelationshipRequest):+async def update_relationship(+ request: UpdateRelationshipRequest,+ brain_id: str = Depends(get_brain_id),+):"""Update properties of an existing relationship.@@ -94,6 +110,7 @@ async def update_relationship(request: UpdateRelationshipRequest):Returns:The updated relationship representation or a result object describing the outcome of the update."""+ request.brain_id = brain_idreturn await update_relationship_controller(uuid=request.uuid,brain_id=request.brain_id,diff --git a/src/services/api/routes/retrieve.py b/src/services/api/routes/retrieve.pyindex 6fb7276..afd9172 100644--- a/src/services/api/routes/retrieve.py+++ b/src/services/api/routes/retrieve.py@@ -9,8 +9,9 @@ Modified By: Christian Nonis <[email protected]>"""from typing import List, Literal, Optional-from fastapi import APIRouter, Body, Query+from fastapi import APIRouter, Body, Depends, Queryfrom fastapi.responses import JSONResponse+from src.services.api.dependencies import get_brain_idfrom src.services.api.constants.requests import (GetContextRequestBody,GetContextResponse,@@ -64,7 +65,7 @@ async def retrieve(...,description="The entities to prioritize in the relationships, separated by commas.",),- brain_id: str = "default",+ brain_id: str = Depends(get_brain_id),):"""Retrieve data from the knowledge graph and data store.@@ -82,7 +83,7 @@ async def get_neighbors(None,description="The description of what in the neighbors should share with the target.",),- brain_id: str = "default",+ brain_id: str = Depends(get_brain_id),):"""Get the neighbors of an entity.@@ -97,10 +98,12 @@ async def get_neighbors()async def get_neighbors_with_identification_params(request: RetrieveNeighborsWithIdentificationParamsRequestBody,+ brain_id: str = Depends(get_brain_id),):"""Get the neighbors of an entity."""+ request.brain_id = brain_idreturn await retrieve_neighbors_controller(identification_params=request.identification_params,limit=request.limit,@@ -134,7 +137,10 @@ async def get_neighbors_ai_mode(@retrieve_router.post("/context")-async def get_context(request: GetContextRequestBody) -> GetContextResponse:+async def get_context(+ request: GetContextRequestBody,+ brain_id: str = Depends(get_brain_id),+) -> GetContextResponse:"""Handle an HTTP request to retrieve an entity's contextual information.@@ -146,7 +152,7 @@ async def get_context(request: GetContextRequestBody) -> GetContextResponse:Returns:GetContextResponse: Response containing the context information."""-+ request.brain_id = brain_idreturn await retrieve_get_context_controller(request)@@ -159,7 +165,7 @@ async def get_relationships(to_node_labels: Optional[str] = None,query_text: Optional[str] = None,query_search_target: Optional[str] = "all",- brain_id: str = "default",+ brain_id: str = Depends(get_brain_id),):"""Retrieve relationships filtered by types, node labels, and query criteria.@@ -201,7 +207,7 @@ async def get_entities(skip: int = 0,node_labels: Optional[str] = None,query_text: Optional[str] = None,- brain_id: str = "default",+ brain_id: str = Depends(get_brain_id),):"""Retrieve entities matching optional label and text filters with pagination.@@ -223,7 +229,7 @@ async def get_entities(@retrieve_router.get(path="/structured-data/types")async def get_structured_data_types(- brain_id: str = "default",+ brain_id: str = Depends(get_brain_id),):"""Get all unique types from structured data.@@ -234,7 +240,7 @@ async def get_structured_data_types(@retrieve_router.get(path="/structured-data/{id}")async def get_structured_data_by_id(id: str,- brain_id: str = "default",+ brain_id: str = Depends(get_brain_id),):"""Get structured data by ID.@@ -248,7 +254,7 @@ async def get_structured_data_list(skip: int = 0,types: Optional[str] = None,query_text: Optional[str] = None,- brain_id: str = "default",+ brain_id: str = Depends(get_brain_id),):"""Get a list of structured data.@@ -262,7 +268,7 @@ async def get_structured_data_list(@retrieve_router.get(path="/text-chunks")async def get_text_chunks(- brain_id: str = "default",+ brain_id: str = Depends(get_brain_id),limit: int = 10,skip: int = 0,query_text: Optional[str] = None,@@ -283,7 +289,7 @@ async def get_text_chunks(@retrieve_router.get(path="/observations/labels")async def get_observation_labels(- brain_id: str = "default",+ brain_id: str = Depends(get_brain_id),):"""Get all unique labels from observations.@@ -294,7 +300,7 @@ async def get_observation_labels(@retrieve_router.get(path="/observations/{id}")async def get_observation_by_id(id: str,- brain_id: str = "default",+ brain_id: str = Depends(get_brain_id),):"""Get observation by ID.@@ -309,7 +315,7 @@ async def get_observations_list(resource_id: Optional[str] = None,labels: Optional[str] = None,query_text: Optional[str] = None,- brain_id: str = "default",+ brain_id: str = Depends(get_brain_id),):"""Retrieve a list of observations filtered by the provided parameters.@@ -335,7 +341,7 @@ async def get_observations_list(@retrieve_router.get(path="/changelogs/types")async def get_changelog_types(- brain_id: str = "default",+ brain_id: str = Depends(get_brain_id),):"""Retrieve all unique changelog types for the specified brain.@@ -352,7 +358,7 @@ async def get_changelog_types(@retrieve_router.get(path="/changelogs/{id}")async def get_changelog_by_id(id: str,- brain_id: str = "default",+ brain_id: str = Depends(get_brain_id),):"""Retrieve a changelog entry by its unique identifier.@@ -373,7 +379,7 @@ async def get_changelogs_list(skip: int = 0,types: Optional[str] = None,query_text: Optional[str] = None,- brain_id: str = "default",+ brain_id: str = Depends(get_brain_id),):"""Retrieve a paginated list of changelogs.@@ -397,7 +403,7 @@ async def get_hops(query: str,degrees: Literal[2] = 2,flattened: bool = True,- brain_id: str = "default",+ brain_id: str = Depends(get_brain_id),): # noqa: F821"""Compute graph hops for the given query.@@ -419,7 +425,7 @@ async def get_entity_info(target: str,query: str,max_depth: int = 3,- brain_id: str = "default",+ brain_id: str = Depends(get_brain_id),):"""Retrieve detailed information for an entity identified by the given target and query.@@ -440,7 +446,7 @@ async def get_entity_info(async def get_entity_context(target: str,context_depth: int = 3,- brain_id: str = "default",+ brain_id: str = Depends(get_brain_id),):"""Retrieve contextual information for an entity identified by `target`.@@ -463,7 +469,7 @@ async def get_entity_synergies(do: bool = False,pa: bool = False,ppa: bool = False,- brain_id: str = "default",+ brain_id: str = Depends(get_brain_id),):"""Retrieve synergies for a specified entity.@@ -488,7 +494,7 @@ async def get_entity_synergies(async def get_entity_status(target: str,types: Optional[List[str]] = [],- brain_id: str = "default",+ brain_id: str = Depends(get_brain_id),):"""Retrieve status information for a specified entity.diff --git a/src/services/api/routes/tasks.py b/src/services/api/routes/tasks.pyindex 66e9a58..7745b6f 100644--- a/src/services/api/routes/tasks.py+++ b/src/services/api/routes/tasks.py@@ -10,14 +10,15 @@ Modified By: the developer formerly known as Christian Nonis at <alch.infoemail@import jsonfrom src.utils.logging import log-from fastapi import APIRouter+from fastapi import APIRouter, Depends+from src.services.api.dependencies import get_brain_idfrom src.services.kg_agent.main import cache_adaptertasks_router = APIRouter(prefix="/tasks", tags=["tasks"])@tasks_router.get("/")-async def get_tasks(brain_id: str = "default"):+async def get_tasks(brain_id: str = Depends(get_brain_id)):try:task_keys = cache_adapter.get_task_keys(brain_id)results = []@@ -44,7 +45,7 @@ async def get_tasks(brain_id: str = "default"):@tasks_router.get("/{task_id}")-async def get_task(task_id: str, brain_id: str = "default"):+async def get_task(task_id: str, brain_id: str = Depends(get_brain_id)):"""Get the result of a task by its ID."""