Sub topic 11
Memory and Notes Outside the Window
This chapter assumes you know what a context window and a token budget are, and that you have seen the compaction pattern from the previous chapter. It covers how to keep information that does not fit in the window, or should not occupy it, and bring it back when needed.
Why keep memory outside the window
Compaction shrinks history, but it is lossy. A summary can drop a file path, a decision, or a constraint that matters ten steps later. In a long task, the window also resets between sessions. External memory addresses both problems. The agent writes durable facts to storage outside the window, such as a file or a database. It reads them back only when they are relevant.
The window becomes working memory, and the external store becomes long-term memory. Only a small part of the store is loaded on any call.
What to store
Good candidates for notes:
- Decisions and the reasons for them, such as "chose SQLite because no server is available".
- Task state: what is done, what remains, and what failed.
- Facts that are expensive to rediscover, such as file locations or API quirks.
- User preferences that apply across sessions.
Poor candidates are raw tool output and full transcripts. Store a conclusion, not the evidence behind it. If you need the evidence later, store a pointer such as a file path or URL.
A minimal note store
This example keeps notes in a JSON file. Each note has a topic so the agent can load only what it needs.
import json
from pathlib import Path
class NoteStore:
def __init__(self, path):
self.path = Path(path)
self.notes = json.loads(self.path.read_text()) if self.path.exists() else []
def write(self, topic, text):
self.notes.append({"topic": topic, "text": text})
self.path.write_text(json.dumps(self.notes, indent=2))
def read(self, topic, limit=5):
matches = [n["text"] for n in self.notes if n["topic"] == topic]
return matches[-limit:] # most recent notes first priority
store = NoteStore("notes.json")
store.write("database", "Chose SQLite; no server available.")
store.write("database", "Schema lives in db/schema.sql.")
print(store.read("database"))At the start of a step, you call read for the current topic and place the results in the context. The limit caps how many tokens the notes can cost.
Choosing between memory approaches
| Approach | Strength | Weakness |
|---|---|---|
| Plain file the agent edits | Simple, readable by humans | Grows without bound unless pruned |
| Keyed notes by topic | Cheap, precise lookup | Needs a good topic scheme |
| Embedding search over notes | Finds notes by meaning | Can return plausible but irrelevant notes |
Start with the simplest option that works. Move to search only when the number of notes is too large to select by topic.
Common errors
- Writing too much. If every observation becomes a note, reading them back costs as much as the original history. Write only what a future step will need.
- Never pruning. Old notes go stale. A note saying "tests pass" is harmful after the code changes. Add dates or step numbers, and delete or update notes that are no longer true.
- Poisoned memory. A wrong fact written once is reloaded on every later call. Treat notes as untrusted input until verified, especially when they come from tool output or web pages.
- Loading everything. Reading the whole store at the start defeats the purpose. Select notes by relevance, as you would with retrieved documents.
- Silent conflicts. Two notes can disagree. Keep the newer one, or mark the conflict so the model does not guess.
Exercise
An agent working on a two-day refactor writes a note after every tool call and loads all notes at the start of each step. After a day, its answers get worse and its calls cost more. Name two causes and one fix for each.
Show answer
First, writing too much: notes duplicate raw tool output and fill the window. Fix by storing only conclusions and decisions, with pointers to evidence. Second, loading everything: the whole store occupies the budget and distracts the model. Fix by selecting notes by topic or relevance and capping how many are read. Stale notes are also a plausible cause; prune or date them.