Sliding Window Memory is a conversation memory strategy that keeps only the most recent N messages (or K interactions) in the buffer. When a new message arrives and the buffer exceeds the limit, the oldest message is automatically evicted — just like a window sliding forward over a stream of conversation.
CN: Sliding Window Memory(滑动窗口记忆)是一种对话记忆策略,它只在缓冲区中保留最近的 N 条消息(或 K 轮交互)。当新消息到达且缓冲区超过限制时,最旧的消息会被自动移除——就像一扇窗口在对话流上向前滑动。
What does Sliding Window Memory include?
Core Concepts
| 概念 (Concept) | EN | CN |
|---|---|---|
| Window Size (k) | The maximum number of interactions (or messages) to keep | 保留的最大交互(或消息)数量 |
| FIFO Eviction | First-In-First-Out: oldest messages are removed first | 先进先出:最早的消息最先被移除 |
| Buffer | The data structure that holds the recent messages | 存放最近消息的数据结构 |
| Trimming | The act of removing old messages when limit is exceeded | 超过限制时移除旧消息的行为 |
Two Measurement Approaches
- Count-based Window: Keep the last
Nmessages (orKturns). Simple and predictable. - Token-based Window: Keep messages until a token budget is reached, then evict oldest.
CN:
Key Caveats
- System messages should NOT be trimmed: System prompts are foundational and should always be kept.
- Tool call pairs must be preserved together: If you trim a tool result, you must also trim its corresponding tool call, otherwise you break the API contract.
- Sliding window loses long-term context: It cannot answer questions like “Remember what I said 50 turns ago?”
CN:
- System 消息不应该被裁剪: System prompt 是基础性的,应该始终保留。
- Tool call 配对必须一起保留: 如果你裁剪了一个 tool result,也必须裁剪对应的 tool call,否则会违反 API 协议。
- 滑动窗口丢失长期上下文: 它无法回答诸如“还记得 50 轮前我说了什么吗?”这样的问题。
Key Takeaways
| 要点 (Key Point) | EN | CN |
|---|---|---|
| 滑动窗口只保留最近 N 条消息 | Sliding window keeps only the most recent N messages | 滑动窗口只保留最近的 N 条消息 |
deque(maxlen=N) 自动驱逐最旧消息 | deque(maxlen=N) automatically evicts oldest messages | deque(maxlen=N) 自动驱逐最旧消息 |
| System 消息永远不应被裁剪 | System messages should never be trimmed | System 消息永远不应被裁剪 |
LangChain 提供 ConversationBufferWindowMemory | LangChain provides ConversationBufferWindowMemory | LangChain 提供 ConversationBufferWindowMemory |
| 基于 Token 的窗口比基于数量的窗口更实用 | Token-based window is more practical than count-based | 基于 Token 的窗口比基于数量的窗口更实用 |
| 滑动窗口的代价是丢失长期上下文 | The trade-off is losing long-term context | 滑动窗口的代价是丢失长期上下文 |
| 可与摘要结合形成混合记忆系统 | Can be combined with summarization for hybrid memory | 可与摘要结合形成混合记忆系统 |

