记忆窗口、检索与 Function Calling 联动
约 560 字大约 2 分钟
布欧-Lewyon
2026-06-08
首页 › Agent Spring Boot › Memory 对话记忆
窗口策略
| 参数 | 默认值 | 作用 |
|---|---|---|
max-messages | 20 | 短期 LIST 最多保留条数 |
session-ttl-minutes | 120 | 无活动后会话过期 |
max-memories | 200 | 长期记忆上限,超出淘汰 |
search-top-k | 5 | search_memory 返回条数 |
对话超长时,旧消息被 LTRIM 裁掉。模型仍可通过 search_memory 捞长期库里的摘要。
为什么不把 tool 中间态写入短期记忆
assistant 带 tool_calls 的消息只在当轮 callLLM 内存在。持久化只存:
- 用户最终问题
- 助手最终自然语言回答
减少 Redis 体积,也避免下轮 context 里夹杂无效 tool JSON。
聊天模式 vs Agent 模式
ChatService 流式 | AgentService + Memory | |
|---|---|---|
| 端点 | GET /api/chat/stream | POST /api/agent/chat |
| 记忆 | 无 | 短+长 |
| Tool | 无 | 6 个 |
| 流式 | 是 | 否 |
用户要「记得刚才说了什么」必须走 Agent 模式。
Token 与注入权衡
system: 角色 + Tool 说明 + 最多 10 条长期记忆
messages: 短期 history(≤20 条 user/assistant)
user: 当前问题长期记忆全塞进 system 会涨 Token。策略:
- system 只放 top 10 条摘要
- 更多用
search_memory按需拉取 - 短期窗口 20 条对客服场景通常够
与 RAG 的边界(预告)
| 记忆 | RAG |
|---|---|
| 用户个性化事实 | 企业知识库文档 |
| Redis 关键词检索 | Embedding 语义检索 |
save_memory | search_articles |
agent-rag 会同时保留两套,System Prompt 由 MemoryManager.buildSystemPrompt(userId, ragContext) 扩展。
面试可讲的设计点
- 双 ID:
userId跨会话,sessionId隔离对话 - history 双源:客户端优先,Redis 降级
- 长期记忆 Tool 化:模型决定记什么,比 NLP 规则抽取更省事
- 不用 Spring AI Memory:协议透明,但迁移到
MessageChatMemoryAdvisor时可对照本实现
学习点
- 窗口 + TTL 控制成本;长期记忆用 Tool 按需检索补全。
- 流式聊天与记忆 Agent 分路径,产品上要模式区分。
- 下一阶段在
agent-rag加文章向量检索。
小结
- 短期 LTRIM + 长期淘汰 +
search_memory构成完整记忆策略。 - Agent 路径非流式,但带完整 Memory + Tool。
agent-memory完成后进入agent-rag整合 RAG。
上一节:Redis Service 实现
下一节:RAG 架构
