ReActAgent 源码分析

概述 ReActAgent 是 AgentScope Java 的核心推理引擎,位于 agentscope-core 模块。它实现了 ReAct (Reasoning and Acting) 设计模式——在推理(想下一步做什么)和执行(调工具)之间交替循环。 源码位置:agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java(1925 行) 核心依赖 public class ReActAgent extends StructuredOutputCapableAgent { private final Memory memory; // 对话历史(InMemoryMemory) private final String sysPrompt; // 系统提示词 private final Model model; // LLM 模型 private final int maxIters; // 最大迭代次数(默认 10) private final Toolkit toolkit; // 可用工具集 private final PlanNotebook planNotebook; // 计划本 private final StatePersistence statePersistence; // 状态持久化策略 } 核心循环:reason → act → reason → act → … 整个 ReAct 循环的入口: private Mono<Msg> executeIteration(int iter) { return reasoning(iter, false); // 先推理 } reasoning 阶段(第 560-650 行) ① 检查 maxIters → 超限则走 summarizing() ② notifyPreReasoningEvent() ← Hook 注入点:CompactionHook、SubagentsHook、WorkspaceContextHook ③ model.stream(messages + tool schemas) ← 调 LLM ④ 逐 chunk 处理 + notifyReasoningChunk() ← 流式输出 ⑤ notifyPostReasoning() ← Hook 注入点 ⑥ 判断: - stopRequested → 返回(HITL 打断) - gotoReasoning → 继续推理(结构化输出重试) - isFinished(msg) → 没有 tool call → 返回结果 - 有 tool call → going to acting(iter) 关键判断 isFinished(第 969 行): ...

May 22, 2026 · 3 min · 531 words · WY