Sub topic 9
Memory and managing the context window
This chapter assumes you have read the agent loop chapter. You should be comfortable with the messages list that run_agent builds and with what a token is.
Why the history grows
In the loop, every step appends an assistant message and a tool result to messages. The whole list is sent to the model on the next call. The model has a fixed context window, which is the maximum number of tokens it can read in one request. A long run, or one large tool result, can exceed it. Even before that point, a long history raises cost and latency, and the model may pay less attention to details buried in the middle.
Memory in an agent is therefore a set of decisions about what to put in the next request.
Two kinds of memory
| Kind | Where it lives | Lifetime | Example |
|---|---|---|---|
| Short-term | The `messages` list | One run | Tool results from this task |
| Long-term | A file or database outside the model | Across runs | User preferences, past decisions |
Long-term memory is only useful if the agent reads it. Load relevant entries into the prompt at the start, or expose a lookup tool.
Three ways to stay within the window
- Truncate. Keep the system prompt and the most recent messages, and drop the oldest ones.
- Summarize. Replace old messages with a short summary written by the model.
- Offload. Store large content outside the history and keep only a reference.
The diagram shows how these fit before each model call.
A simple trimming function
This function keeps the first message, which holds the user's goal, and as many recent messages as fit a budget. It estimates tokens as four characters each, which is a rough rule for English text. Use your model's tokenizer for exact counts.
def estimate_tokens(message: dict) -> int:
text = str(message.get("content") or "") + str(message.get("tool_call") or "")
return len(text) // 4 + 1
def trim_messages(messages: list, budget: int) -> list:
first, rest = messages[0], messages[1:]
kept = []
used = estimate_tokens(first)
for message in reversed(rest):
cost = estimate_tokens(message)
if used + cost > budget:
break
kept.append(message)
used += cost
return [first] + list(reversed(kept))
history = [{"role": "user", "content": "Find the cheapest flight."}]
history += [{"role": "tool", "name": "search", "content": "x" * 400} for _ in range(10)]
print(len(trim_messages(history, budget=300)))In run_agent, call trim_messages(messages, budget) and pass the result to call_model.
Common errors
- Orphaned tool results. Trimming may drop an assistant message that made a tool call but keep its tool result. Many APIs reject this. Trim in pairs.
- Losing the goal. Always keep the original request and the system prompt.
- Summaries that drop facts. Tell the summarizer to preserve IDs, file paths, and decisions.
- Huge tool outputs. Cap their size inside
run_tooland tell the model the output was truncated.
Exercise
Why does the trim function above keep messages[0] even when it is the oldest message?
Show answer
It holds the user's original goal. If it is dropped, the agent may forget what task it is working on.
Exercise
A trimmed history contains a tool result whose matching assistant tool call was removed. What can happen, and how do you prevent it?
Show answer
Many model APIs reject the request or the model gets confused. Prevent it by trimming a tool call and its result together, as a pair.