从零构建ReAct Agent:完整代码实现解析

张开发
2026/4/11 5:25:18 15 分钟阅读

分享文章

从零构建ReAct Agent:完整代码实现解析
从零构建ReAct Agent说实话当我第一次看到 ReAct 这个名词的时候还以为是某个新出的前端框架。直到折腾了半天才发现这玩意儿是解决 LLM “一本正经胡说八道” 的神器。作为一个在 LLM 应用开发里踩过无数坑的人我可以负责任地说ReAct 可能是目前最实用的 Agent 设计模式之一。今天就从零开始用 200 行左右的代码带你完整实现一个能思考、能行动、会纠错的 ReAct Agent。为什么需要 ReActLLM 的致命缺陷先说说问题。传统的 LLM 调用方式简单粗暴输入 prompt输出答案。这在写诗、翻译、闲聊这类任务上表现不错。但一旦涉及需要多步推理、实时数据、或工具调用的场景LLM 就原形毕露了。比如我问 GPT-4“苹果公司现在的 CEO 是谁他今年多大”如果知识库截止到训练日期它可能会给我一个过时的答案。更糟的是它可能会幻觉出一个看似合理的错误答案——比如告诉你乔布斯还在世。这就是 LLM 的致命缺陷无法自主获取最新信息也无法在多步推理中自我纠错。ReActReasoning Acting就是为了解决这个问题而生的。ReAct 是什么一个直觉理解ReAct Reasoning推理 Acting行动。核心思想很简单让 LLM 像人类一样思考——先想想再行动观察结果再调整思路。传统方式用户提问 → LLM 直接回答 → 可能答错ReAct 方式用户提问 → LLM 思考我需要什么信息 → 调用工具 → 观察结果 → 继续思考 → 再行动 → 直到得到答案 → 最终回答这个过程形成了一个思考-行动-观察的循环直到 LLM 觉得自己掌握了足够信息才会给出最终答案。ReAct 适合什么场景不是所有任务都需要 ReAct。它最适合以下场景1. 需要实时信息的任务比如查询天气、股价、新闻。这些信息每天都在变LLM 的训练数据无法覆盖。2. 需要多步推理的复杂问题比如找出 2024 年诺贝尔奖得主中年龄最大的那位的主要成就。这需要先查 2024 年诺贝尔奖得主名单然后查每个人的年龄比较找出年龄最大的最后查那位得主的主要成就3. 需要调用外部工具的场景比如计算复杂公式、执行代码、操作数据库。4. 容错率低的任务医疗诊断、法律咨询、金融分析——这些场景下一个错误的答案可能代价高昂。ReAct 的自我纠错机制能大大降低出错概率。完整代码实现一个能用的 ReAct Agent好了理论说够了直接上代码。下面是完整的 ReAct Agent 实现包含核心逻辑、工具定义和运行示例。代码基于 Python不依赖任何 Agent 框架你可以直接复制粘贴使用。importjsonimportrefromtypingimportDict,List,Callable,AnyfromdatetimeimportdatetimeclassReActAgent: ReAct Agent 核心实现 支持多轮思考-行动-观察循环 def__init__(self,llm_client,tools:Dict[str,Callable],max_iterations:int10): 初始化 Agent Args: llm_client: LLM 客户端需要有 generate() 方法 tools: 工具函数字典key 为工具名value 为工具函数 max_iterations: 最大迭代次数防止死循环 self.llmllm_client self.toolstools self.max_iterationsmax_iterationsdefrun(self,query:str)-str: 运行 Agent 处理用户查询 Args: query: 用户问题 Returns: 最终答案 # 初始化思考轨迹trajectory[]# 构建系统提示词告诉 LLM 怎么玩 ReActsystem_promptself._build_system_prompt()# 构建初始用户消息messages[{role:system,content:system_prompt},{role:user,content:fQuestion:{query}\n\nLets solve this step by step.}]# 开始 ReAct 循环foriinrange(self.max_iterations):# 调用 LLM 获取下一步思考responseself.llm.generate(messages)# 解析 LLM 的回复thought,action,action_inputself._parse_response(response)print(f\n Step{i1})print(fThought:{thought})print(fAction:{action})print(fAction Input:{action_input})# 记录思考过程trajectory.append({thought:thought,action:action,action_input:action_input})# 检查是否得到了最终答案ifaction.lower()finish:print(f\n✅ 任务完成)returnaction_input# 执行工具调用ifactioninself.tools:try:observationself.tools[action](action_input)print(fObservation:{observation})exceptExceptionase:observationfError:{str(e)}print(fObservation:{observation})else:observationfError: Unknown action {action}. Available actions:{list(self.tools.keys())}print(fObservation:{observation})# 更新消息历史加入观察和下一步指示messages.append({role:assistant,content:response})messages.append({role:user,content:fObservation:{observation}\n\nContinue with the next thought and action.})# 超过最大迭代次数返回已收集的信息returnfReached maximum iterations. Last thought:{thought}def_build_system_prompt(self)-str: 构建系统提示词定义 ReAct 的输出格式 tool_descriptions\n.join([f-{name}:{func.__doc__orNo description}forname,funcinself.tools.items()])returnfYou are a helpful AI assistant that solves problems step by step. You have access to the following tools:{tool_descriptions}Use the following format: Thought: [your reasoning about what to do next] Action: [the tool name to use, or finish if you have the answer] Action Input: [the input to the tool, or the final answer if finishing] Rules: 1. Always start with Thought: 2. After thought, provide Action: and Action Input: 3. Use finish as the action when you have the complete answer 4. Be concise in your thoughts and actions 5. If a tool returns an error, try a different approach def_parse_response(self,response:str)-tuple: 解析 LLM 的回复提取 thought, action, action_input # 使用正则表达式提取各个部分thought_matchre.search(rThought:\s*(.?)(?\nAction:|$),response,re.DOTALL)action_matchre.search(rAction:\s*(.?)(?\nAction Input:|$),response,re.DOTALL)input_matchre.search(rAction Input:\s*(.?)(?\n|$),response,re.DOTALL)thoughtthought_match.group(1).strip()ifthought_matchelseactionaction_match.group(1).strip()ifaction_matchelsefinishaction_inputinput_match.group(1).strip()ifinput_matchelseresponse.strip()returnthought,action,action_input# 工具函数定义 defsearch_web(query:str)-str: 模拟网络搜索工具 实际使用时可以替换为真实的搜索引擎 API # 这里用简单的字典模拟搜索结果knowledge_base{tim cook age:Tim Cook was born on November 1, 1960, making him 64 years old as of 2024.,apple ceo:Tim Cook has been the CEO of Apple Inc. since August 2011.,python programming:Python is a high-level programming language known for its simplicity.,current date:datetime.now().strftime(%Y-%m-%d),}query_lowerquery.lower()forkey,valueinknowledge_base.items():ifkeyinquery_lower:returnvaluereturnfNo specific information found for:{query}. Try a different search term.defcalculate(expression:str)-str: 计算数学表达式 安全地执行简单的数学计算 try:# 只允许数字和基本运算符防止代码注入allowed_charsset(0123456789-*/.() )ifnotall(cinallowed_charsforcinexpression):returnError: Invalid characters in expressionresulteval(expression)returnstr(result)exceptExceptionase:returnfError:{str(e)}defget_current_time()-str: 获取当前时间 returndatetime.now().strftime(%Y-%m-%d %H:%M:%S)# 模拟 LLM 客户端 classSimpleLLM: 简单的 LLM 客户端模拟 实际使用时替换为 OpenAI、Claude 或其他 LLM API defgenerate(self,messages:List[Dict])-str: 模拟 LLM 生成回复 这里用简单的规则模拟 ReAct 行为 last_messagemessages[-1][content]# 模拟 ReAct 推理过程ifappleinlast_message.lower()andceoinlast_message.lower():ifobservationnotinlast_message.lower():returnThought: I need to find out who is the current CEO of Apple Inc. Action: search_web Action Input: Apple CEO currentelse:returnThought: Now I know Tim Cook is the CEO. Let me find out his age. Action: search_web Action Input: Tim Cook ageeliftim cookinlast_message.lower()and64inlast_message.lower():returnThought: I now have all the information needed. Tim Cook is the CEO of Apple and he is 64 years old (born in 1960). Action: finish Action Input: Tim Cook is the current CEO of Apple Inc. He was born on November 1, 1960, making him 64 years old as of 2024. He has been leading Apple since August 2011, succeeding Steve Jobs.elifcalculateinlast_message.lower()orany(opinlast_messageforopin[,-,*,/]):# 提取数学表达式numbersre.findall(r\d,last_message)iflen(numbers)2:returnfThought: The user wants me to calculate{numbers[0]}*{numbers[1]}. Action: calculate Action Input:{numbers[0]}*{numbers[1]}# 默认回复returnThought: I have gathered enough information to provide an answer. Action: finish Action Input: Based on the available information, I can provide the following answer...# 运行示例 if__name____main__:# 初始化工具tools{search_web:search_web,calculate:calculate,get_current_time:get_current_time,}# 初始化 LLM 客户端实际使用时替换为真实的 API 客户端llmSimpleLLM()# 创建 AgentagentReActAgent(llm,tools,max_iterations5)# 测试用例 1需要搜索的多步问题print(*50)print(测试用例 1查询 Apple CEO 及其年龄)print(*50)query1Who is the current CEO of Apple and how old is he?answer1agent.run(query1)print(f\n最终答案:{answer1})# 测试用例 2数学计算print(\n*50)print(测试用例 2数学计算)print(*50)# 重置 Agent 状态agent2ReActAgent(llm,tools,max_iterations5)query2Calculate 123 * 456answer2agent2.run(query2)print(f\n最终答案:{answer2})代码解析关键设计点这段代码虽然不长但包含了一个完整 ReAct Agent 的核心逻辑。让我解释几个关键设计点1. 严格的输出格式控制通过系统提示词强制 LLM 按照固定格式输出Thought: ... Action: ... Action Input: ...这是 ReAct 工作的基础。如果 LLM 不遵守这个格式整个流程就会崩溃。实际项目中你可能需要使用 few-shot prompting 给出示例对不遵守格式的回复进行重试使用更强大的模型GPT-4、Claude 3 Opus 等2. 轨迹追踪trajectory列表记录了完整的思考-行动-观察链条。这不仅用于调试还可以作为上下文喂给 LLM让它了解之前做了什么保存到数据库用于后续分析展示给用户增加透明度3. 工具解耦工具函数完全独立于 Agent 核心逻辑。你可以轻松添加新工具defmy_new_tool(input:str)-str:工具描述# 实现逻辑returnresult tools[my_new_tool]my_new_tool4. 安全考虑calculate函数里限制了允许的字符防止代码注入攻击。这在生产环境是必须的——你永远不知道 LLM 会输出什么。连接到真实 LLMOpenAI 示例上面的代码用了模拟的 LLM。要连接到真实的 OpenAI API只需要简单的适配器fromopenaiimportOpenAIclassOpenAIAdapter:def__init__(self,api_key:str,model:strgpt-4):self.clientOpenAI(api_keyapi_key)self.modelmodeldefgenerate(self,messages:List[Dict])-str:responseself.client.chat.completions.create(modelself.model,messagesmessages,temperature0.7,max_tokens500)returnresponse.choices[0].message.content# 使用方式llmOpenAIAdapter(api_keyyour-api-key)agentReActAgent(llm,tools)answeragent.run(你的问题)同样的模式也适用于 Claude、Gemini、或其他任何 LLM API。生产环境的改进建议上面的代码是教学用的简化版。实际部署时你还需要考虑1. 错误处理工具调用失败的重试机制LLM 输出格式错误的恢复策略超时处理2. 上下文管理长对话的上下文压缩关键信息的记忆机制多轮对话的状态保持3. 工具增强工具参数的自动校验工具调用的并发执行工具返回结果的后处理4. 可观测性完整的执行日志性能指标收集用户反馈循环写在最后ReAct 并不是什么高深的技术但它的实用价值很高。在这个 LLM 应用爆炸的时代单纯调用 API 已经不够了。用户要的不是生成一段文字而是解决一个实际问题。ReAct 提供了一种结构化的方式让 LLM 从答题者变成问题解决者。我在这篇文章里提供的代码你可以基于它添加更多工具对接你的业务系统接入真实的 LLM API构建更复杂的 Agent 工作流或者直接用于生产环境记得加上错误处理和日志

更多文章