LangGraph 如何實作 ReAct Workflow
ReAct agent 最早在 2023 年論文 ReACT: Synergizing Reasoning and Acting in Language Models 中提出,是一種結合「推理(Reasoning)」與「行動(Acting)」框架的 AI agent,能將 chain of thought(CoT)推理與外部工具使用結合。ReAct 框架提升了 LLM 在複雜任務與決策流程中的能力。
LangGraph 透過 create_react_agent
函數,建立一個能根據 LLM 輸出自動循環調用工具(ReAct agent)的狀態流程圖(StateGraph)。
這篇文章深入了解 LangGraph 原始碼,分析 ReAct agent 實作方法。
Workflow 節點與流程設計
- 以
tool_calling_enabled = len(tool_classes) > 0
判斷是否啟用工具(tools)。 pre_model_hook
:在 agent 執行前預處理狀態,可用於訊息裁剪、摘要、長對話歷史管理等,避免 LLM 輸入過長或不相關。post_model_hook
:在 agent 執行後、進入下一步前處理狀態,可用於人類審核(human-in-the-loop)、安全檢查、驗證、加強 guardrails。
無工具調用 (tool_calling_enabled = False)
flowchart TD
pre_model_hook --> agent --> post_model_hook --> generate_structured_response
有工具調用 (tool_calling_enabled = True)
agent/tools 可多次循環,直到不再需要 tool_calls。
flowchart TD
pre_model_hook --> agent
agent --> post_model_hook
post_model_hook --還有未完成的tools--> tools
post_model_hook --tools已執行完成&指定回傳格式--> generate_structured_response
post_model_hook --tools已執行完成&不指定回傳格式--> END
generate_structured_response --> END
tools --> pre_model_hook
小結
LangGraph 的 create_react_agent
透過 StateGraph 靈活組合 agent、tools、hook、結構化輸出等節點,並可利用條件邊(conditional_edge)實現多輪循環與分支,完整支援 ReAct agent 的推理-行動循環。