LangChain ReAct Agent 核心原理 + 底层实现剖析

📅 2026/7/31 13:23:14
LangChain ReAct Agent 核心原理 + 底层实现剖析
LangChain ReAct Agent 核心原理 底层实现剖析配套TS最小实现一、ReAct 原始论文思想基础ReAct Reason Act推理 行动论文ReAct: Synergizing Reasoning and Acting in Language Models核心发现单纯 Chain-of-Thought(CoT) 只有内部推理模型无法获取外部真实信息容易幻觉单纯工具调用模型跳过分步思考直接输出调用指令复杂任务容易选错工具、参数错误。ReAct范式交替执行【思考Thought】→【行动Action】→【观察Observation】循环标准循环序列Thought: 我现在需要解决什么问题应该调用哪个工具 Action: 工具名称: 参数 Observation: 工具返回的真实结果 循环迭代 Thought: 根据刚刚拿到的结果继续分析…… …… Thought: 我已经拥有全部信息可以直接给出最终答案 Action: Finish和普通Function Calling最大区别OpenAI原生Function Calling模型一次性输出函数调用JSONReAct显式文本链式思考思考过程作为上下文留存适合开源大模型很多开源模型不支持原生function call依靠Prompt实现工具调用。二、LangChain ReAct Agent 核心原理LangChain 提供两套主流ReAct实现ReAct Agent基于Prompt、文本解析通用兼容所有LLMReAct JSON Agent输出结构化JSON更容易解析降低模型输出格式错误核心工作循环LangChain标准流程用户Question → 构建Prompt问题工具描述历史Thought/Action/Observation → LLM生成输出文本 → AgentParser 解析LLM输出 分支1解析出 Action工具调用 → 执行工具得到 Observation → 将 ThoughtActionObservation 追加到对话上下文 → 再次送入LLM开启新一轮循环 分支2解析出 Final Answer结束标记 → 终止循环返回答案 → 最大迭代轮数限制max_iterations防止死循环关键约束所有思考、行动全部通过文本Prompt规约LLM输出自然语言文本不是原生函数调用模型必须严格遵守固定输出格式Parser依靠正则提取Action名称与参数上下文持续累积所有历史轮次的 Thought/Action/Observation模型依赖历史记录持续推理设有终止条件出现最终答案 或者 达到最大循环次数。三、底层核心组件LangChain 源码层级基于langchain.agents.ReActAgent/create_react_agent新版LangChain 0.1 TS langchain/langgraph / langchain/core1. 五大核心组件1Prompt Template最关键ReAct能否跑通Prompt是核心。标准Prompt包含任务指令所有可用Tools名称、功能、入参说明强制输出格式规则规定Thought/Action/Action Input/Observation格式示例Few-shot样例非常重要开源模型缺少样例极易格式错乱极简模板范式Answer the following questions as best you can. You have access to the following tools: {tools} Use the following format: Question: the input question you must answer Thought: you should always think about what to do Action: the action to take, should be one of [{tool_names}] Action Input: the input to the action Observation: the result of the action ... (this Thought/Action/Action Input/Observation can repeat N times) Thought: I now know the final answer Final Answer: the final answer to the original input question Begin! Question: {input} {agent_scratchpad}agent_scratchpad草稿区存放历史每一轮 Thought/Action/Observation是循环记忆载体。2Agent ParserAgentOutputParser作用原始LLM文本输出 → 结构化对象ReAct默认ReActSingleInputOutputParser底层逻辑正则表达式匹配匹配到Final Answer:→ 返回AgentFinish终止匹配到Action:Action Input:→ 返回AgentAction执行工具格式不匹配 → 抛出OutputParserException痛点开源模型经常输出格式跑偏解析失败这是ReAct Agent最常见bug。3AgentExecutor执行器调度核心AgentExecutor是ReAct的调度主循环整个Agent运行时引擎4Tools 工具集合统一接口BaseTool具备 name、description、_run() 执行方法。AgentExecutor根据parser解析出来的tool name路由到对应工具执行。5Stopping Condition 终止策略两类终止条件逻辑终止Parser识别到 Final Answer安全终止max_iterations 最大循环次数防止无限循环调用工具四、两种实现路线区分重要容易混淆路线1传统 ReAct AgentString-based经典// langchain/agentsimport{createReactAgent}fromlangchain/agents;LLM输出自由文本依靠正则解析优点兼容所有LLM无function call能力的开源模型首选缺点输出格式不稳定极易解析失败需要大量few-shot传输载体纯文本字符串。路线2ReAct JSON Agent结构化改进版createJsonAgentPrompt要求模型输出JSON结构不再是自然文本Parser直接解析JSON规避复杂正则降低格式错误率但要求模型具备JSON输出能力。⚠️ 区分OpenAI Tools Agent ≠ ReAct AgentOpenAI Function/Tools Agent依靠模型原生支持函数调用底层是消息结构体不需要手写正则ParserReActPrompt驱动文本解析不依赖模型原生工具调用能力是通用方案。五、ReAct 底层数据流完整链路用户Query ↓ PromptTemplate 拼接指令 工具列表 scratchpad(历史轨迹) ↓ LLM 生成文本响应 ↓ ReAct Parser正则解析输出 ├─ AgentFinish → 输出答案流程结束 └─ AgentAction → 查找对应Tool ↓ Tool.invoke() 执行得到Observation ↓ 将 Thought Action Observation 追加到 scratchpad ↓ 回到开头重新组装Prompt进入下一轮迭代六、ReAct Agent 优缺点底层机制带来的特性优势模型无关不需要LLM原生支持工具调用Llama、Qwen等开源模型均可使用思考过程透明完整Thought文本可观测方便调试Agent决策逻辑灵活可控可以自由修改Prompt调整推理逻辑。原生缺陷格式脆弱大模型一旦输出偏离规定格式Parser直接报错上下文膨胀每一轮scratchpad持续变长token消耗上涨推理速度慢多轮LLM串行调用复杂任务容易出现循环调用工具反复调用同一个工具。七、新版LangChainLangGraph与旧ReAct的关系原生AgentExecutor是命令式while循环硬编码现在官方推荐用LangGraph 重构ReAct逻辑把循环改写为状态图agent → tools → agent图节点跳转优势自定义容错、重试、格式异常修复逻辑持久化Agent状态支持人类介入(Human-in-the-loop)本质依然是 ReAct Thought→Action→Observation 思想只是调度框架升级。八、极简最小可运行实现TypeScript剥离LangChain封装看清底层本质环境依赖npm install typescript ts-node langchain/coreimport{BasePromptTemplate,PromptTemplate}fromlangchain/core/prompts;import{BaseTool}fromlangchain/core/tools;/** * 解析结果类型定义 */typeParseResult|{type:finish;answer:string;}|{type:action;tool:string;input:string;};/** * 简易ReAct输出Parser正则实现对标 ReActSingleInputOutputParser */functionsimpleParse(llmOutput:string):ParseResult{constfinalAnswerRegex/Final Answer:(.*)/s;constactionRegex/Action:(.*?)\nAction Input:(.*)/s;constfinalMatchllmOutput.match(finalAnswerRegex);if(finalMatch){return{type:finish,answer:finalMatch[1].trim(),};}constactionMatchllmOutput.match(actionRegex);if(actionMatch){return{type:action,tool:actionMatch[1].trim(),input:actionMatch[2].trim(),};}thrownewError(输出格式解析失败LLM输出内容${llmOutput});}/** * ReAct 主执行器简易版 AgentExecutor * param question 用户问题 * param llm 兼容 invoke 的LLM实例 * param tools 工具列表 * param maxIter 最大迭代次数 */asyncfunctionreactRun(question:string,llm:{invoke:(prompt:string)Promise{content:string}},tools:BaseTool[],maxIter5):Promisestring{// 草稿区存放所有历史 Thought/Action/Observationletscratchpad;// 工具映射表 name - ToolconsttoolMapnewMapstring,BaseTool();tools.forEach((tool)toolMap.set(tool.name,tool));// ReAct标准PromptconstreactPrompt:BasePromptTemplatePromptTemplate.fromTemplate({tools} Use format strictly: Thought: xxx Action: tool_name Action Input: xxx Observation: result ... Thought: I know answer Final Answer: xxx Question: {input} {agent_scratchpad});for(leti0;imaxIter;i){// 格式化工具描述文本consttoolsTexttools.map((t)${t.name}:${t.description}).join(\n);// 组装完整PromptconstpromptStrawaitreactPrompt.format({input:question,tools:toolsText,agent_scratchpad:scratchpad,});// 调用大模型constllmRespawaitllm.invoke(promptStr);constoutputTextllmResp.contentasstring;try{constparsedsimpleParse(outputText);if(parsed.typefinish){// 识别最终答案直接返回returnparsed.answer;}// 查找工具并执行consttargetTooltoolMap.get(parsed.tool);if(!targetTool){scratchpad\n${outputText}\nObservation: 错误不存在该工具${parsed.tool};continue;}// 执行工具获得观察结果constobservationawaittargetTool.invoke(parsed.input);// 追加本轮记录进入草稿区scratchpad\n${outputText}\nObservation:${observation};}catch(err){// 解析异常把错误写入上下文让模型下一轮修正格式scratchpad\n${outputText}\nObservation: Format error! You must follow required format.;}}return超出最大迭代次数${maxIter}无法完成任务;}// 测试示例 /* // 示例自定义工具 const searchTool new DynamicTool({ name: search, description: 搜索引擎用于查询外部信息, func: async (query: string) { return 模拟搜索结果关于【${query}】的相关资料; }, }); // 使用示例 const answer await reactRun( 查询2026年国内AI发展趋势, llmInstance, [searchTool], 5 ); console.log(answer); */export{reactRun,simpleParse};补充TS版本官方标准ReAct Agent调用示例langchain/agentsimport{createReactAgent}fromlangchain/agents;import{ChatOpenAI}fromlangchain/openai;import{DynamicTool}fromlangchain/core/tools;constllmnewChatOpenAI({model:qwen-turbo,openAIApiKey:xxx,configuration:{baseURL:https://xxx/v1},});// 定义工具consttools[newDynamicTool({name:calculator,description:用于数学计算输入数学表达式,func:async(expr)eval(expr).toString(),}),];// 创建标准ReAct AgentconstagentcreateReactAgent({llm,tools});// AgentExecutor执行constresultawaitagent.invoke({input:35 * 46 等于多少,});console.log(result.output);拓展ReAct JSON Agent TS简易解析器如果切换为JSON模式可替换simpleParse消除正则依赖functionjsonOutputParser(llmOutput:string):ParseResult{constjsonStrllmOutput.replace(/(json)?/g,).trim();constdataJSON.parse(jsonStr);if(data.finalAnswer){return{type:finish,answer:data.finalAnswer};}elseif(data.actiondata.actionInput){return{type:action,tool:data.action,input:data.actionInput,};}thrownewError(JSON结构不符合规范);}