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
refactor agent prompt configuration with strategy registries
Cursor Agentb1b4036f0785
diff --git a/src/core/agents/architect_agent.py b/src/core/agents/architect_agent.pyindex 0b09fe2..1e3276c 100644--- a/src/core/agents/architect_agent.py+++ b/src/core/agents/architect_agent.py@@ -8,7 +8,7 @@ Modified By: Christian Nonis <[email protected]>-----"""-from typing import Dict, List, Literal, Optional, Tuple+from typing import Callable, Dict, List, Literal, Optional, Tuplefrom langchain.tools import BaseToolfrom pydantic import BaseModelimport os@@ -72,6 +72,21 @@ class ArchitectAgent:"""Architect agent."""+ _SYSTEM_PROMPT_BUILDERS: dict[tuple[str, str], Callable[[str], str]] = {+ ("single", "granular"): lambda extra: prompt_registry.get(+ "ARCHITECT_AGENT_SYSTEM_PROMPT", ARCHITECT_AGENT_SYSTEM_PROMPT+ ).format(extra_system_prompt=extra),+ ("single", "coarse"): lambda extra: prompt_registry.get(+ "ARCHITECT_AGENT_SYSTEM_PROMPT", ARCHITECT_AGENT_SYSTEM_PROMPT+ ).format(extra_system_prompt=extra),+ ("tooler", "granular"): lambda extra: prompt_registry.get(+ "ARCHITECT_AGENT_TOOLER_SYSTEM_PROMPT", ARCHITECT_AGENT_TOOLER_SYSTEM_PROMPT+ ).format(extra_system_prompt=extra),+ ("tooler", "coarse"): lambda extra: prompt_registry.get(+ "ARCHITECT_AGENT_TOOLER_COARSE_SYSTEM_PROMPT",+ ARCHITECT_AGENT_TOOLER_COARSE_SYSTEM_PROMPT,+ ).format(extra_system_prompt=extra),+ }entities: Dict[str, ScoutEntity]@@ -218,34 +233,7 @@ class ArchitectAgent:Side effects:Creates an agent via create_agent and assigns it to self.agent."""-- system_prompt = ""-- if type_ == "single":- system_prompt = prompt_registry.get(- "ARCHITECT_AGENT_SYSTEM_PROMPT", ARCHITECT_AGENT_SYSTEM_PROMPT- ).format(- extra_system_prompt=(extra_system_prompt if extra_system_prompt else "")- )- elif type_ == "tooler":- if mode == "granular":- system_prompt = prompt_registry.get(- "ARCHITECT_AGENT_TOOLER_SYSTEM_PROMPT", ARCHITECT_AGENT_TOOLER_SYSTEM_PROMPT- ).format(- extra_system_prompt=(- extra_system_prompt if extra_system_prompt else ""- )- )- elif mode == "coarse":- system_prompt = prompt_registry.get(- "ARCHITECT_AGENT_TOOLER_COARSE_SYSTEM_PROMPT", ARCHITECT_AGENT_TOOLER_COARSE_SYSTEM_PROMPT- ).format(- extra_system_prompt=(- extra_system_prompt if extra_system_prompt else ""- )- )- else:- raise ValueError(f"Invalid mode for architect agent: {mode}")+ system_prompt = self._resolve_system_prompt(type_, mode, extra_system_prompt)tools = ((tools@@ -275,6 +263,22 @@ class ArchitectAgent:use_custom_backend=(mode == "coarse"),)+ def _resolve_system_prompt(+ self,+ type_: Literal["single", "tooler"],+ mode: Literal["granular", "coarse"],+ extra_system_prompt: Optional[dict] = None,+ ) -> str:+ resolved_extra_system_prompt = extra_system_prompt if extra_system_prompt else ""+ if mode not in ("granular", "coarse"):+ raise ValueError(f"Invalid mode for architect agent: {mode}")+ if type_ not in ("single", "tooler"):+ raise ValueError(f"Invalid type for architect agent: {type_}")+ key = (type_, mode)+ if key not in self._SYSTEM_PROMPT_BUILDERS:+ raise ValueError(f"Unsupported architect configuration: type={type_}, mode={mode}")+ return self._SYSTEM_PROMPT_BUILDERS[key](resolved_extra_system_prompt)+def run(self,text: str,diff --git a/src/core/agents/janitor_agent.py b/src/core/agents/janitor_agent.pyindex 1db09dc..11f2cde 100644--- a/src/core/agents/janitor_agent.py+++ b/src/core/agents/janitor_agent.py@@ -11,7 +11,7 @@ Modified By: Christian Nonis <[email protected]>import jsonimport osfrom functools import reduce-from typing import List, Literal, Optional, Tuple, Union+from typing import Callable, List, Literal, Optional, Tuple, Unionfrom langchain.agents.structured_output import ToolStrategyfrom langchain.tools import BaseToolfrom pydantic import BaseModel@@ -49,7 +49,6 @@ from src.core.agents.tools.janitor_agent import (JanitorAgentGetSchemaTool,JanitorAgentSearchEntitiesTool,JanitorAgentExecuteGraphReadOperationTool,- JanitorAgentExecuteGraphOperationTool,)from src.core.agents.tools.janitor_agent.JanitorAgentSearchRelationshipTool import (JanitorAgentSearchRelationshipsTool,@@ -77,6 +76,18 @@ class JanitorAgent:"""Janitor agent."""+ _SYSTEM_PROMPT_BUILDERS: dict[str, Callable[[str], str]] = {+ "janitor": lambda extra: prompt_registry.get(+ "JANITOR_AGENT_SYSTEM_PROMPT", JANITOR_AGENT_SYSTEM_PROMPT+ ).format(extra_system_prompt=extra),+ "graph-janitor": lambda extra: prompt_registry.get(+ "JANITOR_AGENT_GRAPH_NORMALIZATOR_SYSTEM_PROMPT",+ JANITOR_AGENT_GRAPH_NORMALIZATOR_SYSTEM_PROMPT,+ ).format(extra_system_prompt=extra),+ "atomic-janitor": lambda extra: prompt_registry.get(+ "ATOMIC_JANITOR_AGENT_SYSTEM_PROMPT", ATOMIC_JANITOR_AGENT_SYSTEM_PROMPT+ ).format(extra_system_prompt=extra),+ }def __init__(self,@@ -153,7 +164,7 @@ class JanitorAgent:output_schemas: Optional[Union[BaseModel, Tuple[BaseModel, ...]]] = None,extra_system_prompt: Optional[dict] = None,brain_id: str = "default",- type_: str = Literal["janitor", "graph-janitor"],+ type_: Literal["janitor", "graph-janitor", "atomic-janitor"] = "janitor",):"""Configure and instantiate the internal LangChain agent and assign it to `self.agent`.@@ -169,51 +180,11 @@ class JanitorAgent:type_ (str): Agent mode controlling system prompt selection; supported values are "janitor", "graph-janitor", and "atomic-janitor"."""- system_prompt = None- if type_ == "janitor":- system_prompt = prompt_registry.get(- "JANITOR_AGENT_SYSTEM_PROMPT", JANITOR_AGENT_SYSTEM_PROMPT- ).format(- extra_system_prompt=extra_system_prompt if extra_system_prompt else ""- )- elif type_ == "graph-janitor":- system_prompt = prompt_registry.get(- "JANITOR_AGENT_GRAPH_NORMALIZATOR_SYSTEM_PROMPT", JANITOR_AGENT_GRAPH_NORMALIZATOR_SYSTEM_PROMPT- ).format(- extra_system_prompt=extra_system_prompt if extra_system_prompt else "",- )- elif type_ == "atomic-janitor":- system_prompt = prompt_registry.get(- "ATOMIC_JANITOR_AGENT_SYSTEM_PROMPT", ATOMIC_JANITOR_AGENT_SYSTEM_PROMPT- ).format(- extra_system_prompt=extra_system_prompt if extra_system_prompt else ""- )- else:+ resolved_extra_system_prompt = extra_system_prompt if extra_system_prompt else ""+ if type_ not in self._SYSTEM_PROMPT_BUILDERS:raise ValueError(f"Invalid type: {type_}")-- response_format = None- if output_schemas:- if isinstance(output_schemas, tuple):- if len(output_schemas) == 1:- union_schema = output_schemas[0]- elif len(output_schemas) == 2:- union_schema = Union[output_schemas[0], output_schemas[1]]- else:- union_schema = reduce(lambda x, y: Union[x, y], output_schemas)- else:- union_schema = output_schemas- response_format = ToolStrategy(schema=union_schema)- elif output_schema:- if isinstance(output_schema, tuple):- if len(output_schema) == 1:- union_schema = output_schema[0]- elif len(output_schema) == 2:- union_schema = Union[output_schema[0], output_schema[1]]- else:- union_schema = reduce(lambda x, y: Union[x, y], output_schema)- response_format = ToolStrategy(schema=union_schema)- else:- response_format = output_schema+ system_prompt = self._SYSTEM_PROMPT_BUILDERS[type_](resolved_extra_system_prompt)+ response_format = self._resolve_response_format(output_schema, output_schemas)self.agent = runtime_agent_factory.build(model=self.llm_adapter.llm.langchain_model,@@ -224,6 +195,32 @@ class JanitorAgent:architecture=config.agentic_architecture,)+ def _resolve_response_format(+ self,+ output_schema: Optional[Union[BaseModel, Tuple[BaseModel, ...]]],+ output_schemas: Optional[Union[BaseModel, Tuple[BaseModel, ...]]],+ ):+ if output_schemas is not None:+ normalized_schema = self._normalize_schema(output_schemas)+ return ToolStrategy(schema=normalized_schema)+ if output_schema is not None:+ if isinstance(output_schema, tuple):+ normalized_schema = self._normalize_schema(output_schema)+ return ToolStrategy(schema=normalized_schema)+ return output_schema+ return None++ def _normalize_schema(+ self, schema_or_schemas: Union[BaseModel, Tuple[BaseModel, ...]]+ ):+ if not isinstance(schema_or_schemas, tuple):+ return schema_or_schemas+ if len(schema_or_schemas) == 1:+ return schema_or_schemas[0]+ if len(schema_or_schemas) == 2:+ return Union[schema_or_schemas[0], schema_or_schemas[1]]+ return reduce(lambda x, y: Union[x, y], schema_or_schemas)+def _content_only_history(self, messages: Optional[list], keep_last: Optional[int] = None) -> list:diff --git a/src/core/agents/kg_agent.py b/src/core/agents/kg_agent.pyindex 67861e9..d04b3c6 100644--- a/src/core/agents/kg_agent.py+++ b/src/core/agents/kg_agent.py@@ -9,7 +9,7 @@ Modified By: Christian Nonis <[email protected]>"""import os-from typing import Iterable, List, Literal, Optional, Union+from typing import Callable, Iterable, List, Literal, Optional, Unionfrom langchain.tools import BaseToolfrom pydantic import BaseModelfrom concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutError@@ -61,6 +61,16 @@ MAX_RECURSION_LIMIT_GRAPH_CONSOLIDATOR = 50class KGAgent:+ _SYSTEM_PROMPT_BUILDERS: dict[str, Callable[[str], str]] = {+ "normal": lambda extra: prompt_registry.get(+ "KG_AGENT_SYSTEM_PROMPT", KG_AGENT_SYSTEM_PROMPT+ ).format(extra_system_prompt=extra),+ "graph-consolidator": lambda extra: prompt_registry.get(+ "KG_AGENT_GRAPH_CONSOLIDATOR_SYSTEM_PROMPT",+ KG_AGENT_GRAPH_CONSOLIDATOR_SYSTEM_PROMPT,+ ).format(extra_system_prompt=extra),+ }+"""Knowledge Graph Agent. Used to operate with the knowledge graph with new information.Not used for batch updates.@@ -160,7 +170,7 @@ class KGAgent:metadata: dict,tools: Optional[List[BaseTool]] = None,output_schema: Optional[BaseModel] = None,- extra_system_prompt: Optional[dict] = None,+ extra_system_prompt: Optional[str] = None,brain_id: str = "default",):"""@@ -177,19 +187,12 @@ class KGAgent:extra_system_prompt (Optional[dict]): Optional additional content to interpolate into the selected system prompt.brain_id (str): Identifier of the knowledge brain/context to use when creating default tools."""- system_prompt = None- if type_ == "normal":- system_prompt = prompt_registry.get(- "KG_AGENT_SYSTEM_PROMPT", KG_AGENT_SYSTEM_PROMPT- ).format(- extra_system_prompt=extra_system_prompt if extra_system_prompt else ""- )- elif type_ == "graph-consolidator":- system_prompt = prompt_registry.get(- "KG_AGENT_GRAPH_CONSOLIDATOR_SYSTEM_PROMPT", KG_AGENT_GRAPH_CONSOLIDATOR_SYSTEM_PROMPT- ).format(- extra_system_prompt=extra_system_prompt if extra_system_prompt else ""- )+ resolved_extra_system_prompt = extra_system_prompt if extra_system_prompt else ""+ if type_ not in self._SYSTEM_PROMPT_BUILDERS:+ raise ValueError(f"Invalid type: {type_}")+ system_prompt = self._SYSTEM_PROMPT_BUILDERS[type_](+ resolved_extra_system_prompt+ )self.agent = runtime_agent_factory.build(model=self.llm_adapter.llm.langchain_model,diff --git a/src/core/agents/tools/janitor_agent/JanitorAgentExecuteGraphOperationTool.py b/src/core/agents/tools/janitor_agent/JanitorAgentExecuteGraphOperationTool.pyindex 5917e82..41abcb8 100644--- a/src/core/agents/tools/janitor_agent/JanitorAgentExecuteGraphOperationTool.py+++ b/src/core/agents/tools/janitor_agent/JanitorAgentExecuteGraphOperationTool.py@@ -8,67 +8,10 @@ Modified By: the developer formerly known as Christian Nonis at <alch.infoemail@-----"""-from langchain.tools import BaseTool+from src.core.agents.tools.janitor_agent.JanitorAgentExecuteGraphReadOperationTool import (+ JanitorAgentExecuteGraphReadOperationTool,+)-from src.adapters.graph import GraphAdapter--class JanitorAgentExecuteGraphOperationTool(BaseTool):- """- Tool for executing a graph operation.- """-- name: str = "execute_graph_read_operation"-- janitor_agent: object- kg: GraphAdapter- brain_id: str = "default"-- args_schema: dict = {- "type": "object",- "properties": {- "query": {- "type": "string",- "description": "The query to execute on the knowledge graph. Should be a valid graph read only operation depending on the graph database type.",- },- },- "required": ["query"],- }-- def __init__(- self,- janitor_agent,- kg: GraphAdapter,- database_desc: str,- brain_id: str = "default",- ):- description: str = (- "Tool for executing read only operations on the knowledge graph. "- "Use this tool to read information from the knowledge graph. "- "The query should be a valid graph read only operation depending on the graph database type."- "The query should be a valid JSON object with a 'query' key. "- "{database_desc}."- "If you get an error, try again after fixing your query and don't give up. "- "If you get a result, return the result as a JSON object."- )- formatted_description = description.format(database_desc=database_desc)- super().__init__(- janitor_agent=janitor_agent,- kg=kg,- description=formatted_description,- brain_id=brain_id,- )-- def _run(self, *args, **kwargs) -> str:- _query = ""- if len(args) > 0:- _query = args[0]- else:- _query = kwargs.get("query", "")-- if len(_query) == 0:- return "No query provided in the arguments or kwargs"-- response = self.kg.execute_operation(_query, brain_id=self.brain_id)-- return response+class JanitorAgentExecuteGraphOperationTool(JanitorAgentExecuteGraphReadOperationTool):+ passdiff --git a/tests/test_agent_configuration_patterns.py b/tests/test_agent_configuration_patterns.pynew file mode 100644index 0000000..2bea2ac--- /dev/null+++ b/tests/test_agent_configuration_patterns.py@@ -0,0 +1,201 @@+import os+import unittest+from unittest.mock import patch++from pydantic import BaseModel+++ENV_DEFAULTS = {+ "BRAINPAT_TOKEN": "test-token",+ "MODELS_MODE": "local",+ "EMBEDDINGS_LOCAL_MODEL": "local-model",+ "EMBEDDINGS_SMALL_MODEL": "small-model",+ "EMBEDDING_NODES_DIMENSION": "3",+ "EMBEDDING_TRIPLETS_DIMENSION": "3",+ "EMBEDDING_OBSERVATIONS_DIMENSION": "3",+ "EMBEDDING_DATA_DIMENSION": "3",+ "EMBEDDING_RELATIONSHIPS_DIMENSION": "3",+ "REDIS_HOST": "localhost",+ "REDIS_PORT": "6379",+ "NEO4J_HOST": "localhost",+ "NEO4J_PORT": "7687",+ "NEO4J_USERNAME": "neo4j",+ "NEO4J_PASSWORD": "password",+ "MILVUS_HOST": "localhost",+ "MILVUS_PORT": "19530",+ "MONGO_CONNECTION_STRING": "mongodb://localhost:27017",+ "CELERY_WORKER_CONCURRENCY": "1",+ "OLLAMA_HOST": "localhost",+ "OLLAMA_PORT": "11434",+ "OLLAMA_LLM_SMALL_MODEL": "small",+ "OLLAMA_LLM_LARGE_MODEL": "large",+}+for key, value in ENV_DEFAULTS.items():+ os.environ.setdefault(key, value)++from src.core.agents.architect_agent import ArchitectAgent+from src.core.agents.janitor_agent import JanitorAgent+from src.core.agents.kg_agent import KGAgent+from src.core.agents.tools.janitor_agent import (+ JanitorAgentExecuteGraphOperationTool,+ JanitorAgentExecuteGraphReadOperationTool,+)+++class _DummyLLM:+ langchain_model = object()+++class _DummyLLMAdapter:+ llm = _DummyLLM()+++class _SchemaA(BaseModel):+ value_a: str+++class _SchemaB(BaseModel):+ value_b: int+++class _FakeToolStrategy:+ def __init__(self, schema):+ self.schema = schema+++class KGAgentPromptStrategyTests(unittest.TestCase):+ def _build_agent(self):+ return KGAgent(+ llm_adapter=_DummyLLMAdapter(),+ cache_adapter=object(),+ kg=object(),+ vector_store=object(),+ embeddings=object(),+ database_desc="db",+ )++ @patch("src.core.agents.kg_agent.runtime_agent_factory.build")+ @patch("src.core.agents.kg_agent.prompt_registry.get")+ def test_get_agent_uses_registry_for_normal_prompt(self, get_prompt, build_agent):+ get_prompt.return_value = "normal::{extra_system_prompt}"+ kg_agent = self._build_agent()++ kg_agent._get_agent(+ type_="normal",+ identification_params={},+ metadata={},+ tools=[object()],+ extra_system_prompt="extra",+ )++ self.assertEqual(build_agent.call_args.kwargs["system_prompt"], "normal::extra")++ @patch("src.core.agents.kg_agent.runtime_agent_factory.build")+ @patch("src.core.agents.kg_agent.prompt_registry.get")+ def test_get_agent_uses_registry_for_graph_consolidator_prompt(+ self, get_prompt, build_agent+ ):+ get_prompt.return_value = "graph::{extra_system_prompt}"+ kg_agent = self._build_agent()++ kg_agent._get_agent(+ type_="graph-consolidator",+ identification_params={},+ metadata={},+ tools=[object()],+ extra_system_prompt="extra",+ )++ self.assertEqual(build_agent.call_args.kwargs["system_prompt"], "graph::extra")++ def test_get_agent_rejects_invalid_type(self):+ kg_agent = self._build_agent()+ with self.assertRaises(ValueError):+ kg_agent._get_agent(+ type_="invalid", # type: ignore[arg-type]+ identification_params={},+ metadata={},+ tools=[object()],+ )+++class JanitorAgentSchemaStrategyTests(unittest.TestCase):+ def _build_agent(self):+ return JanitorAgent(+ llm_adapter=_DummyLLMAdapter(),+ kg=object(),+ vector_store=object(),+ embeddings=object(),+ database_desc="db",+ )++ @patch("src.core.agents.janitor_agent.ToolStrategy", _FakeToolStrategy)+ def test_resolve_response_format_wraps_output_schemas(self):+ janitor_agent = self._build_agent()+ response_format = janitor_agent._resolve_response_format(+ output_schema=None, output_schemas=(_SchemaA, _SchemaB)+ )+ self.assertIsInstance(response_format, _FakeToolStrategy)+ self.assertIn("_SchemaA", str(response_format.schema))+ self.assertIn("_SchemaB", str(response_format.schema))++ @patch("src.core.agents.janitor_agent.ToolStrategy", _FakeToolStrategy)+ def test_resolve_response_format_wraps_tuple_output_schema(self):+ janitor_agent = self._build_agent()+ response_format = janitor_agent._resolve_response_format(+ output_schema=(_SchemaA, _SchemaB), output_schemas=None+ )+ self.assertIsInstance(response_format, _FakeToolStrategy)+ self.assertIn("_SchemaA", str(response_format.schema))+ self.assertIn("_SchemaB", str(response_format.schema))++ def test_resolve_response_format_keeps_single_schema_unwrapped(self):+ janitor_agent = self._build_agent()+ response_format = janitor_agent._resolve_response_format(+ output_schema=_SchemaA, output_schemas=None+ )+ self.assertIs(response_format, _SchemaA)++ def test_get_agent_rejects_invalid_type(self):+ janitor_agent = self._build_agent()+ with self.assertRaises(ValueError):+ janitor_agent._get_agent(type_="invalid") # type: ignore[arg-type]+++class ArchitectAgentPromptStrategyTests(unittest.TestCase):+ @patch("src.core.agents.architect_agent.prompt_registry.get")+ def test_resolve_system_prompt_uses_strategy_registry(self, get_prompt):+ get_prompt.return_value = "architect::{extra_system_prompt}"+ architect_agent = ArchitectAgent.__new__(ArchitectAgent)+ resolved = architect_agent._resolve_system_prompt(+ type_="tooler", mode="coarse", extra_system_prompt="extra"+ )+ self.assertEqual(resolved, "architect::extra")++ def test_resolve_system_prompt_rejects_invalid_mode(self):+ architect_agent = ArchitectAgent.__new__(ArchitectAgent)+ with self.assertRaises(ValueError):+ architect_agent._resolve_system_prompt(+ type_="tooler", mode="invalid" # type: ignore[arg-type]+ )++ def test_resolve_system_prompt_rejects_invalid_type(self):+ architect_agent = ArchitectAgent.__new__(ArchitectAgent)+ with self.assertRaises(ValueError):+ architect_agent._resolve_system_prompt(+ type_="invalid", mode="granular" # type: ignore[arg-type]+ )+++class JanitorToolReuseTests(unittest.TestCase):+ def test_graph_operation_tool_reuses_read_operation_tool(self):+ self.assertTrue(+ issubclass(+ JanitorAgentExecuteGraphOperationTool,+ JanitorAgentExecuteGraphReadOperationTool,+ )+ )+++if __name__ == "__main__":+ unittest.main()