Chapter 14 of 32 · ~20 min read & lab+75 XP
Chapter 14 · Agentic AI

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!

What Is It?

Short-Term Agent Memory manages active conversation turns inside a strict token budget using atomic sliding windows and rolling summaries.

Why Is It Required?

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.

Everyday Analogy: Keeping your pinned instruction card at the top of a clipboard while archiving older scratch pages once the board fills up.
Why ML Engineers & Data Scientists Actually Need This

A chat agent that naively appends every message forever eventually crashes with ContextLengthExceeded — and naive slicing crashes with HTTP 400: orphaned tool_call_id!

ML / AI Engineer

Getting Atomic Turn-Group Eviction and Token-Budget Packing right is the difference between a toy demo and a resilient production assistant.

Data Scientist

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!

Interview & Debug Edge

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!'

Step 0 · Test Your Gut Before Any Math!

What happens if a sliding-window evictor deletes an Assistant message containing tool_calls while leaving the corresponding role: 'tool' Observation message in messages[]?

What You Will Master in This Chapter
  • 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: tool Observation without its matching Assistant tool_call
  • Combine Sliding Windows with Rolling Summarization (Summary-Buffer Memory) to preserve early goals across long chats
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 3
Bhist=Lmax⁡−Tsys−Ttools−ToutB_{\text{hist}} = L_{\max} - T_{\text{sys}} - T_{\text{tools}} - T_{\text{out}}Say aloud:“available history token budget”
Plain-English Meaning
Exact token room left for conversation turns after reserving System, Tool Schemas, and Output headroom
Everyday Example
128K − 2K − 3K − 4K = 119K
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

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

Everyday Story First (Zero Math Yet!)

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!

Sliding-Window Short-Term Memory: Pin System Prompt, Evict Oldest TurnsSYS (Pinned)Turn 1 (Evict)Turn 2 (Evict)Turn 3 (Kept)Turn 4 (New)Always reserve output token headroom: max_history_tokens = context_limit − sys_tokens − max_output_tokens!
Sliding-Window Memory pins the System Prompt permanently at index 0 and evicts the oldest User/Assistant turns once the token budget B is reached!

Back-to-Front Greedy Packing

  1. Reserve tokens for System Prompt + Tool Schemas + Max Output.
  2. Walk backward from the newest turn to the oldest, adding turns while used + turn_tokens <= B_hist.
  3. Reverse the selected slice to restore chronological order and prepend the pinned System Prompt!
Animated Mini-Lab • 3.1

Sliding-Window Token Budget Simulator (System = 200 tok pinned)

Turn 1
250 tok
Turn 2
280 tok
Turn 3
240 tok
Turn 4 (Latest)
220 tok

2. Hybrid Summary-Buffer Memory

Everyday Story First (Zero Math Yet!)

Pure sliding windows suffer from amnesia (forgetting the user's name or goal from Turn 1); Summary-Buffer memory bridges the gap cleanly.

Summary-Buffer Hybrid Memory: Compressed History + Verbatim Recent TailSystem PromptRolling Summary (Turns 1–12)"User is building a FastAPI app..."Recent Verbatim Window (Turns 13–16)Exact code snippets & tool outputs preserved ✓
Hybrid Summary-Buffer Memory compresses evicted older turns into a concise Rolling Summary while keeping the newest K verbatim turns crisp!

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

Everyday Story First (Zero Math Yet!)

Never slice messages[-10:] blindly in a tool-using agent — always group tool calls with their observations!

Atomic Tool-Pair Eviction Rule: Never Orphan a `role: tool` Message!Broken Naive Slice ✗[SYS, Tool(id=7), User, Asst]API crashes HTTP 400: orphaned tool_call_id=7!Atomic Turn-Group Eviction ✓Evict (Asst[call=7] + Tool[id=7]) together100% valid message sequence guaranteed!
Critical eviction invariant: NEVER evict an Assistant 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 User or Assistant (no tool_calls) = 1-message block.
  • Assistant (with N tool_calls) + its N following role: "tool" messages = 1 atomic block of size N + 1!
Walk Through With Me · Interactive Worked Example

Worked Example: Packing Turns Under a 1,000-Token Budget

Pinned System = 200 tok. Turns: [T1: 300, T2: 350, T3: 250, T4: 200].

11. Remaining budget after System PromptStep 1 / 2

1000−200=800 tokens1000 - 200 = \mathbf{800\text{ tokens}} available for turns.

Teacher's Note: Always keep the latest turn (T4) first!
Pause & Check · Quick Intuition Pulse

In Sliding-Window Agent Memory, which message must NEVER be evicted?

Try It YourselfStandard

Why is summarizing on every single turn terrible for GPU Prefix Caching compared to batch-summarizing only when crossing a high-water mark?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

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!

Interactive Visual Lab
Lab Challenge: Watch the 60 FPS Sliding-Window Evictor keep [SYS] pinned while evicting oldest turns cleanly.
Interactive Animation • 3.1 Deep Lab

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.

Active Turn 2 / 5
[SYS] Pinned ✓
Turn #1 (In Window)
Turn #2 (In Window)
0%
Turn 2 Arrived
Intuition Takeaway: Short-term memory packs newest turns back-to-front under B_hist, pins the System Prompt, evicts (tool_call + tool_obs) pairs atomically, and uses hysteresis Summary-Buffer compression to avoid amnesia.
Where This Powers Real ML, Deep Learning & Generative AI

Long-Running Customer Support & IDE Chats

Combines pinned System Prompt + hysteresis Summary-Buffer + atomic tool-pair eviction.

Production NumPy & PyTorch Code Patterns
# 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)])
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Slicing messages[-K:] without checking if messages[-K] is a role: 'tool' message.
Best Practice: Always group (Assistant tool_call + Tool outputs) atomically before slicing!
Chapter Mastery Check (+75 XP)
Score: 0 / 1
1Why must a Sliding-Window Memory manager treat an Assistant tool_call message and its role: 'tool' responses as ONE atomic eviction unit?

Apply What You Learned — Solve Matching Coding Problems