Sub topic 9
Memory and managing the context window
This chapter assumes you can read Python, have built the tool-calling loop from the earlier chapters, and know that a model reads a limited number of tokens per request. Here you will learn why an agent's history grows, what to do about it, and how to avoid the common mistakes.
Why the history grows
The model has no memory between calls. Each call to call_model(messages) sends the whole conversation again. In the agent loop, every step appends two items: the assistant's reply and the tool result. A run of 8 steps therefore sends the first message 8 times, and the tool results from step 1 are paid for at every later step.
The context window is the maximum number of tokens the model can read in one request. The input and the model's output both count against it. When the history exceeds the window, the API returns an error or you lose content. Even below the limit, a long history raises cost and latency, and the model can overlook details buried in the middle.
Tool results are usually the largest part. One web page or database dump can hold thousands of tokens, while the user's goal is a sentence.
Two kinds of memory
| Kind | Where it lives | Lifetime | Example |
|---|---|---|---|
| Short-term (working) memory | The `messages` list | One run | Tool results from the current task |
| Long-term memory | A file, database, or vector store outside the prompt | Across runs | A user's preferred units, notes from past sessions |
Long-term memory only affects the model when you put it into the prompt. The model cannot see a database. You either load selected facts at the start of a run, or give the agent tools such as save_note and search_notes so it decides what to store and retrieve.
Measuring the budget
You cannot manage what you do not measure. Count tokens before each call. Exact counts need the provider's tokenizer. A rough rule for English text is about 4 characters per token, which is good enough for deciding when to trim, as long as you leave a margin.
def estimate_tokens(messages: list[dict]) -> int:
# Rough estimate: about 4 characters per token.
total = 0
for m in messages:
total += len(str(m.get("content") or "")) // 4 + 4
if m.get("tool_call"):
total += len(str(m["tool_call"])) // 4
return totalPick a budget below the real limit. For a 32,000-token window, a budget of 24,000 leaves room for the system prompt, the tool schemas, and the reply. Tool schemas are sent on every call and count against the window too.
Strategy 1: truncate tool results
The cheapest fix is to cap each tool result when it enters the history. Say clearly that content was cut, so the model knows it can ask for more.
def clip(text: str, max_chars: int = 2000) -> str:
if len(text) <= max_chars:
return text
omitted = len(text) - max_chars
return text[:max_chars] + f"\n[truncated {omitted} characters; call the tool again with a narrower request]"In run_agent, wrap the result: result = clip(run_tool(...)). Better still, design tools to return less, with filters and page sizes, as covered in the tool design chapter.
Strategy 2: sliding window
Keep the first message (the goal) and the most recent messages, and drop the middle.
def sliding_window(messages: list[dict], keep_last: int = 6) -> list[dict]:
if len(messages) <= keep_last + 1:
return messages
return [messages[0]] + messages[-keep_last:]This has an edge case that breaks real agents. Many APIs require that every tool result follows the assistant message that requested it. If the cut lands between them, the API rejects the request. Cut on boundaries, so that an assistant tool call and its tool result stay together.
def sliding_window_safe(messages: list[dict], keep_last: int = 6) -> list[dict]:
if len(messages) <= keep_last + 1:
return messages
tail = messages[-keep_last:]
# Do not start the tail with an orphaned tool result.
while tail and tail[0]["role"] == "tool":
tail = tail[1:]
return [messages[0]] + tailThe weakness of any window is silent forgetting. If step 2 found the user's order number and step 3 was dropped, the agent may ask again or invent a value.
Strategy 3: summarize old turns
Instead of dropping old messages, replace them with a short summary written by the model. This keeps decisions and facts at a fraction of the size.
def compact(call_model, messages: list[dict], keep_last: int = 4) -> list[dict]:
if len(messages) <= keep_last + 1:
return messages
old, recent = messages[1:-keep_last], messages[-keep_last:]
while recent and recent[0]["role"] == "tool":
old.append(recent.pop(0))
prompt = [{"role": "user", "content":
"Summarize this work so far. Keep facts, IDs, decisions, and open questions.\n"
+ "\n".join(f'{m["role"]}: {m.get("content")}' for m in old)}]
summary = call_model(prompt)["content"]
return [messages[0],
{"role": "user", "content": f"Summary of earlier steps: {summary}"}] + recentSummarizing costs an extra model call and is lossy. Exact values such as IDs, file paths, and numbers are the first things a summary mangles. The prompt above asks for them explicitly. A safer pattern is to store such values outside the history, for example in a dictionary of "facts found so far" that you re-inject every turn.
Putting it together
Run the trimming just before each model call, not on the stored history, unless you mean to discard data permanently. Keeping the full log separately also gives you something to trace later.
def build_context(call_model, messages, budget=24000):
if estimate_tokens(messages) <= budget:
return messages
trimmed = compact(call_model, messages)
if estimate_tokens(trimmed) > budget:
trimmed = sliding_window_safe(trimmed, keep_last=4)
return trimmedIn the loop, change reply = call_model(messages) to reply = call_model(build_context(call_model, messages)). Keep appending to the full messages list.
Writing to long-term memory
Give the agent a small, explicit memory interface rather than letting it write anywhere.
import json
NOTES: dict[str, str] = {}
def save_note(key: str, value: str) -> str:
NOTES[key] = value
return json.dumps({"saved": key})
def search_notes(query: str) -> str:
hits = {k: v for k, v in NOTES.items() if query.lower() in (k + " " + v).lower()}
return json.dumps(hits)Register both in TOOLS. In production, replace the dictionary with a database. Retrieval by meaning, using embeddings, is the subject of the next chapter.
Common errors
- Counting only messages, not schemas. Tool definitions and the system prompt consume window space on every call.
- Splitting a tool call from its result. The API rejects the request. Always trim on pairs.
- Trusting summaries for exact values. Keep IDs and numbers in structured state.
- Saving everything. A memory store full of noise makes retrieval worse. Save durable facts, not raw tool output.
- Storing untrusted text as instructions. A note written from a web page may contain commands. Treat retrieved memory as data, and label it as such in the prompt.
- Trimming the stored history. You lose the evidence you need to debug a failed run.
Exercise
An agent's run fails on step 9 with an API error saying a tool result has no matching tool call. Your code uses a sliding window with keep_last=6. What is the likely cause, and how do you fix it?
Show answer
The window cut the history between an assistant message that requested a tool and the tool message that answered it, so the tail starts with an orphaned tool result. Fix it by trimming on boundaries: drop any leading tool messages from the tail, or keep the assistant tool call together with its result, as in slidingwindowsafe.
Exercise
Your agent summarizes old turns, and now it sometimes uses the wrong order number after a long run. Give two changes that reduce this.
Show answer
Keep exact values out of the free-text summary by storing them in a structured "facts" dictionary that is re-injected on every call. Also change the summary prompt to require that IDs, paths, and numbers be copied verbatim, and keep the most recent tool results unsummarized.