版本
基于 AgentScope-Java v2.0.5 分析。
agent 的循环
-
Agent 的核心,是两个 while 循环:
-
外层循环,持续接受用户指令,是用户与 Agent 之间的循环。
-
内层循环,是对于一个用户的指令,不断规划+行动+观察,是 Agent 内部自己的循环。
-
java
while(1) {
感知用户输入
while(任务未完成) {
规划(决定下一步做什么)
行动(调用工具,真的去做)
观察(读取结果,评估效果)
判断是否完成,完成则跳出循环
}
}
ReActAgent 的内循环 ReAct loop
io.agentscope.core.ReActAgent
-
ReAct loop 是 agent 的内循环,AgentScope 称为推理-行动循环。
-
AgentScope ReAct loop 实现这套循环,使用的是递归的方式。
-
io.agentscope.core.ReActAgent.CallExecution#executeIteration
scss
executeIteration(iter) // 首轮 iter = 0
└─ reasoning(iter, false) // ignoreMaxIters = false
└─ 是否达到循环次数上限 ← 第 2551 行
├─ 是:达到上限 → return summarizing()
│ └─ summaryStream(...) → summaryModelCallStream(...)
│ └─ mci.model().stream(...) ← 第 4278 行:调用模型总结,结束循环
│
└─ 否:未达上限 → 进入常规推理
├─ 组装本轮消息、可用工具和生成参数
├─ reasoningStream(...)
│ └─ 经 onModelCall 中间件进入 modelCallStream(...)
│ ├─ mci.model().stream(...) ← 第 2887 行:调用模型推理
│ └─ context.processChunk(chunk) ← 第 2902 行:逐个处理返回分片
├─ buildFinalMessage() ← 第 2647 行:聚合成本轮 Msg
└─ runPostReasoningPipeline(msg, iter) ← 第 2695 行:决定下一步
├─ 已得到最终回答 → 返回 Msg,结束循环
│ ├─ if (isFinished(eventMsg)) ← 第 2736 行
│ └─ return Mono.justOrEmpty(eventMsg); ← 第 2752 行
└─ 有普通工具调用 → acting(iter) → 工具结果写入历史
→ executeIteration(iter + 1) // 进入下次循环
→ 回到第 2551 行,重新判断是否达到上限
HarnessAgent
HarnessAgent 在外层增加工作区、沙箱和上下文压缩等能力,不再实现同一套循环。
AgentState
- ReActAgent 负责 agent 的推理行动循环,AgentState 保存 loop 已经发生了什么(维护上下文)。
- AgentState 保存了什么
| 字段 | 在循环中的作用 |
|---|---|
| userId, sessionId | 标识这份状态关联的用户和会话。一次调用开始时,据此加载或创建对应的 AgentState。 |
| List context | 上下文,保存用户输入、模型生成的 assistant message(思考过程)、工具执行结果和最终回答。读写 AgentState 主要操作上下文。 |
| toolContext | 记录已激活的工具组等信息,影响这轮模型能看到哪些工具。 |
| permissionContext | 保存会话权限配置,供工具执行前判断。 |
| curIter, summary | 虽然类里有这两个字段,但当前主循环不用 curIter 判断轮数,达到上限也不是把结果写入 summary。 |
AgentState 在内循环 ReAct loop 的读写
io.agentscope.core.state.AgentState
scss
进入循环前:doCallInner(msgs)
├─ [读] 检查 state.context 中是否有未完成的工具调用 第 1948 行
└─ [写] 普通新请求:把用户消息追加到 state.context 第 1952 → 2514 行
executeIteration(iter)
└─ reasoning(iter, false)
├─ 判断 iter >= maxIters(读方法参数 iter,不读 state.curIter) 第 2551 行
│
├─ 已达上限 → summarizing()
│ ├─ [读] 复制 state.context,在副本上追加总结提示 第 4351--4352 行
│ ├─ 调用模型总结 第 4278 行
│ └─ [写] 将总结 Msg 追加到 state.context,不写 state.summary 第 4232--4233 行
│
└─ 未达上限 → 常规推理
├─ [读] 取 state.context 中的历史,再拼接系统消息 第 2561、2577 行
├─ [读] 取 state.toolContext 中的激活工具组,组装 schema 第 2580--2581 行
├─ model.stream(...) → processChunk(...) → buildFinalMessage()
│ 分片在 ReasoningContext 中聚合,不逐片写 AgentState
├─ 收到停止请求且 finalMsg 非空 → [写] 追加到 state.context 第 2656--2657 行
└─ 正常路径 → runPostReasoningPipeline(msg, iter) 第 2695 行
├─ [写] 把本轮助手 Msg 追加到 state.context 第 2713 行
├─ 已得到最终回答 → 返回 Msg,不重复写入
│ ├─ if (isFinished(eventMsg)) 第 2736 行
│ └─ return Mono.justOrEmpty(eventMsg); 第 2752 行
└─ 有普通工具调用 → acting(iter)
├─ [读] 从 state.context 找出尚未返回结果的工具调用 第 3099 行
├─ [写] 执行工具,将 TOOL 消息追加到 state.context 第 4002 行
└─ executeIteration(iter + 1) 第 3237 行
→ 回到第 2551 行检查上限;未达上限则读取含工具结果的历史