昨天我先把 Memory 的骨架定義好,今天則輪到最核心的「Brain」。
這一層是 Controller 的角色:它不自己思考、不自己記錄,而是負責把 Memory 與 Thinking Net 黏合起來,驅動整個 Agent 的有限狀態機(FSM)。
換句話說:
Memory 是資料真相,State 是行為模組,Brain 則是整個 orchestrator。
class Brain:
def __init__(
self,
thinking_net: str | dict[Enum, State],
memory_struct: str | Memory,
tools: list[BaseTool],
) -> None:
# 初始化 net 與 memory
self.net = self._create_net(thinking_net)
self.memory = self._create_memory(memory_struct, tools)
# 初始狀態:直接取 net 的第一個 state
self.state = list(self.net.values())[0]
self.loop_limit = 10
async def _step(self) -> AsyncIterator[str]:
# 進入狀態
self.state.on_enter(self.memory)
# 執行狀態,並串流輸出
async for chunk in self.state.run(self.memory):
yield chunk
# 離開狀態
self.state.on_exit(self.memory)
# 決定下一個狀態
next_state_enum = await self.state.next_state(self.memory)
self.state = self.net[next_state_enum]
async def answer(self, task: str) -> AsyncIterator[str]:
# 先把目標設定到 memory
await self.memory.set_goal(task)
while not self.memory.done and self.loop_limit > 0:
async for chunk in self._step():
yield chunk
self.loop_limit -= 1
def _create_net(self, thinking_net: str | dict[Enum, State]) -> dict[Enum, State]:
if isinstance(thinking_net, str):
if thinking_net not in NET_MAP:
raise ValueError(f"Unknown thinking net: {thinking_net}")
return NET_MAP[thinking_net]
return thinking_net
def _create_memory(self, memory_struct: str | Memory, tools: list[BaseTool]) -> Memory:
if isinstance(memory_struct, str):
if memory_struct not in MEM_MAP:
raise ValueError(f"Unknown memory struct: {memory_struct}")
return MEM_MAP[memory_struct](tools=tools)
return memory_struct
Thinking Net
"react"
),由 NET_MAP
載入預設的 FSM 定義。dict[Enum, State]
,完全自定義狀態與轉移。Memory
"messages"
)對應到 MEM_MAP
,或直接丟進現成的 Memory 實例。TreeMemory
搭配 ReflexionNet
。State 生命週期
_step()
都會呼叫 on_enter
→ run
(串流輸出)→ on_exit
。next_state()
決定轉移。Loop Limit
10
,避免意外無窮迴圈。例如:
brain = Brain(
thinking_net="react", # ReAct FSM
memory_struct="messages", # 最暴力的訊息列表 Memory
tools=[SearchTool(), CalcTool()]
)
async for chunk in brain.answer("幫我查台北今天天氣並算出明天帶傘機率"):
print(chunk)
這樣就能看到:Reasoning → Action → Reasoning → Answering 的完整過程。
到這裡,Agent-brain 的最小骨架已經有了:
明天目標:把 BaseTool
完成,補齊 execute()
和序列化邏輯。
有了工具,agent-brain 才能真正「動起來」,跑完整個 ReAct 流程。