15-07 实战:实现AgentScope的三层记忆体系
✅实战:实现AgentScope的三层记忆体系
AutoContextMemory的使用
AutoContextMemory其实也是Memory的一个实现类。所以可以把他当做Memory设置到ReactAgent中。
AutoContextMemory可以通过AutoContextConfig来设置一些可以调节的参数,并且AutoContextMemory因为需要用到LLM,所以需要给他一个ChatModel。
1 | DashScopeChatModel chatModel = DashScopeChatModel.builder() .apiKey("sk-dcebc45c03b04c6e85391abb2264e594") .modelName("qwen3-max") .stream(true) .enableThinking(true) .formatter(new DashScopeChatFormatter()) .defaultOptions(GenerateOptions.builder().thinkingBudget(1024).build()) .build(); |
构造好了一个AutoContextMemory之后,就可以把他设置个ReactAgent作为Memory了,但是,这里还需要注意的是,AutoContextMemory中的compressIfNeeded是需要通过一个Hool来调用执行的。这个Hook就是AutoContextHook。
所以用法如下:
1 | ReActAgent agent = ReActAgent.builder() .memory(memory) // 自动上下文压缩 .hook(new AutoContextHook()) // 自动上下文压缩 Hook .build(); |
在AutoContextHook的handlePreReasoning中,会执行autoContextMemory.compressIfNeeded(); 。也就是在LLM每一次Reasoning之前,会触发调用。
三层记忆体系
通过前面几节课介绍的长期记忆、持久化记忆以及智能上下文压缩。我们可以用ASJ实现一个三层记忆体系:
1 | package cn.hollis.llm.llmentor.agentscope.demo; |
1 | 用户输入 ↓ ┌──────────────────┐ │AutoContextMemory │ ← 短期记忆(带自动压缩) │ 最近 20 条原文 + │ 超长后早期消息会被 LLM 总结 │ 早期对话摘要 │ └──────────────────┘ ↓ ┌──────────────────┐ │ JsonSession │ ← 会话持久化(跨重启) │ 序列化到磁盘 │ 保存的是上面的短期记忆 └──────────────────┘ ↓ ┌──────────────────┐ │ Mem0LongTermMem │ ← 长期记忆(跨会话语义检索) │ 向量化提取的事实 │ 每轮自动写入,每轮自动召回 └──────────────────┘ |
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Southblock'Blog!
