About this notebook
Companion to Module 6: Memory and context engineering. Every cell below was executed with the offline backend, so you can reproduce these outputs exactly with no API key. Download the notebook (.ipynb)
Every step of an agent resends the whole conversation, so a long task gets slower and more expensive with every step, and eventually it does not fit. Long contexts also make models worse at using what is in them. This notebook runs one long task, then tries the standard ways of keeping the context small and checks what each one costs in tokens and in correctness:
- stored against sent: the full record, and the request built from it each step;
- counting tokens: where the tokens of a request go;
- a sliding window, and the bug in the obvious version;
- compaction: old tool outputs become short stubs;
- summarisation: old steps become a summary;
- when to act: one small function you can replace;
- four strategies on the same task, compared.
Which model answers here?
With no
MODELset, the offline policy model runs the task with a rule written for this notebook. It reads one file per step, and it works out what it has already done the way any model must: from what is still in the request. That makes the effect of each strategy visible, and it is the point of the notebook. A real model’s failures are less tidy. It may repeat work, stop early, or fill a gap with a guess, but the causes are the same. The summaries are written by a rule that copies numbers with a regular expression. A real model writes prose, and it can drop or change a number.
from agentlab.nbsetup import setup
nb = setup("06a_context_management", packs=["context"])
llm = nb.llmLLM backend
offline policy model (deterministic, rule-based, no API key used)
1. One long task, and what each step sends
The task is an audit: list every amount of money in two folders of the handbook from
Module 5. The agent has the file tools from Notebook 5b and has to read twelve files, one
per step. ContextManager is the before_llm callback this notebook is about. With
strategy="none" it changes nothing and only logs the size of every request.
from agentlab import Agent
from agentlab.memory import ContextManager
from agentlab.rag import FileTools, handbook_dir
files = FileTools(handbook_dir()) # the agent only reads, so no copy is needed
TASK = "List every amount of money in the travel and expenses folders, file by file."
INSTRUCTIONS = ("You audit the company handbook with the file tools. "
"Read every file you need.")
BUDGET = 1500 # tokens we are willing to send in one request
def audit_agent(manager: ContextManager, max_steps: int = 24) -> Agent:
return Agent(model=llm, tools=files.tools(), instructions=INSTRUCTIONS,
max_steps=max_steps, before_llm_callbacks=[manager])
first_call = len(llm.calls)
unmanaged = ContextManager(strategy="none", budget=BUDGET)
result = await audit_agent(unmanaged).run(TASK)
calls = llm.calls[first_call:] # (request, response) for every step of this run
print(f"status: {result.status}, steps: {result.context.current_step}\n")
print(result.output)status: complete, steps: 14 I found 27 amounts of money in 9 files: - travel/travel-booking.md: USD 2,000; USD 40 - travel/travel-currency.md: NOK 1,050; USD 100 - travel/travel-ground-transport.md: NOK 230; EUR 2; SGD 2.50; USD 10.50; USD 0.65 - travel/travel-lodging.md: USD 210; NOK 1,800; EUR 160; SGD 280; CAD 250; USD 200 - travel/travel-per-diem.md: USD 65; NOK 750; EUR 55; SGD 85; CAD 75 - expenses/expenses-client-meals.md: USD 90; USD 75 - expenses/expenses-home-office.md: USD 600; USD 150 - expenses/expenses-learning-budget.md: USD 1,500; USD 500 - expenses/expenses-submitting.md: USD 25 No amounts in: travel/travel-safety.md, travel/travel-visas.md, expenses/expenses-corporate-card.md.
The answer is complete. Here is what it cost, step by step. Each request contains every earlier call and result:
from agentlab.memory import count_tokens, tool_output_tokens
print(f"{'step':>4} {'items':>6} {'tokens':>7} {'tool results':>18} then the model")
for step, (request, response) in enumerate(calls, 1):
did = ", ".join(c.name for c in response.tool_calls) or "answered"
tokens, tool = count_tokens(request), tool_output_tokens(request)
share = f"{tool:,} ({tool / tokens:.0%})"
print(f"{step:4d} {len(request.contents):6d} {tokens:7,} {share:>18} {did}")
total_unmanaged = sum(count_tokens(r) for r, _ in calls)
print(f"\ninput tokens over the whole run: {total_unmanaged:,}")step items tokens tool results then the model 1 1 388 0 (0%) list_files, list_files 2 5 539 88 (16%) read_file 3 7 1,195 706 (59%) read_file 4 9 1,439 912 (63%) read_file 5 11 1,720 1,153 (67%) read_file 6 13 1,984 1,379 (70%) read_file 7 15 2,242 1,599 (71%) read_file 8 17 2,494 1,814 (73%) read_file 9 19 2,691 1,974 (73%) read_file 10 21 2,887 2,130 (74%) read_file 11 23 3,054 2,257 (74%) read_file 12 25 3,244 2,407 (74%) read_file 13 27 3,438 2,560 (74%) read_file 14 29 3,645 2,728 (75%) answered input tokens over the whole run: 30,960
Two different things are growing here, and it helps to keep them apart:
context.events the full record of the run: only ever appended to
| (used for logs, replay, sessions and evaluation)
| every step: context.contents() -> a new LlmRequest
v
before_llm callbacks ContextManager may drop, stub or summarise items here
|
v
the request what the model sees on this step; the events are unchangedContext management only ever edits the request. The record stays complete, so a run can be inspected afterwards and a mistake in the context strategy never destroys data.
print("events stored:", len(result.context.events),
"| items in the record:", len(result.context.contents()))events stored: 28 | items in the record: 30
2. Where the tokens go
A request is the system prompt, the tool schemas, and the messages. Splitting the last request of the run by role shows what is worth shrinking:
import json
from collections import Counter
from agentlab.llm.base import build_messages, tool_definitions
from agentlab.llm.pricing import MESSAGE_OVERHEAD, estimate_tokens
last_request = calls[-1][0]
parts = Counter()
for m in build_messages(last_request):
role = {"system": "system prompt", "user": "user message", "tool": "tool results",
"assistant": "tool calls"}[m["role"]]
parts[role] += MESSAGE_OVERHEAD + estimate_tokens(m["content"] or "")
if m.get("tool_calls"):
parts[role] += estimate_tokens(json.dumps(m["tool_calls"]))
parts["tool schemas"] = estimate_tokens(json.dumps(tool_definitions(last_request)))
total = sum(parts.values())
for name, n in parts.most_common():
print(f"{name:14s} {n:6,} tokens {n / total:6.1%}")
print(f"{'total':14s} {total:6,} tokens (count_tokens says {count_tokens(last_request):,})")tool results 2,728 tokens 74.8% tool calls 529 tokens 14.5% tool schemas 341 tokens 9.4% system prompt 24 tokens 0.7% user message 23 tokens 0.6% total 3,645 tokens (count_tokens says 3,645)
Tool results are most of it, and that is typical of agents: what tools return outweighs what people type. The counts are estimates at about four bytes per token. Real tokenizers differ by model (Notebook 2a), and providers offer a token-counting call when you need the exact number before sending.
3. A sliding window, and the bug in the obvious version
The simplest strategy keeps the task (everything up to the first user message) and the
last
from agentlab.memory import orphaned_results, sliding_window
record = result.context.contents()
naive = record[:1] + record[-8:]
print("naive window starts with a", type(naive[1]).__name__,
"| results whose call is missing:", orphaned_results(naive))naive window starts with a ToolResult | results whose call is missing: ['call_0010']
The cut fell between a tool call and its result, so the window starts with a result
whose call is gone. Every major API rejects that request outright. A message with role
tool must answer a call in the message before it. sliding_window moves the cut
forward past any such result:
safe = sliding_window(record, keep_last=8)
print("safe window starts with a", type(safe[1]).__name__,
"| results whose call is missing:", orphaned_results(safe),
f"| keeps {len(safe)} of {len(record)} items")safe window starts with a ToolCall | results whose call is missing: [] | keeps 8 of 30 items
4. Compaction: keep the call, drop the bulky output
A tool result is usually needed right after it arrives and rarely later. Compaction replaces every result except the newest few with a one-line stub that says what the call was and how to get the content back. The call stays, so the model still sees what it has done.
from agentlab import LlmRequest, ToolResult
from agentlab.memory import compact_tool_results
def tokens_of(contents) -> int:
return count_tokens(LlmRequest(instructions=[INSTRUCTIONS], contents=list(contents),
tools=files.tools()))
compacted = compact_tool_results(record, keep_recent=2)
print(f"full record: {tokens_of(record):,} tokens, "
f"compacted: {tokens_of(compacted):,} tokens")
stub = next(x for x in compacted if isinstance(x, ToolResult) and x.name == "read_file")
print(stub.content[0])full record: 3,818 tokens, compacted: 1,825 tokens
[compacted: read_file({"path": "travel/travel-booking.md"}) returned 2,454 characters; call it again if needed]
Compaction is cheap and needs no model call. It is also recoverable: the model can call the tool again for any stubbed result. Its weakness is the task we are running. An audit needs details from early results at the very end.
5. Summarisation: replace old steps with a summary
Summarisation asks a model to fold the old part of the history into a short text. The prompt (adapted from the book’s context optimiser) asks for key findings with exact numbers, the work done, and what is still to do. Here it summarises the first six steps of the run (fourteen items: two listings and five files read):
from agentlab.memory import SUMMARY_PROMPT, summarize_history
print(SUMMARY_PROMPT.split("\n")[0][:92], "...\n")
summary = await summarize_history(llm, record[1:15], task=TASK, preview=4000)
print(summary)[context-summary] You are summarizing the progress of an AI agent so it can keep ... Key findings: - travel/travel-booking.md: USD 2,000; USD 40 - travel/travel-currency.md: NOK 1,050; USD 100 - travel/travel-ground-transport.md: NOK 230; EUR 2; SGD 2.50; USD 10.50; USD 0.65 - travel/travel-lodging.md: USD 210; NOK 1,800; EUR 160; SGD 280; CAD 250; USD 200 - travel/travel-per-diem.md: USD 65; NOK 750; EUR 55; SGD 85; CAD 75 Work done: - listed travel: travel-booking.md, travel-currency.md, travel-ground-transport.md, travel-lodging.md, travel-per-diem.md, travel-safety.md, travel-visas.md - listed expenses: expenses-client-meals.md, expenses-corporate-card.md, expenses-home-office.md, expenses-learning-budget.md, expenses-submitting.md - read: travel/travel-booking.md, travel/travel-currency.md, travel/travel-ground-transport.md, travel/travel-lodging.md, travel/travel-per-diem.md Still to do: - read 7 more files: travel/travel-safety.md, travel/travel-visas.md, expenses/expenses-client-meals.md, expenses/expenses-corporate-card.md, expenses/expenses-home-office.md, expenses/expenses-learning-budget.md, expenses/expenses-submitting.md - then answer with every amount of money, file by file
Fourteen items became a few lines, and the numbers the task needs are all still there.
The rest of the record can now be replaced by this text. Summarisation costs an extra
model call each time, and a summary is only as good as its writer. The offline rule
copies every amount with a regular expression. A real model may round “NOK 1,050” or
leave out a file it judged unimportant. The prompt says “keep every number” for that
reason. preview=4000 lets the summariser see each result in full. With the default of
1,500 characters, the end of the longest file would be cut off before the summariser
ever saw it.
6. When to act: one function you can replace
Every strategy needs a trigger. ContextManager measures each request and asks
should_compact whether to act. The function is deliberately small. Its docstring
lists three reasonable policies and what each one trades away:
import inspect
from agentlab.memory import should_compact
print(inspect.getsource(should_compact))def should_compact(stats: ContextStats) -> bool:
"""Decide whether to shrink this request before it is sent. Replace the body to change policy.
The default acts when the request reaches 80 percent of the budget. Three reasonable
policies, and what each trades away:
1. Token budget (the default): ``stats.tokens >= 0.8 * stats.budget``.
+ Tied to what actually costs money and what overflows the context window.
- Needs a token count on every call, and fires late: one large reduction instead of
several small ones.
2. Turn count: ``stats.turns > 0 and stats.turns % 4 == 0``.
+ Trivial and predictable; the request prefix changes only at known steps, which
keeps a provider's prompt cache warm in between.
- Blind to size: one 50,000-token result goes through untouched, while a short run
is compacted for nothing.
3. Share of the window taken by tool outputs:
``stats.tool_share >= 0.6 and stats.tokens >= 0.5 * stats.budget``.
+ Targets exactly what compaction removes (old tool results), and leaves
conversation-heavy contexts alone.
- A context full of long user or assistant text never triggers; two thresholds to tune.
Whatever you choose, the reduction itself is done by ``ContextManager``; this function
only says *when*.
"""
return stats.tokens >= 0.8 * stats.budget
Here is what it decides on each request of the unmanaged run, next to the two alternatives from its docstring written as one-line functions:
from agentlab.memory import context_stats
policies = {
"should_compact": should_compact,
"every 4 turns": lambda s: s.turns > 0 and s.turns % 4 == 0,
"tool share": lambda s: s.tool_share >= 0.6 and s.tokens >= 0.5 * s.budget,
}
header = "".join(f"{name:>16}" for name in policies)
print(f"{'step':>4} {'tokens':>7} {'tool share':>11} {header}")
for step, (request, _) in enumerate(calls, 1):
stats = context_stats(request, turns=step - 1, budget=BUDGET)
marks = "".join(f"{'act' if decide(stats) else '.':>16}"
for decide in policies.values())
print(f"{step:4d} {stats.tokens:7,} {stats.tool_share:11.0%} {marks}")step tokens tool share should_compact every 4 turns tool share 1 388 0% . . . 2 539 16% . . . 3 1,195 59% . . . 4 1,439 63% act . act 5 1,720 67% act act act 6 1,984 70% act . act 7 2,242 71% act . act 8 2,494 73% act . act 9 2,691 73% act act act 10 2,887 74% act . act 11 3,054 74% act . act 12 3,244 74% act . act 13 3,438 74% act act act 14 3,645 75% act . act
The first column comes from should_compact in agentlab/memory/context.py, and it is
the trigger for every run in the next section. Replace its body with one of the other
policies, or one of your own, and re-run the notebook: this table, the comparison and
the plot below all change with it.
7. Four strategies on the same task
Each strategy runs the audit from scratch, with should_compact deciding when to act.
The answer key comes from reading the files directly:
import re
AMOUNT = re.compile(r"\b(?:USD|NOK|EUR|SGD|CAD) ?\d[\d,]*(?:\.\d+)?")
def amounts_in(text: str) -> set[str]:
return {m.group(0).rstrip(",") for m in AMOUNT.finditer(text)}
answer_key = set()
for folder in ("travel", "expenses"):
for name in files.list_files(folder).split()[2:]:
path = f"{folder}/{name}"
answer_key |= {(path, a) for a in amounts_in(files.read_file(path))}
def found_in(answer: str | None) -> set:
lines = re.finditer(r"^- (\S+\.md): (.*)$", answer or "", flags=re.M)
return {(m.group(1), a) for m in lines for a in amounts_in(m.group(2))}
print(f"{len(answer_key)} amounts in {len({p for p, _ in answer_key})} files")27 amounts in 9 files
from agentlab.memory import SUMMARY_MARKER
runs = {}
for strategy in ("none", "window", "compact", "summarize"):
manager = ContextManager(strategy=strategy, budget=BUDGET, llm=llm, keep_last=8,
keep_recent=2, preview=4000)
first_call = len(llm.calls)
res = await audit_agent(manager).run(TASK)
summariser = [r for r, _ in llm.calls[first_call:]
if r.instructions and r.instructions[0].startswith(SUMMARY_MARKER)]
runs[strategy] = {"result": res, "log": manager.log,
"summariser": sum(count_tokens(r) for r in summariser)}
print(f"{'strategy':10s}{'status':>10}{'steps':>6}{'amounts':>9}{'agent tokens':>14}"
f"{'summariser':>12}{'largest':>9}")
for strategy, run in runs.items():
res, log = run["result"], run["log"]
found = len(found_in(res.output) & answer_key)
print(f"{strategy:10s}{res.status:>10}{res.context.current_step:6d}"
f"{found:5d}/{len(answer_key)}{sum(r['sent'] for r in log):14,}"
f"{run['summariser']:12,}{max(r['sent'] for r in log):9,}")strategy status steps amounts agent tokens summariser largest none complete 14 27/27 30,960 0 3,645 window max_steps 24 0/27 31,301 0 1,569 compact complete 14 3/27 17,288 0 1,652 summarize complete 14 27/27 13,176 5,150 1,195
Four strategies, four different outcomes:
- none is correct and the most expensive, and its largest request is more than twice the budget. With longer files it would not fit at all.
- window never finishes. Once the folder listings and the first reads slid out of the window, the agent could no longer tell what it had done, so it listed the folders again and re-read the same files until the step budget ran out:
window_steps = runs["window"]["result"].context.events
names = [c.name.replace("_files", "").replace("_file", "") for e in window_steps
for c in e.content if getattr(c, "type", "") == "tool_call"]
print(" ".join(names[:20]), "...")list list read read read list list read read read list list read read read list list read read read ...
- compact finishes with a little over half the tokens, but the answer is incomplete. The stubs told the agent which files it had read, but not what was in them. The offline rule says so in its answer. A real model might re-read the stubbed files, which costs the tokens again, or, worse, answer from what it can still see without saying so.
- summarize is complete and sends the fewest tokens to the agent. It pays for that with the summariser’s own calls (even counting them, it is far below the unmanaged run), and it trusts the summariser with every number.
None of these is best in general. A task that needs early details at the end (aggregation, audits, research) needs notes or a summary. A task where only the latest state matters (fixing a failing test, browsing) does well with plain compaction. Production agents often combine them: compact first, because it is cheap and recoverable, and summarise when compaction is no longer enough.
import matplotlib.pyplot as plt
colours = {"none": "#81796f", "window": "#b5523b", "compact": "#2c5f9e",
"summarize": "#2c7d54"}
fig, ax = plt.subplots(figsize=(6.4, 3.8))
for strategy, run in runs.items():
steps = [r["step"] for r in run["log"]]
sent = [r["sent"] for r in run["log"]]
ax.plot(steps, sent, color=colours[strategy], label=strategy, linewidth=1.6)
acted = [(r["step"], r["sent"]) for r in run["log"] if r["acted"]]
if acted:
ax.scatter(*zip(*acted), color=colours[strategy], marker="x", s=22, zorder=3)
ax.axhline(BUDGET, color="#81796f", linestyle="--", linewidth=1)
ax.text(26.4, BUDGET + 40, "budget", ha="right", va="bottom", fontsize=8, color="#81796f")
ax.set_xlabel("step")
ax.set_ylabel("tokens sent (estimated)")
ax.set_xlim(0.5, 26.5)
ax.set_ylim(0, 4000)
ax.legend(frameon=False, loc="upper left", ncol=2)
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
plt.show()
Tokens sent to the agent on each step of the audit, per strategy. Crosses mark the steps where should_compact decided to act; the dashed line is the budget. The window run continues to step 24 because it never finishes.
The unmanaged run grows steadily. The window and compaction runs stay close to the budget, sometimes just above it, because the newest results are always kept whole and a single file can be large. Compaction creeps upward as its stubs accumulate. The summarising run saw-tooths: it shrinks each time a summary replaces the old steps, then grows again until the next one.
Try this
- Replace the body of
should_compactinagentlab/memory/context.pywith the tool-share policy from its docstring and re-run the notebook. Which strategy gains, and which loses?- Run compaction with
keep_recent=12. Is the answer complete now? What happened to the token savings?- Set
preview=300for the summariser. How many of the 27 amounts survive? This is a cheap way to see how a lossy summary fails silently.- Change
keep_lastof the window to 40. Does it still loop? Why does a window that large behave exactly likestrategy="none"on this task?- With a live model, run the
compactstrategy. Does the model callread_fileagain for the stubbed files, or does it answer from what it can see?
nb.usage()| model calls | input tokens | output tokens | cost |
|---|---|---|---|
| 87 (fake: 87) | ≈ 130,725 | ≈ 3,425 | ≈ USD 0.1444 (reference price) |