Lesson 55.4 · 4 of 4 · 5 min read · Reviewed 24 Nov 2026
Sliding windows and recursive summaries
By the end, you can
- Keep working memory bounded with a sliding window of recent turns.
- Fold turns that leave the window into a recursive summary without losing key facts.
Working memoryWorking memory: The information an agent holds in its current context window: instructions, recent turns and tool results. (55.1) has a fixed size, but conversations do not. Two simple mechanisms keep a long chat inside the window: a sliding window for recent turns and a recursive summary for everything older.
The sliding window
Keep only the newest turns in full. When a new turn arrives, the oldest one slides out.
turn: 1 2 3 4 5 6 7 8 9 10 11 12
window: [7 8 9 10 11 12] (last 6 turns)
gone: [1 2 3 4 5 6]
On its own, this is a hard forget: whatever was said in turn 2 no longer exists for the model. That is fine for small talk and bad for “my budget is 500 credits”.
The recursive summary
Instead of throwing old turns away, fold them into a summary. Each time turns leave the window:
new_summary = summarise(old_summary + turns_leaving_the_window)
The context for each call is then:
[system prompt]
[summary of turns 1-6]
[turns 7-12 in full]
[new user message]
The summary is recursive because it is built from the previous summary, not from the full history. That keeps the cost of each update small and constant, however long the chat runs. Research systems such as MemGPT use this idea, with the summary acting as a compressed “recall” of what was paged out.
A worked example
| Turn | Event | Summary after update |
|---|---|---|
| 4 | User: “Budget 500 credits, no weekends” | (still in window) |
| 11 | Turn 4 slides out | “Planning a trip. Budget 500 credits. No weekend travel.” |
| 18 | Turns 5 to 11 slide out | “Planning a trip to Porto. Budget 500 credits. No weekends. Chose the 9 May train.” |
Getting the details right
- Size the window in tokensToken: The unit a model reads and writes: a word, part of a word, a space or a symbol, mapped to an integer id., not turns. One turn with a big tool result can be larger than ten chat turns.
- Slide whole units. A tool call and its tool result leave together, or the API rejects the request and the model loses track.
- Summarise in batches. Folding one turn at a time costs a model call per turn. Fold several at once, when the window passes a threshold.
- Pin exact values. Ids, amounts and dates go in a structured block that is copied forward, not summarised (60.4).
Common mistakes
- Drift. After many rounds, a summary of a summary can lose or bend facts: “500 credits” becomes “a modest budget”. Pinned facts prevent it.
- Summarising the system promptSystem prompt: Instructions passed in the top-level system field that set the model’s role, rules and context for the whole conversation.. Instructions stay as they are; only conversation slides.
- No limit on the summary. Give it a token cap, or it slowly becomes the new long history.
Chapter 60 goes further with compactionCompaction: Summarising older conversation history so a long session fits in the context window while keeping what matters. for agentsAgent: A system where a model decides its own next steps, calling tools in a loop until the task is done.. The window plus summary is the simple version that every chat app can start with.
Key points
- A sliding window keeps only the last N turns (or the last N tokens) in full; everything older leaves the context.
- A recursive summary keeps what left: each time turns slide out, the old summary plus those turns become a new summary.
- Measure the window in tokens, and never split a tool call from its result.
- Summaries of summaries drift, so pin exact facts outside the summary.
Build a sliding window with recursive summary
Keep the last turns in full within a token budget, fold turns that leave into a recursive summary, and keep tool calls with their results.
You will have: A Window class that prints the context on the final turn, with the budget fact still present.
Steps
- Read the 30 sample turns: turn 4 states the budget, and some turns are a tool call followed by its result.
- Write add(turn): append, then while the window is over budget, remove the oldest unit (a tool call leaves with its result).
- Fold removed turns into the summary with summarise(old_summary, removed), which keeps lines starting with FACT.
- Cap the summary at 5 facts and print the final context.
- Check that the context never starts with a tool result whose call was removed.
Done when
- The final context mentions 'budget 500 credits'.
- The largest window seen never goes over the token budget.
- No orphan tool result is printed at the start of the window.
Open in the Playground No API key needed.
Starter code (Python)
TURNS = []
for i in range(1, 31):
if i == 4:
TURNS.append({"role": "user", "text": "FACT: budget 500 credits, no weekend travel"})
elif i % 7 == 0:
TURNS.append({"role": "tool_call", "text": "search trains day %d" % i})
TURNS.append({"role": "tool_result", "text": "12 trains found, cheapest 40 credits ... " * 3})
else:
TURNS.append({"role": "user" if i % 2 else "assistant", "text": "chat about the trip, turn %d" % i})
def tokens(text):
return max(1, len(text) // 4)
def summarise(old_summary, removed):
facts = [l for l in old_summary.split("\n") if l] + [t["text"] for t in removed if t["text"].startswith("FACT")]
return "\n".join(facts[-5:])
class Window:
def __init__(self, budget):
self.budget, self.turns, self.summary = budget, [], ""
def size(self):
return sum(tokens(t["text"]) for t in self.turns)
def add(self, turn):
self.turns.append(turn)
# TODO: while over budget, remove the oldest unit (a tool_call takes its tool_result with it)
# and fold the removed turns into self.summary with summarise
w = Window(budget=60)
for t in TURNS:
w.add(t)
print("summary:", w.summary or "(empty)")
print("window size:", w.size(), "turns:", len(w.turns))
Show a solution
TURNS = []
for i in range(1, 31):
if i == 4:
TURNS.append({"role": "user", "text": "FACT: budget 500 credits, no weekend travel"})
elif i % 7 == 0:
TURNS.append({"role": "tool_call", "text": "search trains day %d" % i})
TURNS.append({"role": "tool_result", "text": "12 trains found, cheapest 40 credits ... " * 3})
else:
TURNS.append({"role": "user" if i % 2 else "assistant", "text": "chat about the trip, turn %d" % i})
def tokens(text):
return max(1, len(text) // 4)
def summarise(old_summary, removed):
facts = [l for l in old_summary.split("\n") if l] + [t["text"] for t in removed if t["text"].startswith("FACT")]
return "\n".join(facts[-5:])
class Window:
def __init__(self, budget):
self.budget, self.turns, self.summary = budget, [], ""
self.max_seen, self.orphans = 0, 0
def size(self):
return sum(tokens(t["text"]) for t in self.turns)
def add(self, turn):
self.turns.append(turn)
while self.size() > self.budget and len(self.turns) > 1:
n = 2 if self.turns[0]["role"] == "tool_call" and len(self.turns) > 1 and self.turns[1]["role"] == "tool_result" else 1
removed, self.turns = self.turns[:n], self.turns[n:]
self.summary = summarise(self.summary, removed)
if self.turns and self.turns[0]["role"] == "tool_result" and len(self.turns) > 1:
self.orphans += 1
self.max_seen = max(self.max_seen, self.size())
w = Window(budget=60)
for t in TURNS:
w.add(t)
print("summary:", w.summary or "(empty)")
print("window size:", w.size(), "turns:", len(w.turns), "largest window seen:", w.max_seen)
print("orphan tool results at window start:", w.orphans)
print("context:")
print(" [system prompt]")
print(" [summary] " + w.summary.replace("\n", " | "))
for t in w.turns:
print(" [" + t["role"] + "] " + t["text"][:50])
Finished the chapter? Take the chapter check.