Short-Term Agent Memory: Sliding Windows, Token Budgets & Rolling Summarization
How to manage multi-turn agent conversations without hitting Context Overflow or HTTP 400 errors: pinning the System Prompt, token-budget sliding windows, Hybrid Summary-Buffer memory, and atomic (tool_call + tool_obs) eviction!
Short-Term Agent Memory manages active conversation turns inside a strict token budget using atomic sliding windows and rolling summaries.
Naive message slicing orphans tool_result messages from their tool_call (crashing APIs) or drops the system prompt; atomic trimming keeps context valid and affordable.
A chat agent that naively appends every message forever eventually crashes with ContextLengthExceeded — and naive slicing crashes with HTTP 400: orphaned tool_call_id!
Getting Atomic Turn-Group Eviction and Token-Budget Packing right is the difference between a toy demo and a resilient production assistant.
Hybrid Summary-Buffer memory keeps latency and API bills flat even in 100-turn support sessions while retaining critical user constraints mentioned in Turn 1!
Direct coding interview favorite: 'Implement a Sliding-Window Memory manager with a max token budget that pins the System Prompt and preserves valid message ordering!'
What happens if a sliding-window evictor deletes an Assistant message containing tool_calls while leaving the corresponding role: 'tool' Observation message in messages[]?
- Compute exact available history token budgets:
max_history = context_limit − sys_tokens − tool_schemas − max_output - Implement a Sliding-Window Memory Manager that pins the System Prompt and evicts oldest turns cleanly
- Enforce Atomic Tool-Pair Eviction so you NEVER orphan a
role: toolObservation without its matching Assistanttool_call - Combine Sliding Windows with Rolling Summarization (Summary-Buffer Memory) to preserve early goals across long chats
Think of Short-Term Agent Memory like a small whiteboard in a conference room: the team rules stay taped permanently to the top (Pinned System Prompt), the last 5 minutes of work stay written in full detail (Recent Verbatim Window), and before you erase the left edge to make room for new notes, you jot 2 bullet points into a Summary Box so nobody forgets the original goal!
1. Token-Budget Sliding Windows & System Prompt Pinning
Drag the Budget slider in the mini-lab below to see how newest turns stay protected while oldest turns evict cleanly under a tight token ceiling!
Back-to-Front Greedy Packing
- Reserve tokens for System Prompt + Tool Schemas + Max Output.
- Walk backward from the newest turn to the oldest, adding turns while
used + turn_tokens <= B_hist. - Reverse the selected slice to restore chronological order and prepend the pinned System Prompt!
Sliding-Window Token Budget Simulator (System = 200 tok pinned)
2. Hybrid Summary-Buffer Memory
Pure sliding windows suffer from amnesia (forgetting the user's name or goal from Turn 1); Summary-Buffer memory bridges the gap cleanly.
When to Trigger Rolling Summarization
Don't re-summarize on every turn (that breaks Prefix Caching every turn!). Instead, use a high-water / low-water hysteresis: let turns grow to e.g. 12K tokens (hitting Prefix Cache on turns 1..15!), then summarize the oldest 8K tokens down to 600 tokens in one batch!
3. Enforcing Atomic Tool-Pair Integrity
Never slice messages[-10:] blindly in a tool-using agent — always group tool calls with their observations!
tool_call message while leaving its orphaned role: tool Observation behind — evict atomic (call + obs) pairs together!Clean Grouping Rule
Before evicting, partition history into atomic blocks:
- Standalone
UserorAssistant (no tool_calls)= 1-message block. Assistant (with N tool_calls)+ itsNfollowingrole: "tool"messages = 1 atomic block of sizeN + 1!
Worked Example: Packing Turns Under a 1,000-Token Budget
Pinned System = 200 tok. Turns: [T1: 300, T2: 350, T3: 250, T4: 200].
available for turns.
In Sliding-Window Agent Memory, which message must NEVER be evicted?
Why is summarizing on every single turn terrible for GPU Prefix Caching compared to batch-summarizing only when crossing a high-water mark?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Truncate or chunk the oversized input gracefully (or offload it to a file/RAG index) and notify the user — never send an over-limit payload that guarantees an API 400 crash!
[SYS] pinned while evicting oldest turns cleanly.Sliding-Window Short-Term Memory Evictor (Window = 3 Recent Turns)
Watch the System Prompt stay pinned at index 0 while the oldest turns evict cleanly as new turns arrive.
B_hist, pins the System Prompt, evicts (tool_call + tool_obs) pairs atomically, and uses hysteresis Summary-Buffer compression to avoid amnesia.Long-Running Customer Support & IDE Chats
Combines pinned System Prompt + hysteresis Summary-Buffer + atomic tool-pair eviction.
# Atomic Turn-Preserving Sliding Window (never orphan a tool_result from its tool_call)
def trim_sliding_window(messages: list[dict], max_tokens: int) -> list[dict]:
system = [m for m in messages if m["role"] == "system"]
convo = [m for m in messages if m["role"] != "system"]
# Group assistant tool_call with its following tool_result as an atomic unit
groups: list[list[dict]] = []
i = 0
while i < len(convo):
if convo[i].get("tool_call") and i + 1 < len(convo) and convo[i + 1]["role"] == "tool":
groups.append([convo[i], convo[i + 1]])
i += 2
else:
groups.append([convo[i]])
i += 1
kept, used = [], sum(m["tokens"] for m in system)
for grp in reversed(groups):
cost = sum(m["tokens"] for m in grp)
if used + cost <= max_tokens:
kept.insert(0, grp)
used += cost
return system + [m for grp in kept for m in grp]
msgs = [
{"role": "system", "tokens": 20},
{"role": "user", "tokens": 30},
{"role": "assistant", "tool_call": True, "tokens": 25},
{"role": "tool", "tokens": 25},
{"role": "user", "tokens": 20},
]
print("Kept roles:", [m["role"] for m in trim_sliding_window(msgs, max_tokens=95)])
messages[-K:] without checking if messages[-K] is a role: 'tool' message.(Assistant tool_call + Tool outputs) atomically before slicing!tool_call message and its role: 'tool' responses as ONE atomic eviction unit?