learn-ai-agents-with-phoebe / Builder session 4 of 10
Learn AI Agents with Phoebe · Builder track · Session 4 of 10

Memory and context

In b1 you saw that the context window IS the agent's working state - every thought, action and observation piles into it, turn after turn. Tonight you learn what happens when that pile gets too tall: findings vanish, standing instructions silently fall away, and the agent starts contradicting its own earlier steps. You will watch the Daybreak Ops Agent lose a number it fetched correctly three steps earlier, then build the memory toolkit that stops it - trimming, compaction, a scratchpad, and the long-term stores real frameworks ship.

🟡 Medium Builder track Python · Claude API + Ollama path 45 min
0-3 · Welcome 3-18 · Context is the state 18-42 · Build-along: memory that survives 42-45 · Q&A
Part 1 · covers Anthropic context management, LangGraph MessagesState, HF Unit 1 recap

The context window IS the agent's memory 7 min live

b1's Thought → Action → Observation cycle has a hidden bill: every turn appends to the context window, and the window is finite. A long task grows its own history until something has to give. There are exactly two ways it gives - overflow (the task blows past the window and the run dies or degrades) and eviction (early turns get trimmed away to make room, taking early findings and standing instructions with them). Both are memory failures. Neither is a "bad model".

Turn 2 exclude refunds T1·A1 O1 plenty of room left Turn 6 exclude refunds T2·A2 O2 T3·A3 O3 T4·A4 O4 filling up Turn 11 exclude refunds T5·A5 O5 T6·A6 O6 T7·A7 O7 ...more turns evicted - trimmed to make room the answer silently changes: refunds are back in the total The agent never says "I forgot". It just answers as if the instruction never existed - fluent, confident, wrong. Overflow kills the run loudly. Eviction corrupts it silently. The silent one is the dangerous one.
🔍 Click to zoom - the window fills turn by turn until "exclude refunds" falls off the edge, and the answer silently changes
LiveTwo ways a context dies4 min▶

Name the failure before you fix it - same habit as the levers in b1:

  • Overflow - a long task (big tool results, many turns) exceeds the window. Symptoms: API errors, truncated inputs, sudden quality cliffs late in a run. Loud, easy to spot.
  • Eviction - to keep running, old turns get dropped or trimmed. Symptoms: the agent re-fetches things it already knew, contradicts its own earlier finding, or ignores an instruction given at turn 1. Quiet, easy to miss - this is the memory-off signature you will reproduce in the demo.
Real world

The standing instruction that expired. An ops team told their agent at the start of every month: "exclude refunded orders from revenue figures." Ten turns of ticket triage later, month-end numbers came out higher than finance's. Nothing crashed and no error was logged - the instruction had simply been evicted mid-run, and every later answer quietly included refunds again.

Self-studyWhy "just use a bigger window" is not the fix3 min read▶

Bigger windows delay the problem; they do not remove it. Three reasons the toolkit still matters:

  • Cost and latency scale with context - every turn re-reads the whole history. A lean context is a cheaper, faster agent.
  • Long tasks are unbounded - an agent that monitors tickets all day will outgrow any window eventually.
  • Runs end - the window empties when the process exits. Anything the agent should know NEXT run needs long-term memory: a store, a file, a session - never the window itself.
Part 2 · covers LangGraph checkpointing + Store, LangChain Academy M2+M5, OpenAI SDK Sessions

The memory toolkit, short-term to long-term 8 min live

Every serious stack ships the same five techniques under different names. Short-term techniques manage the window inside one run; long-term techniques survive across runs. Learn the technique, and every framework's memory docs become familiar.

What long-term memory adds to a run that ends sessions checkpoint + store LONG-TERM MEMORY sessions, checkpointing + store SHORT-TERM MEMORY trimming, compaction, scratchpad = findings survive restarts Short-term keeps a run coherent; long-term memory is what it still knows after the run ends.
🔍 Click to zoom - long-term memory adds survival across runs, not just a bigger window
TechniqueWhat it doesTermWhere you meet it
Message trimming / filteringDrop or truncate old turns (oldest-first, or filter big tool results) to stay under budgetShortRaw loops · LangGraph message state helpers
CompactionSummarize the history so far, replace old turns with the summary, keep goingShortAnthropic context management · you build it below
ScratchpadAgent writes findings to a file or note it re-reads every turn - findings survive evictionShortAnthropic memory tool pattern · self-study card
SessionsPersistent conversation memory across runs - the SDK stores and replays history for youLongOpenAI Agents SDK "Sessions" primitive
Checkpointing + StoreCheckpointing persists state through failures mid-run; Store is long-term memory across threadsLongLangGraph · Academy modules 2 and 5
LiveCompaction by hand6 min▶

Compaction is one extra API call: when the estimated token count crosses a threshold, ask the model to summarize the history - keeping every number, finding and standing instruction - then replace the old turns with that summary and continue. Bolt this onto your b2 loop:

from anthropic import Anthropic

client = Anthropic()
THRESHOLD = 8000  # rough token budget before we compact

def estimate_tokens(messages):
    return sum(len(str(m["content"])) for m in messages) // 4

def maybe_compact(messages):
    if estimate_tokens(messages) < THRESHOLD:
        return messages
    transcript = "\n".join(f"{m['role']}: {m['content']}" for m in messages[:-4])
    summary = client.messages.create(
        model="claude-opus-5",
        max_tokens=500,
        messages=[{"role": "user", "content":
            "Summarize this agent transcript for the agent itself. "
            "Keep EVERY number, finding, and standing instruction:\n\n"
            + transcript}],
    ).content[0].text
    return ([{"role": "user",
              "content": "[Summary of earlier turns]\n" + summary}]
            + messages[-4:])  # keep the freshest turns verbatim

The summarize-then-continue trade: you spend one call and lose verbatim detail, but the numbers, findings and instructions travel forward instead of falling off the edge. The summary prompt is the whole game - "keep every standing instruction" is what saves "exclude refunds".

Self-studyScratchpad pattern4 min read▶

A scratchpad moves key findings OUT of the message history entirely. The agent appends findings to a notes list (or a file), and the loop injects the notes into the system prompt every turn - so even aggressive trimming cannot evict them:

notes = []  # lives OUTSIDE messages - trimming cannot touch it

def remember(finding):
    notes.append(finding)  # e.g. "Feb completed revenue = $271"

def system_prompt():
    return (BASE_PROMPT
        + "\n\nScratchpad - re-read before every step:\n"
        + "\n".join("- " + n for n in notes))

# in the loop: expose remember() as a tool, and rebuild
# the system prompt from notes on every messages.create call

Expose remember as a tool and the agent decides what is worth keeping - the same move Anthropic's memory tool and file-based agent memory make. Write one note per confirmed finding, not per raw tool result, or the scratchpad becomes a second overflowing context.

Demo 1 of 2

Watch the agent lose its own finding ★ 10 min · everyone runs it

The founder asks: "Diagnose the March dip." Below, the Daybreak Ops Agent runs that task with tools and planning on but memory OFF. Step through slowly: it fetches February correctly - $271 - then, at the synthesis step, the figure is gone and the agent contradicts the very step it just ran. That is the memory-off signature: the agent argues with its own earlier finding.

Step through with memory off. Find the step where query_sales("2026-02") returns $271 - the fetch itself is perfect.

Keep stepping to the synthesis. The February figure has been evicted, and the conclusion contradicts the step you just watched. No error, no apology.

Same task, same tools - the difference is memory ✗ Memory off Fetches Feb revenue: $271 Synthesis: figure is gone Contradicts its own step ✓ Memory on Fetches Feb revenue: $271 Synthesis holds $271, $150 Diagnosis names real causes Not a model problem, not a tools problem - a memory problem. Name the lever first.
🔍 Click to zoom - memory on: the agent stops arguing with its own findings

Toggle Memory on and step through again. Same task, same tools - now the synthesis holds onto $271 → $150 all the way to the answer.

Say the diagnosis out loud: not a model problem, not a tools problem - a memory problem. Name the lever first.

How to spot eviction in your own traces Grep the trace for the finding, then for the final answer. If a number appears in a 📦 tool result but the 💬 answer disagrees with it - and no later tool call superseded it - memory is your lever. Re-fetching data it already fetched is the same signature in a cheaper disguise.
Demo 2 of 2 · rung moment

Rung 2 on the ladder: 5/12 becomes 7/12 ★ 6 min · explore

Back to the 12-task scorecard from b1. Tools alone scored 5/12. Turn memory on with it and the score climbs to exactly 7/12 - rung 2 of the course ladder (1 → 5 → 7 → 10 → 12). Read WHICH two tasks flipped and why they are both memory-shaped.

Check the score reads 7/12 with tools + memory on. Two tasks flipped from red to ✓ versus b2's rung.

Flipped task 1: the February-vs-March comparison - a multi-step task where the first fetch must survive until the second one lands.

Flipped task 2: the standing exclude-refunds instruction - a rule given once, early, that must still bind many turns later.

Read the failure text on the tasks still red: diagnoses and reports need planning (b5); the outward-acting ones need guardrails (b7).

★ What you walk out with today The two context failure modes (overflow, eviction) and the memory-off signature - an agent contradicting its own earlier finding. A working compaction function and a scratchpad pattern you can bolt onto the b2 loop tonight. The short-term vs long-term split: window techniques inside a run, Sessions / checkpointing + Store across runs. And rung 2, banked: 7/12.
Homework

Try it yourself - this week ◐ 25-35 min total

Source material

Official sources covered

This session teaches the working core of the memory and context-management guidance across the major agent stacks. Certificates, videos, and graded assessments stay on the official sites (linked each session). This page covers:

✓LangGraph docs - checkpointing, Store, MessagesStateShort-term state vs long-term Store · checkpointing persists through failures mid-run
✓LangChain Academy "Intro to LangGraph" - modules 2 + 5State and memory · long-term memory (Store) · taught here framework-neutral
◐OpenAI Agents SDK - SessionsPersistent memory across runs · positioned in the toolkit table, not built here
◐Anthropic context-management docsCompaction and memory-tool patterns · the by-hand version you built tonight
Check yourself

Three questions before you go 🎯 ◐ 90 seconds

1 · Mid-task, the agent's final answer contradicts a number it fetched correctly three steps earlier. Which lever was off?

Contradicting your own earlier finding is the memory-off signature. Tools-off invents numbers that were never in any result; planning-off stops after one shallow call. The fetch was real - keeping it was the failure.

2 · What exactly is compaction?

Compaction is summarize-then-continue: one extra model call that carries numbers, findings and standing instructions forward in condensed form. Plain deletion of old messages is trimming - cheaper, but it is exactly how "exclude refunds" gets lost.

3 · Where does the short-term vs long-term memory line actually sit?

The window empties when the run ends - trimming, compaction and scratchpads all manage life inside one run. Anything the agent must know next run needs a store: OpenAI SDK Sessions, LangGraph Store, or your own file.

Builder session 4 cheat sheet · pin this

The core factThe context window IS the agent's memory - every thought, action and observation accumulates in it, and it is finite.
Two failure modesOverflow (long tasks blow the window, loud) and eviction (early findings and instructions trimmed away, silent).
Memory-off signatureThe agent contradicts its own earlier finding, or ignores a standing instruction given at turn 1. Fluent, confident, wrong.
TrimmingDrop or truncate old turns to stay under budget. Cheap - and exactly how standing instructions get lost.
CompactionSummarize-then-continue: one messages.create call condenses history, replaces old turns, keeps every number and instruction.
ScratchpadAgent writes findings to notes outside the messages; the loop re-injects them every turn. Eviction-proof by construction.
Long-term memoryAcross runs: OpenAI SDK Sessions · LangGraph checkpointing (survives failures) + Store (long-term). The window never persists.
Rung 2Tools + memory = 7/12. Flipped: the Feb-vs-Mar comparison and the standing exclude-refunds rule. Planning unlocks rung 3.