【AgentScope Java新手村系列】(11)中断与恢复

第十一章 中断与恢复:用 AgentStateStore 持久化会话,sessionId 实现断点续聊

"用户问了 3 轮突然关掉浏览器;20 分钟后用同一个会话 ID 回来------上一轮的上下文、todo、subagent 状态怎么全在?这是 2.0 的 AgentStateStore 后端(JsonFileAgentStateStore / RedisAgentStateStore / MysqlAgentStateStore)干的事,比 1.x 自己把 Memory 序列化 JSON 简单很多。"

本章你将学到:如何让 HarnessAgent 在中断后秒级恢复、如何在前端用 sessionId 做'断点续聊'、以及如何配合 Plan Mode 让用户的待办清单也跟着恢复。

11.1 中断与恢复的本质

1.x 时代,"中断恢复" 要自己做:

  1. 写一个 Memory 的 JSON 序列化器
  2. 启动时检查 session 目录,有旧 JSON 就 load 进 Memory
  3. 手动管理 session ID 与 cookie / token 的对应

2.0 把这件事下沉到 AgentStateStore 后端 ------HarnessAgent 调用时根据 RuntimeContext.sessionId() 去后端查状态;查到就 load 进 AgentState,查不到就当新会话。业务代码不需要写任何序列化逻辑

11.2 第一个可恢复会话

java 复制代码
import io.agentscope.core.agent.RuntimeContext;
import io.agentscope.core.message.UserMessage;
import io.agentscope.core.model.DashScopeChatModel;
import io.agentscope.core.state.JsonFileAgentStateStore;
import io.agentscope.harness.HarnessAgent;

import java.nio.file.Path;
import java.util.List;

public class Chapter11_Resume {

    public static void main(String[] args) {
        // 用同一个 sessionId 模拟"用户先问一通,再回来问"
        String sessionId = "demo-user-9527-2026-06-07";

        HarnessAgent agent = HarnessAgent.builder()
                .name("assistant")
                .sysPrompt("你是一个中文助理,简洁回答。")
                .model(DashScopeChatModel.builder()
                        .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                        .modelName("qwen-plus")
                        .build())
                .workspace(Path.of("./workspace"))
                .stateStore(new JsonFileAgentStateStore(Path.of("./workspace")))  // 文件版 AgentStateStore
                .build();

        RuntimeContext ctx = RuntimeContext.builder()
                .sessionId(sessionId)
                .userId("9527")
                .build();

        // ---- 第一通对话 ----
        agent.call(List.of(new UserMessage("user", "我叫小李,在杭州做程序员。")), ctx).block();
        agent.call(List.of(new UserMessage("user", "我用什么语言开发?")), ctx).block();

        // 假装用户关掉浏览器。20 分钟后 JVM 重新跑 main() ------ 实际生产里这是另一个进程。

        // ---- 20 分钟后:用同一 sessionId 接着问 ----
        agent.call(List.of(new UserMessage("user", "我叫什么?在哪个城市?")), ctx).block();
        // 输出会包含:"你叫小李,在杭州做程序员。"
    }
}

第一次跑:

csharp 复制代码
[reply] 你好小李,很高兴认识你。
[reply] 根据你刚才提供的信息,你在杭州做程序员。

关掉进程,删掉进程内变量;第二次跑(同一个 workspace、同一个 sessionId):

csharp 复制代码
[reply] 早上好小李。有什么可以帮你?
[reply] 你叫小李,在杭州做程序员。

------完整恢复

11.3 三个常见的"断点续聊"场景

11.3.1 浏览器刷新

最简单:前端把 sessionIdlocalStorage,刷新后从 localStorage 取出、塞回请求参数。后端完全无感。

ini 复制代码
let sessionId = localStorage.getItem("sessionId");
if (!sessionId) {
  sessionId = crypto.randomUUID();
  localStorage.setItem("sessionId", sessionId);
}

fetch(`/api/agent/chat?sessionId=${sessionId}`, {
  method: "POST",
  body: JSON.stringify({ text: "我叫什么?" }),
});

11.3.2 用户切换设备

用户在手机问了一通,到电脑上想接着聊。把手机端的 sessionId 暴露成"会话恢复码",让用户在电脑端输入;后端用同一个 sessionId 调 agent。

注意AgentStateStore 不感知设备。要加一层 user_id → session_id 的映射(自己做或者用 Spring Session)。

11.3.3 用户主动重置

提供"清空对话"按钮------后端开新 sessionId

typescript 复制代码
@PostMapping("/session/reset")
public Map<String, String> reset(@RequestParam String userId) {
    String newId = "user-" + userId + "-" + System.currentTimeMillis();
    return Map.of("sessionId", newId);
}

老会话状态会自然过期(按 AgentStateStore 后端的 TTL 清理)。

11.4 Plan Mode 与 todo 的恢复

如果开了 Plan Mode(HarnessAgent.enablePlanMode()),todo_write 写下的待办也会被 AgentStateStore 持久化。例:

ini 复制代码
HarnessAgent agent = HarnessAgent.builder()
        ...
        .enablePlanMode(true)
        .build();

用户在第一通对话里让 agent 计划"调研 5 件事"------agent_todo 会被持久化;用户回来时:

arduino 复制代码
"上次我让你调研的 5 件事,现在做到哪了?"

agent 会读 AgentStateStore 里的 todo 列表,把状态念给用户听。

11.5 用 RedisAgentStateStore 做生产级恢复

JsonFileAgentStateStore 适合开发与单机部署;多实例 / 多机部署要用 RedisAgentStateStore(见第 5 章):

less 复制代码
HarnessAgent agent = HarnessAgent.builder()
        .stateStore(RedisAgentStateStore.builder()
                .jedisClient(new UnifiedJedis("redis://127.0.0.1:6379"))
                .build())
        .build();

恢复流程一模一样,区别只在"状态存在 Redis 而非本地 JSON"。

11.6 主动重连 vs 自动重连

场景 推荐策略
用户离开 5 分钟 不主动重连------AgentStateStore 一直保留;用户回来直接续
30 分钟未活动 由前端弹"是否继续"按钮,避免 token 浪费
1 小时未活动 后端 cron 清理 Redis 里的旧 session
24 小时未活动 强制清空(保留 MEMORY.md 长期记忆)

RedisAgentStateStore 可以设 TTL;JsonFileAgentStateStore 可以用 Files.deleteIfExists 自己写清理脚本。

11.7 完整可运行示例

java 复制代码
import io.agentscope.core.agent.RuntimeContext;
import io.agentscope.core.message.UserMessage;
import io.agentscope.core.model.DashScopeChatModel;
import io.agentscope.core.state.JsonFileAgentStateStore;
import io.agentscope.harness.HarnessAgent;

import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class Chapter11_Interrupted {

    public static void main(String[] args) throws InterruptedException {
        String sessionId = "u-9527-2026-06-07";

        HarnessAgent agent = HarnessAgent.builder()
                .name("assistant")
                .sysPrompt("你是一个中文助理。")
                .model(DashScopeChatModel.builder()
                        .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                        .modelName("qwen-plus")
                        .build())
                .workspace(Path.of("./workspace"))
                .stateStore(new JsonFileAgentStateStore(Path.of("./workspace")))
                .build();

        RuntimeContext ctx = RuntimeContext.builder()
                .sessionId(sessionId).userId("9527").build();

        // ---- Round 1 ----
        agent.call(List.of(new UserMessage("user", "我养了一只橘猫,叫'小年'。")), ctx).block();
        agent.call(List.of(new UserMessage("user", "它叫什么?")), ctx).block();

        System.out.println("=== 模拟用户关闭浏览器 5 秒 ===");
        TimeUnit.SECONDS.sleep(5);

        // ---- Round 2:模拟"再回来" ----
        agent.call(List.of(new UserMessage("user", "我养了什么宠物?")), ctx).block();
    }
}

11.8 本章小结

  • AgentStateStore 是 2.0 中断恢复的核心,业务代码无需写序列化。
  • 同一 sessionId + 同一 AgentStateStore 后端 = 上下文自动恢复。
  • Plan Mode 的 todo 也会被 AgentStateStore 持久化。
  • 生产用 RedisAgentStateStore,开发用 JsonFileAgentStateStore
  • RC2 中 Agent 完全无状态化------同一实例可安全并发服务多 (userId, sessionId) 组合。
相关推荐
众少成多积小致巨2 小时前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
东坡白菜3 小时前
破局全栈:前端开发的Java入门实战记录—JPA(2)
java·后端
SimonKing9 小时前
艹,维护AI写的代码,我心态崩了......
java·后端·程序员
用户298698530149 小时前
Java Word 文档样式进阶:段落与文本背景色设置完全指南
java·后端
dunky9 小时前
Spring 的三级缓存与循环依赖
后端·spring
小bo波1 天前
从"任意文件复制"深挖Java I/O:字符流与字节流的本质抉择
java·nio·io流·后端开发·文件复制
用户3521802454751 天前
🎆从 Prompt 到 Skill:让 Spring AI Agent 学会"装新技能"
人工智能·spring boot·ai编程
nanxun8862 天前
记一次诡异的 Docker 容器"串包"故障排查
java
用户1563068103512 天前
Day01 | Java 基础(Java SE)
java