Learning path: Prompt and Context Engineering · Step 8 of 8
Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
A support agent forgets the customer's name, order and contact choice after twenty turns and fails 0 of 4 checks. Measure the window, clear old tool output, compact old turns and keep a notes file, and the same chat passes 4 of 4 with 470 tokens instead of 2,945.
What you will learn
- Measure the tokens an agent sends on every call and see where the window fills up
- Clear old tool results and compact old turns so the window stays small
- Keep stable facts in a notes file outside the window and put them first
- Prove the fix with a before and after eval
Before you start
- Basic Python
- Context Engineering: What Belongs in the Context Window
A support agent works fine for a few turns. Twenty turns later it can't tell you the customer's name, which order the chat is about or how she asked to be contacted, and it has stopped signing its replies. Nothing is wrong with the model. Its context window filled up, and the important parts fell off.
In this hands-on lesson you'll measure that, then fix it with three moves: clear old tool results, compact old turns and keep a small notes file. Then you'll prove the fix with a before and after eval: 0 of 4 checks become 4 of 4. If you haven't read it yet, Context Engineering: What Belongs in the Window covers the ideas on a single turn. Here we watch a window over twenty.
No API key needed. The code runs with a stand-in test model that has a small 3,000-token window, so the problem shows up within twenty turns. The stand-in only knows what is in the messages it is sent, like a real model. Set LLM_MODEL and your key in .env (for example ANTHROPIC_API_KEY=your-key-here), run pip install langchain langchain-anthropic, and the same code calls a real model.
A small desk
Imagine working at a small desk where only so many papers fit. Every new page you put down pushes the oldest one off the back, and you never notice which one fell. A sensible person keeps a small notebook for the things that matter, such as the customer's name and order number. And old printouts they no longer need get replaced by a one-line summary.
The context window is that desk (more on the desk itself in LLM Tokens, Context Windows and Cost). Our job is to decide what stays on it.
Twenty turns later, it forgot
The project plays a scripted chat from data/chat.json. The customer, Maya, gives her name and order number in the very first message and asks to be contacted by email in the second. Then she asks about several orders, again and again:
"turns": [
"Hi, my name is Maya and my order number is 4390.",
"Please contact me by email, not by phone.",
"What is the status of order 4390?",
"Can you check order 4391 for my brother?",
"And order 4392?",
...
"Great, thanks."
]
After the twenty turns, the eval asks three probe questions and checks one rule from the system prompt: sign every reply with - Ana, Support. Here is the naive block of the output:
python demo.py compare
naive 0/4 checks passed
FAIL Which order did I open this chat about? Sorry, I don't know which order you mean.
FAIL What is my name? Sorry, I don't know your name.
FAIL How should you contact me? Sorry, I don't know how you prefer to be contacted.
FAIL signs every probe reply
The naive agent passes zero of four. It doesn't know the order, the name or the contact choice, and it stopped signing.
The agent: remember, lookup, respond
The agent is a small three-step loop, run once per user turn. It's built as a LangGraph graph in app/agent.py, but you don't need to know any agent framework to follow it. Think of three boxes in a row:
def build(strategy: str, notes_path: Path, model=None):
model = model or get_model()
def remember(state: State):
if strategy == "engineered":
update_notes(notes_path, state["history"][-1].content)
return {}
def lookup(state: State):
oid = order_id_in(state["history"][-1].content)
if not oid:
return {}
call = {"name": "lookup_order", "args": {"order_id": oid}, "id": f"call_{len(state['history'])}"}
return {"history": [AIMessage("", tool_calls=[call]), ToolMessage(lookup_order(oid), tool_call_id=call["id"])]}
def respond(state: State):
window = (context.engineered(state["history"], notes_text(notes_path)) if strategy == "engineered"
else context.naive(state["history"]))
return {"history": [model.invoke(window)], "sent": [context.tokens(window)]}
g = StateGraph(State)
g.add_node("remember", remember)
g.add_node("lookup", lookup)
g.add_node("respond", respond)
g.add_edge(START, "remember")
g.add_edge("remember", "lookup")
g.add_edge("lookup", "respond")
g.add_edge("respond", END)
return g.compile()
(An excerpt: the file also imports the message classes, StateGraph, the tool and the notes helpers, and defines the State the steps share.)
- remember: only the engineered agent uses this step, to write notes. We'll come back to it.
- lookup: if the message names an order, the tool reads that order from the mock data (a big JSON block with shipping events and the return policy), and the result goes into the history.
- respond: build the window and call the model. It also records how many tokens that call sent.
The only difference between the two agents is how respond builds the window: context.naive(...) or context.engineered(...).
Measure before you fix
app/context.py counts tokens with tiktoken and shows what happens when nobody manages the window:
import tiktoken
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage, ToolMessage
ENC = tiktoken.get_encoding("cl100k_base")
WINDOW = 3000 # the stand-in's context limit in tokens (small on purpose, so the problem shows up in 20 turns)
SYSTEM = SystemMessage("You are Ana from the shop's support team. Sign every reply with: - Ana, Support")
def tokens(messages) -> int:
return sum(len(ENC.encode(str(m.content))) for m in messages)
def fit(messages, limit: int = WINDOW):
"""Drop the oldest messages until the rest fits. This is what happens when nobody manages the window."""
kept = list(messages)
while tokens(kept) > limit and len(kept) > 1:
kept.pop(0)
return kept
def naive(history):
return fit([SYSTEM, *history])
The naive window is the system prompt plus the whole history. When that's too big, fit drops messages from the front. Now count the tokens on every call:
python demo.py naive
naive tokens per call: 34 53 367 692 1011 1037 1345 1369 1683 2006 2031 2341 2364 2679 2999 2948 2939 2938 2920 2939
engineered tokens per call: 52 77 391 435 460 465 453 433 431 453 442 455 437 432 452 450 475 474 472 460
window limit: 3000 tokens (cl100k_base count)
From call fifteen on, the window is full. Every new message pushes the oldest ones out, and the oldest ones are exactly where Maya told us who she is.
What fills the window on the last call?
inspect rebuilds the window from the history after turn twenty, so it also counts the agent's final reply. That's why its totals are a little higher than the last numbers in the row above.
python demo.py inspect
naive 2945 tokens: system 0, user 97, assistant 209, tool results 2639
engineered 470 tokens: system 43, user 43, assistant 68, tool results 316
In the naive window the system prompt is zero tokens: it fell off the front. That's why the replies stopped being signed. User messages are only 97 tokens, and tool results take 2,639, about nine tenths of the window. So the naive agent didn't get dumber. Its window filled with old tool output, and the important parts fell off.
The fix, one move at a time
1. Clear old tool results
def clear_old_tool_results(history, keep_last: int = 1):
"""Replace every tool result but the newest with a one-line stub."""
tool_idx = [i for i, m in enumerate(history) if isinstance(m, ToolMessage)]
old = set(tool_idx[:-keep_last]) if keep_last else set(tool_idx)
return [ToolMessage(f"[cleared: lookup_order result, {len(m.content)} chars]", tool_call_id=m.tool_call_id)
if i in old else m for i, m in enumerate(history)]
It finds every tool result except the newest one and swaps each old one for a stub like [cleared: lookup_order result, N chars]. The agent can still see the call happened. If it needs that order again, it can simply look it up again. The stub keeps the tool_call_id, so every tool call still has its matching result.
2. Compact old turns
def compact(history, keep_turns: int = 4):
"""Keep the last few turns word for word; replace the older ones with one short line."""
starts = [i for i, m in enumerate(history) if isinstance(m, HumanMessage)]
if len(starts) <= keep_turns:
return list(history)
cut = starts[-keep_turns]
return [HumanMessage(f"[{len(starts) - keep_turns} earlier turns compacted; stable facts are in the notes]"), *history[cut:]]
The last four turns stay word for word. Everything older becomes one short line saying how many turns were compacted and that the stable facts live in the notes. Which brings us to the third move.
3. Keep stable facts in a notes file
Compacting throws away the first two messages, and those hold the name, the order and the contact choice. So before they go, the remember step copies them out of the window into a small file:
import re
from pathlib import Path
FACTS = {
"name": r"my name is (\w+)",
"order": r"my order number is (\d+)",
"contact": r"contact me by (\w+)",
}
LABELS = {"name": "My name is {}.", "order": "My order number is {}.", "contact": "Please contact me by {}."}
def update_notes(path: Path, user_text: str) -> None:
"""Pull stable facts out of a user message and save them (one line per fact, latest wins)."""
notes = read_notes(path)
for key, pattern in FACTS.items():
m = re.search(pattern, user_text, re.I)
if m:
notes[key] = m.group(1)
path.write_text("".join(f"{k}: {v}\n" for k, v in notes.items()), encoding="utf-8")
def read_notes(path: Path) -> dict[str, str]:
if not path.exists():
return {}
return dict(line.split(": ", 1) for line in path.read_text(encoding="utf-8").splitlines() if ": " in line)
def notes_text(path: Path) -> str:
"""The notes as the sentences the model reads (the customer's own words)."""
return "Notes about this customer: " + " ".join(LABELS[k].format(v) for k, v in read_notes(path).items())
Each user message is checked for three stable facts with simple patterns. They're saved one line each, and the latest value wins. notes_text turns them back into the customer's own sentences for the model to read. After twenty turns the file still holds all three:
python demo.py notes
work\notes_engineered.md:
name: Maya
order: 4390
contact: email
In a real agent you'd decide which facts are stable for your use case. The regex patterns here just keep the demo small and predictable.
Put it together
def engineered(history, notes: str):
"""System prompt and notes first, then compacted history with old tool results cleared."""
return fit([SYSTEM, SystemMessage(notes), *compact(clear_old_tool_results(history))])
The system prompt and the notes come first, then the compacted history with old tool results cleared. fit is still in the chain, but the engineered window never gets near it: the peak is 475 tokens against a limit of 3,000, and a test checks it stays under. That matters, because fit drops from the front, so if it ever fired it would drop the system prompt and the notes first. The facts that matter stay on the desk because the notes are read back from the file on every call and the rest of the window is kept small.
Prove it: before 0/4, after 4/4
"It feels better" isn't proof. The eval in app/evals.py runs the same twenty turns, asks the same three probes and checks the signature on every probe reply:
from langchain_core.messages import AIMessage
from app.agent import CHAT, run_chat
from app.model import SIGNATURE
def score(strategy: str, model=None) -> dict:
asks = [p["ask"] for p in CHAT["probes"]]
state = run_chat(strategy, asks, model=model)
replies = [m.content for m in state["history"][-2 * len(asks):] if isinstance(m, AIMessage)] # one per probe
checks = []
for probe, reply in zip(CHAT["probes"], replies):
checks.append({"check": probe["ask"], "ok": probe["expect"].lower() in reply.lower(), "reply": reply})
checks.append({"check": "signs every probe reply", "ok": all(SIGNATURE in r for r in replies), "reply": ""})
return {"strategy": strategy, "passed": sum(c["ok"] for c in checks), "total": len(checks),
"checks": checks, "sent": state["sent"]}
python demo.py compare
engineered 4/4 checks passed
PASS Which order did I open this chat about? You opened this chat about order 4390. - Ana, Support
PASS What is my name? Your name is Maya. - Ana, Support
PASS How should you contact me? I will contact you by email. - Ana, Support
PASS signs every probe reply
Four out of four. It knows the order is 4390, the name is Maya, the contact is email, and every reply is signed by Ana. The inspect output above shows why: 470 tokens instead of 2,945, with the system prompt still in place. You can also ask your own question after the twenty turns:
python demo.py ask "How should you contact me?"
you : How should you contact me?
agent: I will contact you by email. - Ana, Support
And the five offline tests pass: the naive agent fails the probes, the engineered one passes every check, its window stays under the limit, the notes hold all three facts and exactly one tool result stays whole.
python -m pytest -q
5 passed
Five moves for a long conversation
| Problem | Move | In the project |
|---|---|---|
| You can't see what's in the window | Measure it, in tokens and by kind | tokens(), by_kind(), demo.py naive / inspect |
| Old tool results fill the room | Clear them to a stub | clear_old_tool_results() |
| Old turns pile up | Compact them | compact(keep_turns=4) |
| Key facts fall off | Keep notes outside the window, and put them first | app/notes.py, engineered() |
| Not sure the fix works | Eval before and after | demo.py compare: 0/4 became 4/4 |
Most long-agent failures are context failures, not model failures.
Common mistakes
- Letting the window cut itself. Dropping the oldest messages throws away the system prompt and the first turns, which is usually where the rules and the customer's details are.
- Keeping every tool result whole. Here old order lookups were about nine tenths of the naive window.
- Compacting without notes. If you summarise old turns away and nothing keeps the stable facts, the agent forgets them just as surely.
- Putting notes at the end, or letting the window fill anyway. Put them right after the system prompt, and keep the rest small enough that nothing gets cut. A window that still hits the limit loses its front first.
- Calling it fixed without an eval. Write the probe questions first, run them before and after, and keep them as tests.
Try it yourself
- Ask the engineered agent
python demo.py ask "What is my name?"and read the reply. - Change
keep_turnsincompactto 2 and runpython demo.py compareagain. Does it still pass, and how many tokens does the window use now? - Add a fourth probe to
data/chat.json, such as the item in order 4390, and see which agent can answer it.
The project, README and sample prompts for this lesson are in the StudyEasy AI Community, free to join.
Related course on Udemy
Become an AI Engineer: LLMs, RAG, Agents and MCP
Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)Related posts
The AI Stack in One Picture: Six Layers Every AI Product Is Built From
Every AI product is built from six layers: data, model, retrieval, orchestration, serving and ops, with evals and security across all of them. A restaurant analogy, one request traced through all six, and what an AI engineer actually builds around the model call.
Tokenization: What an LLM Actually Sees When You Type
A language model never sees letters, only token ids. Use tiktoken to watch strawberry become three ids, see a space or a capital change them, fix the letter-counting problem, and compare English, German and Hindi token counts.
LLM Tokens, Context Windows and Cost: What One Question Really Costs
Follow one four-word help desk question that becomes 911 input tokens. Learn what fills the context window, why chat memory grows every turn, how max_tokens cuts a reply, and how to price a call.
What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
A large language model predicts the next token, over and over. That one loop makes it strong at drafting, summarising and classifying, and weak at fresh facts, exact maths, memory and guaranteed truth. See why with a three-line tiktoken script, and learn the fix for each gap.