agentic-ai-course

Module 12 — Context Management for Long-Running Agents

The messages list has grown throughout this entire course, and every module has quietly assumed it fits in the context window. It won’t, forever — a long-running agent eventually accumulates more history than fits, or than is worth paying to resend every turn.

What you’ll learn

The core idea

This is Module 3’s memory pattern, turned around: instead of writing facts out to persist them, you summarize old turns to shrink them.

def compact_history(messages: list[dict]) -> list[dict]:
    if conversation_token_count(messages) < MAX_TOKENS_BEFORE_COMPACTING:
        return messages

    old_messages = messages[:-KEEP_RECENT_MESSAGES]
    recent_messages = messages[-KEEP_RECENT_MESSAGES:]
    summary = summarize_messages(old_messages)

    return [{"role": "user", "content": f"[Earlier conversation summary]: {summary}"}] + recent_messages

The most recent turns stay word-for-word — they’re the most likely to be directly relevant to what happens next, and summarizing them risks losing detail you need immediately. Older turns get compressed into one paragraph that preserves decisions, facts, and open questions, not the exact wording. This trades some fidelity for a bounded, predictable context size — the same trade-off a human making notes during a long meeting makes instinctively.

There’s a real cost here too: every compaction is itself a Claude call, and a bad summary can silently drop something that mattered. This is a mitigation for a real constraint, not a free upgrade — reach for it when a conversation genuinely runs long, not preemptively on every agent.

Run it

pip install -r requirements.txt
export ANTHROPIC_API_KEY=your_key_here
python exercise.py   # after filling in the TODOs
python solution.py   # to compare against a working version

Have a long conversation and watch the printed [N messages, ~X tokens] line — once it crosses the threshold, the next turn compacts and the count drops.

Next

Module 13 — Extended Thinking — giving Claude explicit room to reason through harder problems before answering.