04.7 Context Engineering: Managing Context Over Time

Understand LLMsLesson 7 of 1211,144 words12 parts
Module 04 · 0 of 10 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12

04.6 decided what goes into the context window for a single call: which sources, in what order, under what budget. This lesson takes the next step: what happens when the conversation doesn't end after one call. Real assistants, agents and copilots run for dozens or hundreds of turns, accumulate tool results, drift away from their instructions, and eventually press against the context limit. Managing context over time is the discipline of deciding, on every turn, which parts of the growing history still deserve tokens — and what to do with the rest. This lesson teaches the prompt-level part: why long conversations fail, the history strategies (sliding windows, rolling summaries, selective retention, structured state), summarization prompts, instruction drift, cache-aware history, handling the limit, a complete ConversationManager you can copy, and the tests that tell you whether your history management is actually working.

What you'll learn

  • Why long-running conversations fail in ways short ones don't: quadratic cost, context rot, instruction drift, compounding errors and tool-result floods
  • Every history-management strategy in depth: sliding windows by turns and by tokens, rolling and hierarchical summarization, selective retention and importance scoring, structured "working memory" state, and their failure modes
  • How to write a summarization prompt that preserves what later turns actually need, with two complete prompts you can reuse
  • The one decision rule for provider compaction features (use them as the safety net, keep your own manager for the strategy), with the catalogue itself in 08B.3, Part 6
  • The key rules for agent-level context, in short summaries that link to Module 08B: tool-result management (Part 5), memory across conversations and long tasks across many windows (Part 6) and sub-context isolation (Part 7)
  • How to keep instructions alive over many turns without breaking prompt caching
  • How to handle the context limit gracefully: pre-flight counting, proactive thresholds, the shedding order and what to tell the user
  • A complete, tested ConversationManager with token budget, pinned messages, rolling summary hook and a drop log — plus provider-call glue
  • How to evaluate long-conversation behaviour: fact-retention tests, constraint-retention tests and regression sets

What you don't need

  • API keys for most of this lesson. The ConversationManager, the summarization prompts and the retention harness are pure Python and run with no network at all. Provider samples are labelled illustrative.
  • The basics of context windows, statelessness and the first history strategies — lesson 02.7, Part 4 owns those. This lesson takes them to production depth and does not re-teach them.
  • Tool calling mechanics — lesson 03.5 covers the round trip; Module 08A covers agents. Here you manage what tool results do to the context.

Setup

Everything in this lesson is plain Python 3.11+ with the standard library only — no packages, no keys, no services. If you want a project folder:

bash
uv init context-over-time --bare --python 3.13 && cd context-over-time
# or: mkdir context-over-time && cd context-over-time

The samples are three files that sit next to each other: conversation_manager.py (the library, printed in full in 11.2), demo_manager.py (11.3) and retention_test.py (12.1). For the provider glue in 11.4 you need the Module 03 SDKs (openai, anthropic, google-genai, python-dotenv; checked against the major versions named in lesson 04.1's Setup) and the .env keys described in lesson 03.1. Optionally add tiktoken for a better token estimate than the built-in heuristic; exact per-provider counting is covered in lesson 03.7, Part 2.


What you must be able to do after this lesson#

  • Explain why long conversations degrade
  • Choose a history strategy such as windows or summaries
  • Write a summarization prompt that keeps what later turns need
  • Apply the key rules for tool results, memory and sub-context isolation, and find the agent-level material in Module 08B (08B.3, 08B.4)
  • Build a simple conversation manager and test it on a long conversation

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"The bot got dumber the longer we talked." 1.2 The failure catalogue
"Why does every turn cost more than the last?" 1.2, 9.1
"Just summarize the old messages." Part 3: summarization prompts, 2.6 failure modes
"The model forgot a constraint I gave it ten turns ago." 8.1 Instruction drift, 12.2 constraint tests
"Tool outputs are eating the whole window." Part 5: tool-result management
"Should we use Anthropic's compaction or write our own?" Part 4: provider compaction
"The agent needs to remember things across sessions." Part 6: memory
"Spawn a sub-agent for the research part." Part 7: sub-context isolation
"What do we do when the window is genuinely full?" Part 10: graceful limits
"How do we test that history management works?" Part 12: evaluating

Part 1: Why long-running interactions fail#

1.1 A conversation is a resource that decays#

A single API call is stateless: you assemble a context, the model reads it once, and the context is discarded (02.7, Part 3). A conversation is what your application builds on top of that: a store of turns that you re-assemble, trim, summarize and re-send on every call. The model never sees "the conversation" — it sees whatever slice of it you chose this turn.

That reframing matters. The conversation is not a transcript the model reads; it is a budget you allocate every turn. Every token of history you re-send is a token the model must attend to, pay for and keep coherent with everything else in the window. As the transcript grows, several things degrade at once (the catalogue below lists seven) — and they degrade together, which is why "the bot got weird after turn 30" is almost never one bug.

1.2 The failure catalogue#

Failure Mechanism First symptom you notice
Quadratic cost and latency Turn n re-sends turns 1..n−1; total input tokens grow roughly with the square of turn count (02.7, 6.1) The bill, or slow first tokens
Context rot Accuracy and recall degrade as input length grows even when the task is unchanged (02.7, 5.2) Vaguely wrong answers, missed details
Lost in the middle Relevant old turns sit in the middle of a long context and get less attention (02.7, 5.1) "It knew that earlier but forgot now"
Instruction drift The original instructions are hundreds of turns back; newer, more recent text pulls behaviour away from them Tone shifts, rules quietly dropped, scope creep
Compounding errors A wrong assumption at turn 5 is treated as established fact at turn 50; the model never re-checks it Confident answers built on an early mistake
Tool-result floods Each tool call can return thousands of tokens; a dozen calls can fill the window with output nobody reads again Sudden cost spikes, truncated answers, 400s
The hard wall Input + reserved output exceeds the window; you get an error or silent truncation (02.7, 2.6) context_length_exceeded, prompt is too long

Two of these deserve a sharper look because they are specific to managing over time rather than to context size itself.

Compounding errors is the quiet killer of long agents. When the model says something wrong at turn 5 — a misread date, a wrong order ID, a hallucinated policy — that text becomes part of the history you faithfully re-send. From then on it has the same authority as everything else: the model can't distinguish "what the user actually said" from "what the model once guessed". Every later turn reasons on top of the error. The defence is not a better prompt; it's provenance — keeping facts the user or a tool stated visually and structurally separate from the model's own earlier claims, and re-checking load-bearing claims against a source of truth (a database, a document, the pinned facts block) rather than trusting the transcript.

Instruction drift is the mirror image: the system prompt says "always reply in German" at the top, but forty turns of English chit-chat later the model has drifted back to English. Recency wins over authority at sufficient distance (02.7, 5.5). The fix is not writing the instruction louder — it's re-injecting it where the model is looking, which is Part 8.

1.3 The lifecycle view#

Every turn runs the same loop. Your code owns every box except the model call:

flowchart TB
    subgraph store ["Your store (database / files)"]
        RAW["Raw transcript<br/>(never sent verbatim forever)"]
        MEM[("Long-term memory<br/>facts, preferences")]
        TOOLS[("Tool-result store<br/>large outputs by handle")]
    end
    U["New user message<br/>+ runtime facts"] --> SEL["Select & rank<br/>what enters the window"]
    RAW --> SEL
    MEM --> SEL
    TOOLS -->|"handle -> fetch on demand"| SEL
    SEL --> BUD["Fit to token budget:<br/>pin, summarize, trim, shed"]
    BUD --> CALL["Model API call<br/>(stateless)"]
    CALL --> ANS["Answer + tool calls"]
    ANS --> WR["Write-back:<br/>append turn, update state,<br/>extract memories, store tool results"]
    WR --> RAW
    WR --> MEM
    WR --> TOOLS

Notice what's not in the diagram: the model never manages any of this. Context over time is entirely application code — which is why this lesson is mostly about your code, not about prompting.


Part 2: History strategies in depth#

02.7, 4.2 introduced the strategy menu. This part takes each serious option to production depth: how it actually behaves, where it fails, and how to combine them.

2.1 The strategy space, extended#

Strategy What it keeps What it loses Cost per turn Failure mode
Send everything Everything Nothing Grows quadratically Overflow; rot; cost
Sliding window (last N turns) Recent verbatim All older detail Constant, small Forgets the goal stated at turn 1
Token-budget window Newest that fit Older detail Constant-ish Same, but adapts to message size
Selective retention Pinned facts + recent + scored-important The un-scored middle Constant + small pinned cost Scoring is a judgement call; stale pins
Rolling summary Summary of old + recent verbatim Detail inside summarized range Constant + one summary call occasionally Summary drift; lost constraints; fabrication
Hierarchical summary Summary of summaries + recent Detail at every level Constant + more calls Drift compounds across levels
Structured state Working-memory JSON + recent Anything not extracted into state Constant + extraction call Extraction misses; stale fields
Tool-result clearing Results replaced by stubs Old outputs (re-fetchable) Big savings in agents Model re-calls tools; lost nuance
Sub-context isolation Main thread + returned summaries Everything the sub-agent saw Extra calls Summary bottleneck; lost detail
External memory + retrieval Relevant memories fetched per turn Everything not retrieved Retrieval infra + tokens Retrieval misses; stale memories

The production answer is almost always a combination, and the combination is itself a design decision: which layers, in which order, with which thresholds. The ConversationManager in Part 11 implements the core stack — pinned facts, rolling summary, recency window, importance carry-forward — and leaves hooks for the rest.

2.2 Sliding windows: by turns vs by tokens#

Two ways to bound the verbatim tail:

  • By turns ("keep the last 20 messages"): simple, predictable cost, but a turn can be 50 tokens of chat or 50,000 tokens of pasted log. Twenty turns of the latter blows any budget.
  • By tokens ("keep the newest messages that fit B tokens"): adapts to content, uses the budget fully, but the number of turns retained varies — which matters for coherence (a window that keeps 3 long turns may lose the user's original goal).

Rule of thumb: budget by tokens, think in turns. Always keep whole turns (never split a user/assistant exchange or a tool call from its result — 02.7, 4.7), and treat "last N turns" as a sanity cap on top of the token budget, not the mechanism itself.

2.3 Selective retention and importance scoring#

Not all turns deserve equal survival. Selective retention marks some content as must-keep and lets the rest age out. Three mechanisms, from blunt to subtle:

  1. Pinning — you decide up front what never gets trimmed: the system prompt, the user's goal, key facts, open tasks (02.7, 4.6). Blunt, reliable, and the reason the pinned block exists.
  2. Importance scoring — each turn carries a score; when compaction selects it as a victim, a high scorer is quoted verbatim into the pinned block (carry-forward, 11.2) instead of being paraphrased into the summary. Scores can come from heuristics (turn length, presence of numbers/IDs, question marks), from a cheap classifier call, or — simplest and often best — from your code knowing what matters: a turn where the user stated a constraint, a decision was made, or a tool returned a load-bearing fact gets importance=0.9; small talk gets 0.2.
  3. Semantic retention — embed each turn and keep the ones most similar to the current query (Module 06 covers embeddings; 04.2 showed dynamic few-shot selection). Powerful but adds retrieval infrastructure and can miss exactly the constraint that doesn't look similar to the query.

The honest caveat: importance is a prediction, and predictions are wrong. A turn you scored 0.2 ("ok thanks") can contain the one detail turn 40 needs. This is why selective retention is layered under summarization rather than instead of it: important-sounding turns are carried forward verbatim into the pinned block, everything else still gets summarized rather than silently dropped, and the pinned block carries the facts you're sure matter.

2.4 Rolling and hierarchical summarization#

Rolling summary (a.k.a. running summary): whenever old turns cross a threshold, summarize them and prepend the result to the retained window. Each compaction folds the previous summary plus newly-old turns into a new summary — the summary is itself summarized over time.

Hierarchical summary: for conversations spanning hours or days, you get levels — turn summaries roll into episode summaries, episode summaries into session summaries. Each level loses more detail but stays small. This layered approach is how long-horizon agents can compress weeks of interaction into a context window.

The mechanics that make rolling summaries work in production:

  • Compact in batches, not every turn. Re-summarizing every turn costs an LLM call per message and changes the prompt prefix every call, defeating prompt caching (03.7). Compact when history crosses a threshold (the 60–70% heuristic in 10.1), folding the oldest chunk at once.
  • Keep the raw transcript. The summary is what you send, never what you store. Keep full fidelity in your database so you can re-summarize, audit, or show the user their history.
  • Use a cheaper model for summaries if quality holds — summarization is easier than the main task, and claude-haiku-5-5, gpt-6-luna or gemini-3.8-flash are typically ample (verify on your eval set).
  • Summary of a summary drifts. Each generation is a paraphrase of a paraphrase. Critical facts must be copied verbatim into the pinned block or structured state, not left to survive inside the summary (2.6).

2.5 Structured state: working memory as data#

Prose summaries are lossy and hard to update. An alternative — or companion — is a structured state object: a small JSON document your code maintains that captures where the conversation stands, injected into every request as a pinned block:

json
{
  "goal": "get a refund for order A-1042",
  "stage": "awaiting_return_photos",
  "facts": {"order_id": "A-1042", "issue": "battery drain", "warranty": "24mo"},
  "decisions": ["refund approved pending inspection", "loaner declined"],
  "open_tasks": ["verify photos", "email return label"],
  "last_topic": "display flicker under warranty"
}

This is the "working memory" pattern Anthropic describes for long-running agents: a scratchpad that survives when turns are cleared, updated either by your code (from structured events) or by the model through a tool like update_state(...) whose writes you validate. Compared to a prose summary it is precise (fields, not paragraphs), updatable (change one field, not rewrite a summary), and cheap (a few hundred tokens, stable enough to cache if you order it well).

The trade-off: someone has to write the state. Either your code extracts it (rules, a small LLM call with the extraction prompt in the gallery), or the model maintains it via tool calls (more flexible, more failure surface — the model can write wrong state). Many production systems use both: model-proposed updates that your code validates before accepting.

2.6 How compression fails#

Every compression mechanism trades fidelity for size. The failure modes are specific enough to test for:

Failure What it looks like Defence
Summary drift Each re-summary paraphrases; after 3 compactions the goal is "help with the bike" instead of "refund for order A-1042" Pin critical facts verbatim; prefer field-level state over prose
Lost constraints "Never promise refunds over €500" was in turn 2; the summary kept the refund discussion but dropped the limit Constraints go in the summarization prompt's must-preserve list and/or the pinned block
Fabrication The summarizer "helpfully" fills gaps: invents a decision nobody made, or misremembers which option was chosen Ground summaries in quotes; ask the summarizer to mark uncertainty; verify load-bearing claims against the store
Recency bias in the summary The summary emphasizes the most recent of the summarized turns and thins out the oldest Ask for uniform coverage; keep an age-ordered fact list
Detail that seemed minor A throwaway detail at turn 3 ("my dog is called Biscuit") becomes the answer at turn 40 Importance scoring; retrieval over the raw transcript as a fallback
Broken chronology Non-contiguous compaction produces a summary covering turns 3, 7, 9 while 4–6, 8 stay verbatim Victims must be a contiguous oldest-first prefix — ConversationManager enforces this; never skip protected turns and summarize around them

Part 3: Summarization prompts that survive#

The difference between a summary that helps and one that hurts is almost entirely the prompt. A good summarization prompt does three things a naive "summarize this" doesn't: it says what to preserve (not just what happened), it separates facts from interpretation, and it gives the output a stable shape so the next turn can rely on it.

3.1 What a good summary must preserve#

Ask the summarizer to carry forward, in roughly this priority:

  1. The user's goal — what they're ultimately trying to accomplish, in their words where possible
  2. Constraints and preferences — stated rules ("never…", "always…", "I prefer…"), including negative ones
  3. Decisions and their reasons — what was chosen and why, so the model doesn't re-litigate
  4. Facts, verbatim — names, IDs, numbers, dates, order numbers, error messages: copied exactly, never paraphrased
  5. Open questions and next steps — what's unresolved, what's pending
  6. For agents — which tools ran, which files changed, what failed and why

And explicitly tell it what it may drop: greetings, repetitions, resolved sub-questions, play-by-play narration.

3.2 The rolling-summary prompt#

This is the prompt to use when folding old turns into the running summary. It is written to be given the previous summary plus the newly-old turns, so it works incrementally:

text
You are compressing an ongoing conversation for a support assistant. You will
receive a PREVIOUS SUMMARY (possibly empty) and NEW TURNS to fold into it.
Produce an updated summary that a future turn of the assistant can rely on.

Preserve, in this priority order:
1. The user's underlying goal, in their own words where possible.
2. Every constraint or preference the user stated — including "never",
   "always", "don't" and format rules. Copy them verbatim.
3. Decisions made and the reason given. Mark each DECIDED.
4. Facts: names, IDs, order numbers, amounts, dates, error messages, file
   paths. Copy them EXACTLY as written — never paraphrase or round numbers.
5. Open questions and pending actions.
6. For tool use: which tools ran, their key results, and anything that failed.

Drop: greetings, thanks, repetitions, resolved sub-questions, and narration
of what the assistant did step by step.

Rules:
- Do not invent facts, decisions or outcomes that are not in the input.
- If the input is ambiguous about whether something was decided, write
  "unclear whether X was decided" rather than guessing.
- Keep the summary under 250 words. Prefer terse bullet points.
- Output ONLY the updated summary — no preamble, no commentary.

PREVIOUS SUMMARY:
<summary>
{{previous_summary}}
</summary>

NEW TURNS:
<turns>
{{turns}}
</turns>

Two details matter more than they look: "copy them EXACTLY" for facts (paraphrased order numbers and dates are how summaries corrupt data), and the "unclear whether" escape hatch (a summarizer that must guess will guess confidently and wrongly).

3.3 The state-extraction prompt#

When you maintain structured working memory (2.5), extract state with a separate, stricter prompt — JSON out, validated by your Pydantic model (03.4):

text
You maintain a small JSON "working memory" for an ongoing support conversation.
Read the NEW TURNS and update the CURRENT STATE. Output the complete updated
JSON object only — no prose, no markdown fences.

Fields:
- goal: the user's underlying objective, one sentence, their words where possible
- stage: one of intake | investigating | awaiting_customer | decided | closed
- facts: object of key->value for durable facts (ids, amounts, dates, names);
  copy values EXACTLY as stated; omit anything not explicitly stated
- decisions: list of strings, each "what was decided — reason"
- open_tasks: list of strings for unresolved actions
- constraints: list of verbatim user rules ("never ...", "always ...")

Rules:
- Never invent values. If a field is unknown, use null or an empty list.
- Preserve existing values unless the new turns clearly change them.
- Constraints are copied word-for-word, never paraphrased.
- Output must validate against the provided JSON schema.

CURRENT STATE:
<state>
{{current_state}}
</state>

NEW TURNS:
<turns>
{{turns}}
</turns>

Run this periodically (every compaction, or every N turns) rather than every turn — each call costs tokens, and state doesn't need turn-level freshness. Validate the output against your schema and reject updates that drop fields without cause; a buggy extractor that silently deletes constraints is worse than no extractor.

3.4 Incremental vs full re-summarization#

  • Incremental (summary + new turns → new summary): cheap, what the prompt above does. Suffers drift over many iterations.
  • Full re-summarization (re-summarize a larger window from scratch): more faithful, costs more, and still lossy. Use when you detect drift or when quality matters more than cost.
  • Chunked: for very long spans, summarize in chunks then summarize the chunk summaries (hierarchical, 2.4).

A pragmatic production pattern: incremental summaries for routine compaction, plus a full re-summarization from the raw transcript whenever you re-open a long-lived conversation or when evals show drift. Because you kept the raw transcript (2.4), re-summarizing is always possible.


Part 4: Provider compaction features (as of November 2026)#

Reference

Providers now offer server-side compaction (the API folds old context into a summary item) and client-side context editing (the API clears stale content by rule). They are features you switch on, not strategies you design. The API mechanics are in 03.2, 7.4. Beta headers and status change often, so read the catalogue linked above before you rely on any of it.

4.1 The landscape#

OpenAI offers threshold compaction on the Responses API and a standalone responses.compact call, and marks truncation="auto" as deprecated. Anthropic offers compaction on demand and at a token threshold (both beta), context editing (beta) and the memory tool (stable). Gemini has no built-in history compaction on the plain API, and OpenRouter has a plugin that only truncates. The full table, with the status of each feature and what you write yourself, is in 08B.3, Part 6.

4.2 OpenAI: two ways to compact#

Server-side compaction (a threshold parameter on a Responses request) and the stateless compact endpoint both return an opaque, encrypted compaction item. You keep it in the history unchanged and never prune or edit it. Details and a sample are in 08B.3, 6.1.

4.3 Anthropic: the richest menu, all moving#

Three shapes: compaction on demand (you pick the moment), compaction at a token threshold (the API picks it) and context editing (clears old tool results or thinking blocks by rule, no summary). The memory tool is the provider version of the write-back pattern in Part 6. Two rules hold across all of them: pass compaction blocks back unchanged, and expect headers and shapes to move. Details are in 08B.3, 6.2 and the memory tool is in 08B.4, Part 7.

4.4 Gemini and OpenRouter#

Gemini has no history compaction on generateContent (caching is a cost tool, not history management), so you write the summarizer yourself, which is what Part 11 gives you. OpenRouter's context-compression plugin truncates the middle, it does not summarize, so treat it as a safety net for small-context models. See 08B.3, 6.3.

4.5 Server-side vs rolling your own#

The rule that stays true at the prompt level: use provider compaction as the safety net and your own manager for the strategy. Your manager decides what should be in the window (pinned facts, importance, state, tool-result policy). The provider's compaction makes sure the window never overflows. Keep your own summaries even when the provider compacts, because they are text you can read, diff and test (Part 12), while a compaction item is opaque. The comparison table (control, visibility, portability, cost, debugging, maturity) is in 08B.3, 6.4.


Part 5: Tool-result management#

In an agentic loop, tool outputs are the biggest context consumers, often 10 to 100 times the size of the user's messages. Three unmanaged tool calls can fill a very large window. The fix is to manage the lifecycle of each result, not to delete everything. Module 08A builds on this.

5.1 Why tool outputs are different from chat#

Chat turns are small and irreplaceable. Tool outputs are large, re-fetchable and usually needed once. So "just delete it" is wrong and "manage it" is right. See 08B.3, 4.1.

5.2 The result-lifecycle toolkit#

Six techniques: keep verbatim (recent), clear to a stub, truncate with markers, summarize plus a handle, paginate, and store outside and pass a reference. The pattern that scales: recent results verbatim, older results summarized with a handle, the oldest stubbed or dropped, the same ladder you use for chat turns. Anthropic's clear_tool_uses_20250919 edit automates the stub row server-side (4.3). The full table with when to use each and its risk is in 08B.3, 4.3.

5.3 Handles and just-in-time retrieval#

Keep lightweight identifiers (paths, query ids, URLs) in the context and let the model fetch the content with a tool only when it needs it. Two conditions make this work: the handle is meaningful (the model can tell what it points to) and re-fetching is cheap and safe. Design the fetch path before you start stubbing results. See 08B.3, 4.4.

5.4 A result policy#

Decide at write-back time, per tool: small results stay verbatim, results used again soon are marked in use, everything else becomes a digest plus a handle, and compaction stubs the oldest results first. Two rules prevent the subtle bugs. Never orphan a tool call from its result (treat the pair as one unit). Annotate stubs with what was cleared and how to re-fetch it, because a bare [...] invites hallucination. A runnable policy is in 08B.3, 4.5.

5.5 Non-text parts in history#

Images, PDFs and audio cannot be folded into a text summary without loss, and they are priced differently from text. Their lifecycle is the tool-result lifecycle one tier up: keep recent media verbatim, and replace older media with a description plus a file handle. Two rules: describe a part before you drop it (the description is all that survives) and keep the underlying file. See 08B.3, 4.6 and 03.6 for how parts are sent.


Part 6: Memory across conversations#

Deep-dive

The model remembers nothing between conversations. "Memory" is always application code that stores facts and re-injects them into later prompts (02.7, Part 9). This part keeps the shape of that pipeline.

6.1 Short-term vs long-term memory#

The boundary is time, not topic. Short-term memory lives in the history you re-send and dies with the session ("my refund case is open"). Long-term memory lives in a store you own and survives sessions ("prefers metric units"). Move a fact down to long-term only once it proves durable. See 08B.3, 1.4 for the comparison table.

6.2 The write-back pipeline#

Memory is a loop, not a store: extract durable facts, validate and dedupe them (memories are untrusted text), store them with metadata, retrieve the relevant few for the new conversation, and inject them into a token-budgeted block (04.6). The Anthropic memory tool is the provider-native version: only who proposes the writes differs. The full pipeline with code is in 08B.4, Part 3.

6.3 What to store, and what never to store#

Store stable preferences, durable facts, decisions and explicit "remember" requests. Never store secrets, PII you do not need, or transient state. Two rules: memories are untrusted input (a stored "ignore previous instructions" fires in every future conversation), and stale memories are worse than none (timestamp them and make them correctable). See 08B.2, 4.1 and 6.2.

6.4 User control and deletion#

Any feature that stores personal data needs visibility, deletion, correction and export. Treat the store as user-owned data your app borrows, not hidden state. See 08B.4, Part 6 and 08B.2, 6.3. The mental model of core memory (always in context) versus archival memory (searched on demand) comes from Letta, covered in 08B.2.

6.5 Long tasks across many context windows: files and git as the memory#

Some tasks outlast any single window or compaction. Treat the window as disposable and put the durable state in files: a structured task list (tests.json) that the agent may not edit away, a short progress.txt, frequent git commits and a start-up script. Prefer a fresh window with a prescriptive start-up prompt when the state is on disk and can be rebuilt, and compaction when the state lives only in the conversation. Tell the model what your harness does (for example that the context will be compacted) so it does not stop early. State files are context too: keep them short and treat what you read back as untrusted. The six-step pattern and a runnable example are in 08B.3, Part 7. This is the same "write" move as in 04.6, 1.6.


Part 7: Sub-context isolation#

Deep-dive

When the task is too big for one context (twenty document reads, fifty files), hand the sub-task to a separate model call with its own fresh window and return only a summary. The main context stays clean by construction.

7.1 The delegation pattern#

The sub-call gets the specific sub-task, the minimum context it needs and a spec for what to return. It does the noisy work in its own window. Only the distilled result (typically a few hundred tokens, up to a couple of thousand) crosses back. See 08B.3, 8.1.

7.2 What crosses the boundary, and what it costs#

Findings, key facts with provenance and decisions cross back. Raw documents, intermediate reasoning and dead ends stay in the sub-call. The costs: more calls and latency, and the summary is a bottleneck (anything the sub-call does not return is gone, so ask for findings with provenance, not just conclusions). If you only need one document's content, a read_file tool call is simpler than a sub-agent (5.3). See 08B.3, 8.2 and, for specialist agents with a coordinator, 08D.1.


Part 8: Keeping instructions alive over many turns#

Deep-dive

Your system prompt is written once, at turn 0, at the top of the context. By turn 50 it is hundreds of messages upstream — the position least attended to (02.7, 5.5) and the furthest from the recency pull of the latest user message. This is instruction drift: behaviour that was correct at turn 5 quietly degrades — tone slips, a "never do X" rule gets violated, the persona thins out.

8.1 Instruction drift#

Drift has three compounding causes:

  1. Distance — the instruction is far from where the model's attention concentrates (the end of the context, near the current turn).
  2. Competition — forty turns of user text, tool output and assistant replies dilute the instruction's influence; each new turn is a small vote for "behave like the recent conversation", not "behave like the system prompt".
  3. Compaction — if your summarizer doesn't preserve constraints (2.6, 3.2), the instruction's content can be lost entirely when old turns fold into the summary.

8.2 Re-injection and reminders#

The countermeasures, roughly in order of intrusiveness:

  • Pinned rules in the state block. The highest-value rules ("always answer in German", "never promise refunds over €500", "cite order IDs") belong in the pinned facts/state block (2.5), re-rendered every turn near the top — not buried in the system prompt alone. This is selective retention applied to instructions, and it's the cheapest fix.
  • A reminder at the end. For long contexts, repeat the critical instruction(s) in a short message after the history, right before the new user turn — the position of maximum attention. Anthropic's and Google's long-context guidance both put the query at the end of a long prompt (Anthropic reports up to 30 percent better responses in its tests), and Anthropic's migration notes suggest injecting reminders into the user turn in very long conversations; the cost is a few tokens per call. Keep it to the 2–3 rules that actually drift, not the whole system prompt.
  • Mid-conversation system messages. Anthropic supports {"role": "system"} messages inside messages on the models that document the feature (as of November 2026 the list excludes Claude Sonnet 5, where the page says to use the top-level system field instead; check 03.2, 2.4 before relying on it); OpenAI's Responses API has the developer role for the same purpose. A periodic "reminder turn" ("Reminder: you are Acme support; always cite order IDs; reply in German") every ~20 turns is a legitimate pattern — though each injection is a small context cost and a small cache break (see Part 9).
  • Re-anchor after compaction. When you compact, the summary replaces old turns — the perfect moment to re-state the active goal and constraints in the pinned block, because the model's "recent" context just got rewritten.

Part 9: Cache-aware history management#

Deep-dive

Prompt caching (02.7, Part 7, 03.7, Parts 6–7) rewards stable prefixes: if the first N tokens of your request are identical to last turn's, the provider reuses the cached computation and charges a fraction for them. History management is in constant tension with this, because every edit to the history changes the prefix.

9.1 Append-only histories and stable prefixes#

The cache-friendly shape of a request is:

text
[system prompt]            <- stable across ALL users and turns (cache gold)
[pinned facts + state]     <- stable within a session; changes only on events
[tool definitions]         <- stable per deployment
[conversation history]     <- append-only: turn n+1 = turn n's history + new msgs
[new user message]         <- the only genuinely new tokens each turn

Two rules follow:

  1. Append, don't edit. The single most cache-friendly history is strictly append-only: each turn's request is the previous request plus the new exchange. Any in-place edit — fixing a typo in an old message, reordering turns, rewriting a tool result — invalidates the cache from the edit point forward.
  2. Stable content first, volatile last. System prompt and tool definitions (identical for every user) before per-user pinned facts, before per-turn history. The more of the prefix that's shared across requests, the more cache hits. 02.7, 7.4 covers the design rules and 03.7, Parts 6–7 the provider-specific breakpoint placement.

9.2 Where trimming and compaction break the cache#

Every history-management operation has a cache cost — the trick is concentrating the breaks:

Operation Cache effect Mitigation
Append a turn None — pure suffix growth The ideal case
Update pinned facts/state Breaks cache from the pinned block forward (it's early in the prefix) Update state only at compaction events or every N turns, not every turn; or append state as a late message where the provider allows
Compact / summarize Breaks cache from the summary position forward — but you're already rewriting history Do it in batches at thresholds, not continuously; the break is amortized
Trim oldest turns Breaks cache from the start of history — the worst position Prefer summarization (keeps a stable-ish prefix shape) over hard trimming; if you must trim, trim in large chunks rarely
Edit an old message Breaks cache from that message forward Don't — append a correction instead ("correction: the order ID is A-1043, not A-1042")
Re-inject reminders Small break at the injection point Inject at the end (after history), minimizing the invalidated prefix

Part 10: Handling the limit gracefully#

Deep-dive

Eventually every long conversation reaches the wall. The engineering question isn't whether to compact — it's when, what order to shed things, and what to tell the user. Done well, hitting the limit is an invisible event; done badly, it's a 400 error or a model that confidently forgets.

10.1 Pre-flight counting and proactive thresholds#

Never wait for the API to reject you. Before every call:

  1. Count what you're about to send. Exact counts come from the provider's counter (03.7, Part 2); local estimates (tiktoken, or the chars-per-token heuristic in conversation_manager.py) are fine for routine turns — call the exact counter when you're within ~10–20% of the budget.
  2. Compute the input budget the way 02.7, 4.3 does: context_window − max_output − reasoning_allowance − safety_margin.
  3. Act on a threshold, not on the wall. A common heuristic is to start compacting when projected input crosses 60–70% of the budget — early enough that summarization has room to work and the recent turns stay verbatim. This is a heuristic, not a law: the right threshold depends on your summarizer's quality, your task's sensitivity to detail, and the model. Test it (the retention harness in Part 12 is built for exactly this).

10.2 The shedding order#

When over budget, shed in this order — cheapest-to-regenerate and least-load-bearing first:

  1. Old tool results → stubs/handles (Part 5) — re-fetchable, huge
  2. Low-importance old turns → into the rolling summary (Part 2)
  3. Old memories not relevant to now → drop from the injected set (they stay in the store)
  4. The summary itself → tighten its allowance if it's grown
  5. Recent turns → last resort; never shed these while anything older remains

What you should never shed: the system prompt and pinned facts/state (they're the contract), the newest user message (it's the question being answered), and any turn a tool call depends on.

10.3 What to tell the user#

Context management is invisible infrastructure — until something goes wrong, then transparency matters:

  • Routine compaction: say nothing. The user doesn't need "I summarized our earlier chat" every 30 turns; it reads as the bot being forgetful.
  • When detail was actually lost: if compaction dropped something the user might reference ("I mentioned my dog's name earlier"), a subtle signal is honest — a one-line status ("I've condensed our earlier discussion to stay within limits") beats silent confusion later.
  • On hard failure: if you genuinely can't fit (a single pasted document larger than the window), tell the user plainly and offer the fix ("this file is too large — shall I summarize it first or split it?"). Never let a context_length_exceeded reach the user as a stack trace.
  • Log everything. drop_log, token breakdowns and the exact rendered context are your debugging lifeline (03.10) — when the model "forgets", the first question is what was actually sent.

Part 11: Building a ConversationManager#

Time to assemble it. conversation_manager.py below is a complete, dependency-free implementation of the core stack: token budget + pinned facts/state + rolling summary + recency window + importance carry-forward + drop log. It's provider-neutral — render() returns provider-shaped dicts (only role, content and tool fields ever leave the manager; internal bookkeeping like importance and meta stays inside) that you map to each provider's shape (11.4).

11.1 Design#

The manager owns three things:

  • history — the working transcript (your store's view; production backs this with a database per 03.2, Part 5)
  • summary — the rolling summary of compacted turns
  • drop_log — an audit of everything removed and everything skipped at view level (over_budget, recorded once per turn)

Every render() produces the request layout: system → pinned facts/state → summary → newest fitting turns. Compaction fires proactively at compaction_ratio of budget; hard overflow just sends fewer turns (they stay in history for later).

Two invariants are worth stating explicitly, because everything else follows from them:

  • Chronology: the summary always covers a contiguous oldest-first prefix of the surviving history. Skipping a protected turn and summarizing newer ones would produce a summary describing turns 3, 7, 9 while turns 4–6, 8 stay verbatim — the broken-chronology failure of 2.6. So importance protection never skips a victim: a victimized turn scoring at/above protect_importance is first carried forward — its user/assistant text is quoted verbatim into the pinned block — and then summarized like the rest. Protection means preserved word-for-word (the +pinned marker in drop_log shows it), not exempt from compaction.
  • Projection: render() strips internal bookkeeping, so only role, content, tool_calls and tool_call_id reach the provider payload — the "plain dicts" contract is enforced in code, not just promised.

The tunables: compaction_ratio (soft threshold, default 0.7), keep_recent (verbatim tail, default 2), protect_importance (carry-forward threshold, default 0.8 — set ≥ 1.0 to disable), carry_forward_chars (quote cap, default 800) and summary_allowance (summary token cap, default 400).

11.2 The full code#

python
"""conversation_manager.py — provider-neutral long-conversation context manager.

Pure local, stdlib only. The token counter is pluggable: the default is a
chars-per-token heuristic; in production inject tiktoken or a provider counter
(see lesson 03.7, Part 2).
"""
from __future__ import annotations

import json
from dataclasses import dataclass
from typing import Callable, Protocol

# A message is a plain dict: {"role": ..., "content": ...} plus optional keys:
#   "importance": float 0..1  — bookkeeping for compaction; never sent
#   "meta": dict             — bookkeeping for YOUR store; never sent
#   "tool_calls" / "tool_call_id" — sent through; providers still need their
#                               own tool-call/result mapping (see lesson 11.4)
# render() strips everything outside {"role", "content", "tool_calls",
# "tool_call_id"} before a request leaves the manager.

PER_MESSAGE_OVERHEAD = 4  # role marker, separators, chat-template tokens (rough)

# The only keys that may appear in a rendered request.
_API_KEYS = ("role", "content", "tool_calls", "tool_call_id")


class TokenCounter(Protocol):
    def __call__(self, text: str) -> int: ...


def chars_per_token(chars_per_token: float = 4.0) -> TokenCounter:
    """A rough English estimate. ~4 chars/token for OpenAI-style tokenizers,
    nearer 2.5 for Anthropic's — calibrate on your own logs (lesson 03.7, 2.7)."""
    def count(text: str) -> int:
        return max(1, round(len(text) / chars_per_token))
    return count


def count_message(message: dict, counter: TokenCounter) -> int:
    """Overhead + content + any tool_calls payload. Non-string content
    (multimodal part lists) is serialized before counting; this stays a
    heuristic — for tool-call-heavy or multimodal histories inject a real
    provider counter (lesson 03.7, Part 2)."""
    content = message.get("content")
    text = content if isinstance(content, str) else (
        json.dumps(content, ensure_ascii=False) if content else "")
    tokens = counter(text)
    if message.get("tool_calls"):
        tokens += counter(json.dumps(message["tool_calls"], ensure_ascii=False))
    return PER_MESSAGE_OVERHEAD + tokens


def group_turns(history: list[dict]) -> list[list[dict]]:
    """Group flat history into atomic turns: a new turn starts at each user
    message; assistant and tool messages belong to the turn they answer.
    Messages before the first user message form a leading turn."""
    turns: list[list[dict]] = []
    for message in history:
        if message.get("role") == "user" or not turns:
            turns.append([message])
        else:
            turns[-1].append(message)
    return turns


def turn_tokens(turn: list[dict], counter: TokenCounter) -> int:
    return sum(count_message(m, counter) for m in turn)


def turn_importance(turn: list[dict]) -> float:
    """A turn's importance is the max of its messages': if any part matters,
    the whole exchange is worth keeping together."""
    return max(float(m.get("importance", 0.5)) for m in turn)


def to_api_message(message: dict) -> dict:
    """Project an internal history message to the fields providers accept.
    Bookkeeping keys ("importance", "meta", ...) never leave the process."""
    return {k: v for k, v in message.items() if k in _API_KEYS}


@dataclass
class DropRecord:
    # "summarized" is permanent (the turn left `history`); "over_budget" and
    # "orphaned_leading_turn" are view-level: the turn stays in `history` but
    # wasn't sent on that call. View-level drops are logged once per turn.
    reason: str            # "summarized" | "orphaned_leading_turn" | "over_budget"
    turn_preview: str
    messages: int
    tokens: int
    promoted: bool = False  # high-importance turn quoted verbatim into pinned


@dataclass
class RenderStats:
    tokens_used: int
    budget: int
    turns_kept: int
    turns_in_history: int
    summary_tokens: int
    turns_not_sent: int


class ConversationManager:
    """Keeps a conversation inside a token budget.

    Layout sent to the model, in order:
        system prompt -> pinned facts/state -> rolling summary -> newest turns

    - `pinned_facts` and `state` are re-rendered every call and never trimmed.
    - When the projected size crosses `compaction_ratio` of the budget, the
      oldest turns are folded into `summary` via `summarizer` as a contiguous
      prefix — the summary must cover a prefix of the surviving history, or
      the rendered request would describe later turns before earlier ones.
      The `keep_recent` newest turns are never compacted. A victimized turn
      scoring at/above `protect_importance` is first quoted verbatim into
      the pinned block ("carry-forward"), then summarized like the rest.
    - Turns that still don't fit are not sent this call, but stay in
      `history` (your store keeps the raw transcript; this class is the
      view); each is logged once in `drop_log` as "over_budget".
    - Every removal from `history` is recorded in `drop_log`.
    - render() returns provider-shaped dicts: only role/content/tool_calls/
      tool_call_id leave the manager (see to_api_message).
    """

    def __init__(
        self,
        system: str,
        *,
        context_window: int,
        max_output: int,
        pinned_facts: list[str] | None = None,
        state: dict | None = None,
        counter: TokenCounter | None = None,
        summarizer: Callable[[str | None, list[list[dict]]], str] | None = None,
        summary_allowance: int = 400,
        compaction_ratio: float = 0.7,
        keep_recent: int = 2,
        protect_importance: float = 0.8,
        carry_forward_chars: int = 800,
        safety_margin: float = 0.05,
    ) -> None:
        self.system = system
        self.context_window = context_window
        self.max_output = max_output
        self.pinned_facts = list(pinned_facts or [])
        self.state = dict(state or {})
        self.counter = counter or chars_per_token()
        self.summarizer = summarizer
        self.summary_allowance = summary_allowance
        self.compaction_ratio = compaction_ratio
        self.keep_recent = keep_recent
        self.protect_importance = protect_importance
        self.carry_forward_chars = carry_forward_chars
        self.safety_margin = safety_margin

        self.history: list[dict] = []
        self.summary: str | None = None
        self.drop_log: list[DropRecord] = []
        self.compactions = 0
        # Ids of first messages in turns already logged as view-level drops,
        # so "over_budget"/"orphaned" are recorded once per turn, not per call.
        self._view_logged: set[int] = set()

    # -- what you record -------------------------------------------------

    def add_user(self, content: str, importance: float = 0.5) -> None:
        self.history.append({"role": "user", "content": content,
                             "importance": importance})

    def add_assistant(self, content: str, importance: float = 0.5,
                      tool_calls: list[dict] | None = None) -> None:
        msg = {"role": "assistant", "content": content,
               "importance": importance}
        if tool_calls:
            msg["tool_calls"] = tool_calls
        self.history.append(msg)

    def add_tool_result(self, tool_call_id: str, content: str) -> None:
        # A tool result binds to the assistant turn it answers; group_turns
        # keeps it inside that turn so it can never be orphaned.
        self.history.append({"role": "tool", "tool_call_id": tool_call_id,
                             "content": content, "importance": 0.2})

    def set_state(self, **fields) -> None:
        """Update the structured working memory rendered into the pinned block."""
        self.state.update(fields)

    # -- budgets ----------------------------------------------------------

    @property
    def input_budget(self) -> int:
        return int(self.context_window - self.max_output
                   - self.context_window * self.safety_margin)

    def _fixed_messages(self) -> list[dict]:
        """Everything that is always sent: system, then pinned facts + state.
        The second message is skipped when there is nothing to pin — an
        empty "Session facts:" block would just waste tokens every call."""
        pinned = "\n".join(f"- {f}" for f in self.pinned_facts)
        if self.state:
            pinned += "\n\n<session_state>\n" + json.dumps(
                self.state, ensure_ascii=False, indent=2) + "\n</session_state>"
        messages = [{"role": "system", "content": self.system}]
        if pinned:
            messages.append({"role": "system",
                             "content": "Session facts:\n" + pinned})
        return messages

    def _summary_message(self) -> list[dict]:
        if not self.summary:
            return []
        text = "Summary of earlier conversation:\n" + self.summary
        # Never let the summary eat more than its allowance.
        tokens = self.counter(text)
        if tokens > self.summary_allowance:
            text = text[: int(len(text) * self.summary_allowance / tokens)]
        return [{"role": "system", "content": text}]

    def _projected_tokens(self, turns: list[list[dict]]) -> int:
        fixed = sum(count_message(m, self.counter) for m in self._fixed_messages())
        summary = sum(count_message(m, self.counter) for m in self._summary_message())
        return fixed + summary + sum(turn_tokens(t, self.counter) for t in turns)

    def _log_drop(self, reason: str, turn: list[dict],
                  promoted: bool = False) -> None:
        first = turn[0].get("content")
        preview = first if isinstance(first, str) else json.dumps(
            first or "", ensure_ascii=False)
        self.drop_log.append(DropRecord(
            reason=reason,
            turn_preview=preview[:60],
            messages=len(turn),
            tokens=turn_tokens(turn, self.counter),
            promoted=promoted))

    def _carry_forward(self, turn: list[dict]) -> None:
        """Quote a protected turn's user/assistant text verbatim into the
        pinned block before it is summarized. Tool results are skipped —
        they are re-fetchable by handle (Part 5.3)."""
        parts = []
        for m in turn:
            if m.get("role") in ("user", "assistant"):
                content = m.get("content")
                if isinstance(content, str) and content.strip():
                    parts.append(" ".join(content.split()))
        if not parts:
            return
        text = " / ".join(parts)
        if len(text) > self.carry_forward_chars:
            text = text[: self.carry_forward_chars].rstrip() + " …"
        self.pinned_facts.append(f"[kept verbatim from earlier turn] {text}")

    # -- compaction --------------------------------------------------------

    def _compact(self) -> None:
        """Fold the oldest turns into the rolling summary.

        Victims are a contiguous oldest-first prefix: the summary must cover
        a prefix of the surviving history, or the rendered request would
        place a summary of later turns before earlier verbatim ones. Turns
        are never skipped over — a high-importance victim is carried forward
        verbatim into the pinned block instead (selective retention)."""
        if self.summarizer is None:
            return
        turns = group_turns(self.history)
        # The most recent turns are the live context: never compact them.
        protected = turns[-self.keep_recent:] if self.keep_recent else []
        candidates = turns[: len(turns) - len(protected)]
        if not candidates:
            return
        target = int(self.input_budget * 0.5)

        victim_idx: set[int] = set()
        for i, turn in enumerate(candidates):
            trial = [candidates[j] if j not in victim_idx else []
                     for j in range(len(candidates))] + protected
            if self._projected_tokens(trial) <= target:
                break
            victim_idx.add(i)
        if not victim_idx:
            return

        victims = [candidates[i] for i in sorted(victim_idx)]
        keep = [t for i, t in enumerate(candidates) if i not in victim_idx] + protected
        promoted = {id(t) for t in victims
                    if turn_importance(t) >= self.protect_importance}
        for t in victims:
            if id(t) in promoted:
                self._carry_forward(t)
        self.history = [m for t in keep for m in t]
        self.summary = self.summarizer(self.summary, victims)
        self.compactions += 1
        for t in victims:
            self._log_drop("summarized", t, promoted=id(t) in promoted)

    # -- render ------------------------------------------------------------

    def render(self) -> tuple[list[dict], RenderStats]:
        """Return (messages_to_send, stats). Compact first if over the soft
        threshold, then send the newest turns that fit the hard budget."""
        turns = group_turns(self.history)
        if self._projected_tokens(turns) > self.input_budget * self.compaction_ratio:
            self._compact()
            turns = group_turns(self.history)

        fixed = self._fixed_messages()
        summary_msgs = self._summary_message()
        used = sum(count_message(m, self.counter) for m in fixed + summary_msgs)
        room = self.input_budget - used
        if room < 0:
            raise ValueError(
                f"Pinned context alone needs {-room} tokens over the "
                f"{self.input_budget}-token budget; shrink the system prompt "
                f"or pinned facts.")

        # Newest turns first; a turn is kept whole or not at all.
        kept_reversed: list[list[dict]] = []
        spent = 0
        for turn in reversed(turns):
            cost = turn_tokens(turn, self.counter)
            if spent + cost > room:
                break
            kept_reversed.append(turn)
            spent += cost
        kept = list(reversed(kept_reversed))
        if turns and not kept:
            newest = turns[-1]
            raise ValueError(
                f"The newest turn alone needs {turn_tokens(newest, self.counter)} "
                f"tokens but only {room} are free; shrink the input or raise "
                "the context window.")
        # Never open the sent history on an assistant/tool turn.
        while kept and kept[0][0].get("role") != "user":
            orphan = kept.pop(0)
            self._view_logged.add(id(orphan[0]))
            self._log_drop("orphaned_leading_turn", orphan)

        # Turns outside the kept window stay in `history` but aren't sent
        # this call; log each once so drop_log is a complete audit (10.3).
        kept_ids = {id(t[0]) for t in kept}
        for turn in turns:
            if id(turn[0]) not in kept_ids and id(turn[0]) not in self._view_logged:
                self._view_logged.add(id(turn[0]))
                self._log_drop("over_budget", turn)

        messages = fixed + summary_msgs + [
            to_api_message(m) for t in kept for m in t]
        stats = RenderStats(
            tokens_used=used + sum(turn_tokens(t, self.counter) for t in kept),
            budget=self.input_budget,
            turns_kept=len(kept),
            turns_in_history=len(turns),
            summary_tokens=sum(count_message(m, self.counter)
                               for m in summary_msgs),
            turns_not_sent=len(turns) - len(kept),
        )
        return messages, stats

11.3 Try it: a long support chat#

demo_manager.py drives it through a 12-turn warranty conversation inside a deliberately tiny 1,200-token window, with a stub summarizer (a real one is an LLM call with the 3.2 prompt):

python
"""demo_manager.py — drive ConversationManager through a long support chat."""
import sys
sys.path.insert(0, ".")
from conversation_manager import ConversationManager, chars_per_token


def stub_summarizer(previous, turns):
    """Deterministic stand-in for an LLM summarizer call. Keeps user questions
    and the first clause of each reply — a real summarizer uses Part 3's prompt."""
    parts = []
    if previous:
        parts.append(f"[earlier] {previous}")
    for turn in turns:
        for m in turn:
            role = {"user": "U", "assistant": "A", "tool": "T"}.get(m["role"], "?")
            text = (m.get("content") or "").replace("\n", " ")
            parts.append(f"{role}: {text[:80]}")
    return " | ".join(parts)[:600]


POLICY = (
    "WARRANTY POLICY EXCERPT: Acme e-bikes carry a 24-month warranty covering "
    "motor, battery and controller defects. Cosmetic damage, tyre wear and "
    "accident damage are excluded. Claims require the order number, photos of "
    "the defect and a short description. Approved claims ship a prepaid "
    "return label within 3 business days; refunds are issued to the original "
    "payment method within 10 business days of inspection. Warranty does not "
    "cover commercial use, rental fleets or bikes modified with third-party "
    "parts. Battery capacity degradation below 70 percent of rated capacity "
    "within the warranty period qualifies as a defect. Always ask for the "
    "order number before discussing any claim. Escalate to a human agent when "
    "the customer disputes a denial or mentions legal action."
)

manager = ConversationManager(
    system="You are a support assistant for Acme Bikes. Be concise and accurate.",
    context_window=1200,
    max_output=150,
    pinned_facts=[
        "Customer: Priya Nair (priya.nair@example.com)",
        "Order #A-1042: Volt S e-bike, delivered 2026-09-30",
    ],
    state={"open_issue": "battery drains overnight", "stage": "warranty_check"},
    counter=chars_per_token(4.0),
    summarizer=stub_summarizer,
    summary_allowance=90,
    compaction_ratio=0.7,
    keep_recent=2,
)

turns = [
    ("Hi, my e-bike battery dies overnight even when switched off. Is that normal?",
     "That's not normal — a healthy pack shouldn't lose meaningful charge parked. "
     "I'll check the warranty policy and your order.", 0.6),
    ("It's the Volt S from order A-1042.",
     "Thanks — order A-1042 shows delivery on 30 September, inside the 24-month "
     "warranty. Let me pull the battery policy.", 0.7),
    ("kb_search('battery drain warranty') -> " + POLICY,
     "The policy covers battery defects, including capacity loss. Two questions: "
     "does it happen every night, and has the bike been parked below freezing?", 0.4),
    ("Every night for a week. It was 2 C last night in the garage.",
     "Cold alone shouldn't do that. Please send a photo of the battery label and "
     "a short video of the drain if you can.", 0.85),
    ("ok sending now", "Got it — I'll wait for the files.", 0.2),
    ("btw do you ship to Austria?", "Yes, we ship across the EU; Austria is "
     "covered by the standard 5-8 day window.", 0.3),
    ("Also, can I get a loaner bike while it is repaired?", "Loaner bikes are "
     "available for warranty repairs at select service points; I'll check "
     "availability near you once the claim is approved.", 0.5),
    ("How long does a warranty repair usually take?", "Most battery claims are "
     "resolved within 10 business days of receiving the bike.", 0.5),
    ("The video is uploading now.", "Perfect — once it lands I'll open the claim "
     "and email the return label.", 0.4),
    ("Will the refund go to my card or store credit?", "Refunds always go back "
     "to the original payment method within 10 business days of inspection.", 0.6),
    ("One more thing — the display flickers when it rains.", "That's likely "
     "water ingress on the display cable; it's covered under the same warranty. "
     "I'll add it to the claim.", 0.8),
    ("So to confirm: battery + display, one claim, prepaid label?", "Correct — "
     "one claim covering both issues, and I'll send the prepaid return label "
     "once the photos are verified.", 0.9),
]

for i, (user, assistant, imp) in enumerate(turns, 1):
    manager.add_user(user, importance=imp)
    manager.add_assistant(assistant, importance=imp)
    if i == 9:  # the claim is now open: update the working memory
        manager.set_state(stage="claim_opened",
                          open_issue="battery drain + display flicker",
                          claim_status="awaiting photos")
    messages, stats = manager.render()
    print(f"--- turn {i:2d} | sent {stats.tokens_used}/{stats.budget} tokens | "
          f"kept {stats.turns_kept}/{stats.turns_in_history} turns | "
          f"summary {stats.summary_tokens} tok | not sent {stats.turns_not_sent}")

print("\n=== drop log ===")
for d in manager.drop_log:
    tag = " +pinned" if d.promoted else ""
    print(f"  {d.reason:22s} {d.messages} msgs {d.tokens:4d} tok | "
          f"{d.turn_preview!r}{tag}")

print("\n=== last rendered request ===")
for m in messages:
    print(f"[{m['role']:9s}] {(m.get('content') or '')[:110]!r}")

Run it (python demo_manager.py). Real output:

text
--- turn  1 | sent 138/990 tokens | kept 1/1 turns | summary 0 tok | not sent 0
--- turn  2 | sent 183/990 tokens | kept 2/2 turns | summary 0 tok | not sent 0
--- turn  3 | sent 430/990 tokens | kept 3/3 turns | summary 0 tok | not sent 0
--- turn  4 | sent 481/990 tokens | kept 4/4 turns | summary 0 tok | not sent 0
--- turn  5 | sent 501/990 tokens | kept 5/5 turns | summary 0 tok | not sent 0
--- turn  6 | sent 536/990 tokens | kept 6/6 turns | summary 0 tok | not sent 0
--- turn  7 | sent 591/990 tokens | kept 7/7 turns | summary 0 tok | not sent 0
--- turn  8 | sent 630/990 tokens | kept 8/8 turns | summary 0 tok | not sent 0
--- turn  9 | sent 674/990 tokens | kept 9/9 turns | summary 0 tok | not sent 0
--- turn 10 | sent 462/990 tokens | kept 7/7 turns | summary 94 tok | not sent 0
--- turn 11 | sent 511/990 tokens | kept 8/8 turns | summary 94 tok | not sent 0
--- turn 12 | sent 562/990 tokens | kept 9/9 turns | summary 94 tok | not sent 0

=== drop log ===
  summarized             2 msgs   57 tok | 'Hi, my e-bike battery dies overnight even when switched off.'
  summarized             2 msgs   45 tok | "It's the Volt S from order A-1042."
  summarized             2 msgs  247 tok | "kb_search('battery drain warranty') -> WARRANTY POLICY EXCER"

=== last rendered request ===
[system   ] 'You are a support assistant for Acme Bikes. Be concise and accurate.'
[system   ] 'Session facts:\n- Customer: Priya Nair (priya.nair@example.com)\n- Order #A-1042: Volt S e-bike, delivered 2026-'
[system   ] 'Summary of earlier conversation:\nU: Hi, my e-bike battery dies overnight even when switched off. Is that norma'
[user     ] 'Every night for a week. It was 2 C last night in the garage.'
[assistant] "Cold alone shouldn't do that. Please send a photo of the battery label and a short video of the drain if you c"
[user     ] 'ok sending now'
[assistant] "Got it — I'll wait for the files."
[user     ] 'btw do you ship to Austria?'
[assistant] 'Yes, we ship across the EU; Austria is covered by the standard 5-8 day window.'
[user     ] 'Also, can I get a loaner bike while it is repaired?'
[assistant] "Loaner bikes are available for warranty repairs at select service points; I'll check availability near you onc"
[user     ] 'How long does a warranty repair usually take?'
[assistant] 'Most battery claims are resolved within 10 business days of receiving the bike.'
[user     ] 'The video is uploading now.'
[assistant] "Perfect — once it lands I'll open the claim and email the return label."
[user     ] 'Will the refund go to my card or store credit?'
[assistant] 'Refunds always go back to the original payment method within 10 business days of inspection.'
[user     ] 'One more thing — the display flickers when it rains.'
[assistant] "That's likely water ingress on the display cable; it's covered under the same warranty. I'll add it to the cla"
[user     ] 'So to confirm: battery + display, one claim, prepaid label?'
[assistant] "Correct — one claim covering both issues, and I'll send the prepaid return label once the photos are verified."

Reading it:

  • Turn 10 crossed the 0.7 threshold (717 projected vs the 693 threshold = 0.7 × 990) and compaction fired once, folding the three oldest turns into the summary — a contiguous prefix, so the summary always describes the oldest surviving history in order.
  • Turn 4 stayed verbatim because compaction met its target first, not because of its score — the victim loop stops once the post-compaction projection fits half the budget. Its importance=0.85 still mattered as insurance: had it been selected as a victim, _carry_forward would have quoted it into the pinned block word-for-word (marked +pinned in the drop log) rather than letting the summarizer paraphrase it away. That's selective retention working.
  • The pinned facts and session_state never moved — they're re-rendered every call regardless of pressure.
  • drop_log is the audit trail: which turns left history, why, their token cost — plus over_budget records for turns that stayed in history but didn't fit the window (none fired here; every turn fit).

11.4 Wiring it to the providers (illustrative)#

render() returns provider-shaped dicts — role, content, tool_calls and tool_call_id are the only keys that survive; importance, meta and any other bookkeeping stay inside the manager. Each provider still needs its own mapping — the system messages become instructions/system/system_instruction, the raw tool_calls/tool_call_id fields need each provider's tool-call/result pairing (03.5, 03.2, Part 6), and the session_state block can be folded into the system prompt or sent as a mid-conversation message where supported. The glue below is illustrative — the manager does the context work, the SDK does the transport:

python
# glue.py — illustrative: map ConversationManager output to each provider.
# The manager's "system" role messages are split out per provider conventions
# (03.2 covers where instructions live on each API).
from conversation_manager import ConversationManager

# `manager` is the ConversationManager built in demo_manager.py; one render per call.
rendered, _stats = manager.render()

def split_system(messages):
    system = "\n\n".join(m["content"] for m in messages if m["role"] == "system")
    rest = [m for m in messages if m["role"] != "system"]
    return system, rest

# Anthropic: system prompt is a separate parameter; history is user/assistant.
import anthropic
client = anthropic.Anthropic()
system, msgs = split_system(rendered)
resp = client.messages.create(
    model="claude-haiku-5-5", max_tokens=1024,
    system=system, messages=msgs)

# OpenAI Responses: `instructions` + `input` items.
from openai import OpenAI
oai = OpenAI()
instructions, items = split_system(rendered)
resp = oai.responses.create(model="gpt-6-luna",
                            instructions=instructions, input=items)

# Gemini generate_content: system_instruction in config; contents use roles.
from google import genai
gem = genai.Client()
system_g, items_g = split_system(rendered)
resp = gem.models.generate_content(
    model="gemini-3.8-flash",
    contents=[{"role": ("user" if m["role"] == "user" else "model"),
               "parts": [{"text": m["content"]}]} for m in items_g],
    config={"system_instruction": system_g})

# OpenRouter: OpenAI-compatible Chat Completions; keep system messages inline.
import os
from openai import OpenAI as OR
orr = OR(base_url="https://openrouter.ai/api/v1",
         api_key=os.environ["OPENROUTER_API_KEY"])
resp = orr.chat.completions.create(
    model="anthropic/claude-haiku-5.5",
    messages=[{"role": m["role"], "content": m["content"]}
              for m in rendered])

Example output (illustrative — your exact output will differ): the Anthropic call returns a Message whose content is a list of blocks; resp.content[0].text is the reply. Append {"role": "assistant", "content": resp.content} back to manager.history (as add_assistant), and the loop continues.


Part 12: Evaluating long-conversation behaviour#

Deep-dive

You cannot eyeball whether your history management works. A summary that looks fine can have dropped the one constraint turn 40 needs; a retention policy that seems sensible can be leaking cost. Long-conversation behaviour needs tests, and the good news is they're cheap to build: the failure modes are mechanical (did fact X survive? did constraint Y get violated?), so a small labelled set plus a stub or real model gives you a regression gate. The method here is the starter version; 10A.11 (Parts 6 and 7) is the full treatment of compaction fidelity and multi-session test design.

12.1 The harness#

The trick is a probe: plant a fact or constraint early, run many turns, then ask about it late. If the management pipeline preserved it, the model answers; if not, it doesn't. retention_test.py below is a pure-local version — the "model" is a stub that can only answer when the evidence is literally in the messages it receives, which makes it a perfect instrument for measuring what survives compaction:

python
"""retention_test.py — fact-retention harness (pure local, no model)."""
from conversation_manager import ConversationManager, chars_per_token

FACT = "refund ceiling is 350 euros"
PROBE = "What is the approved refund ceiling?"


def naive_summarizer(previous, turns):
    """A deliberately weak summarizer: keeps only the first 50 chars of each
    user message — like a real summary that didn't think a detail mattered."""
    parts = []
    if previous:
        parts.append(previous)
    for turn in turns:
        for m in turn:
            if m["role"] == "user":
                parts.append("U:" + (m.get("content") or "")[:50])
    return " | ".join(parts)[:300]


def stub_model(messages, probe):
    """Answers only when the evidence string is in the context it received."""
    haystack = "\n".join(m.get("content") or "" for m in messages)
    if FACT in haystack:
        return "The approved refund ceiling is 350 euros."
    return "I don't have that information."


def build_chat(**overrides) -> ConversationManager:
    kwargs = dict(
        system="You are a billing support assistant.",
        context_window=600, max_output=120,
        pinned_facts=["Customer: Dev"],
        counter=chars_per_token(4.0),
        summarizer=naive_summarizer, summary_allowance=80,
        compaction_ratio=0.7, keep_recent=2,
    )
    kwargs.update(overrides)
    mgr = ConversationManager(**kwargs)
    # Turn 1 plants the fact DEEP inside a long message, past the summarizer's
    # 50-char horizon — the classic 'detail that seemed minor at the time'.
    mgr.add_user(
        "Quick question about my invoice from last month. Also, before we "
        "continue, please note for the file that the refund ceiling is 350 "
        "euros for this account, approved by the finance team on 12 October. "
        + "It was a busy month. " * 12)
    mgr.add_assistant("Noted — refund ceiling of 350 euros recorded for the file.",
                      importance=0.9)
    filler = [
        ("Can you resend the invoice PDF?", "Sent — check your email."),
        ("Did the payment go through?", "Yes, it cleared on the 3rd."),
        ("What plan am I on?", "You are on the Team plan, billed monthly."),
        ("Can I add a seat?", "Yes — I have added one seat to your plan."),
        ("When is the next renewal?", "Your plan renews on the 1st of next month."),
        ("Do you offer annual billing?", "Yes, annual billing saves about 15 percent."),
        ("Is there a student discount?", "We offer 20 percent off for verified students."),
        ("How do I update my card?", "Billing settings -> Payment method -> Update."),
        ("Was there a charge in September?", "Yes, one charge of 49 euros on the 1st."),
        ("Can I get a VAT invoice?", "VAT invoices are available under Billing -> Documents."),
        ("Do you support SSO?", "SSO is available on the Business plan."),
        ("How do I export my data?", "Settings -> Data -> Export gives you a JSON file."),
        ("Is there an API?", "Yes, a REST API with docs at developers.acme.example."),
        ("Can I pause my subscription?", "You can pause for up to 3 months once a year."),
        ("What happens to my data if I cancel?", "Data is exportable for 30 days after cancellation."),
        ("Do you have a mobile app?", "Yes, on iOS and Android."),
    ]
    for u, a in filler:
        mgr.add_user(u)
        mgr.add_assistant(a)
    return mgr


def run(label, manager):
    messages, stats = manager.render()
    answer = stub_model(messages, PROBE)
    print(f"{label}: sent {stats.tokens_used}/{stats.budget} tok, "
          f"{stats.turns_kept}/{stats.turns_in_history} turns, "
          f"summary {stats.summary_tokens} tok, {len(manager.drop_log)} drops")
    print(f"   probe -> {answer}\n")
    return answer


mgr_a = build_chat(context_window=100_000)
mgr_b = build_chat(protect_importance=99.0)
mgr_c = build_chat(protect_importance=0.8)
mgr_d = build_chat(protect_importance=99.0,
                   pinned_facts=["Customer: Dev",
                                 "Account rule: refund ceiling is 350 euros"])
run("A. no pressure (huge window)      ", mgr_a)
run("B. compacted, nothing protected   ", mgr_b)
run("C. compacted, fact turn protected ", mgr_c)
run("D. compacted, fact pinned         ", mgr_d)

print("Summary produced in run B:")
print(mgr_b.summary or "(none)")
print("\nSummary produced in run C:")
print(mgr_c.summary or "(none)")

Run it (python retention_test.py). Real output:

text
A. no pressure (huge window)      : sent 553/94880 tok, 17/17 turns, summary 0 tok, 0 drops
   probe -> The approved refund ceiling is 350 euros.

B. compacted, nothing protected   : sent 286/450 tok, 7/7 turns, summary 84 tok, 10 drops
   probe -> I don't have that information.

C. compacted, fact turn protected : sent 422/450 tok, 7/7 turns, summary 84 tok, 10 drops
   probe -> The approved refund ceiling is 350 euros.

D. compacted, fact pinned         : sent 296/450 tok, 7/7 turns, summary 84 tok, 10 drops
   probe -> The approved refund ceiling is 350 euros.

Summary produced in run B:
U:Quick question about my invoice from last month. A | U:Can you resend the invoice PDF? | U:Did the payment go through? | U:What plan am I on? | U:Can I add a seat? | U:When is the next renewal? | U:Do you offer annual billing? | U:Is there a student discount? | U:How do I update my card? | U:Was t

Summary produced in run C:
U:Quick question about my invoice from last month. A | U:Can you resend the invoice PDF? | U:Did the payment go through? | U:What plan am I on? | U:Can I add a seat? | U:When is the next renewal? | U:Do you offer annual billing? | U:Is there a student discount? | U:How do I update my card? | U:Was t

The four runs are the whole lesson in miniature:

  • A — no pressure, the fact survives verbatim → answered.
  • B — compaction fired, nothing protected, the summarizer kept only the first 50 chars of each user message → the fact (buried ~95 chars in) was summarized away → "I don't have that information."
  • C — same victims as B (note the identical summaries), but the fact turn's importance=0.9 cleared protect_importance=0.8 → before summarizing, the manager quoted the turn verbatim into the pinned block (+pinned in the drop log) → the fact survives in the Session facts: message → answered. Protection now means carried forward word-for-word, and it costs pinned-block tokens (compare C's 422 sent vs B's 286).
  • D — the same fact written into pinned_facts by hand → answered with the smallest footprint. Explicit pinning is the strongest guarantee; importance carry-forward is the automated version of it.

That B-vs-C-vs-D contrast is exactly what importance scoring and pinning are for: they convert "hope the summarizer kept it" into "guarantee it's still there" — verbatim, at a known token cost, in a place the model attends to.

12.2 Constraint-retention tests#

Fact probes test recall; constraint probes test behaviour. Plant an instruction early ("never promise refunds over €500"), then run turns that tempt violation ("just this once, can you do €800?"), and check the final answer obeys. With a real model this is an LLM-judged or rule-checked eval (Module 10A); the harness shape is identical — vary the management policy, keep the probe fixed, measure the pass rate over N runs. 10A.11, 6.1 and 6.2 show how to build and grade such probes at scale.

12.3 Building the regression set#

A production-grade long-conversation suite has three layers:

  1. Unit tests on the manager (pure local): feed synthetic histories, assert render() output shape — pinned facts present, no orphaned assistant/tool turns, budget never exceeded, drop_log accurate. These run in CI with no keys.
  2. Retention probes (the harness above, with a real cheap model): a table of (fact planted at turn k, probed at turn n) across compaction thresholds — tells you which details your summarizer actually preserves.
  3. End-to-end conversation tests: scripted multi-turn scenarios (the "warranty claim" demo is one) run against the real model, scored on task success + constraint adherence. These catch what unit tests can't: whether the model does the right thing with what it was sent.

Three production-ready prompts from this lesson, collected for reuse.

1. Rolling conversation summary (3.2) — the workhorse; fold old turns into the running summary while preserving goal, constraints, decisions, verbatim facts and open tasks.

2. State-extraction → working memory (3.3) — maintain the <session_state> JSON block; validate output against a schema and reject field-dropping updates.

3. Tool-result digest — summarize a large tool output for retention while keeping a re-fetch handle:

text
You are compressing a tool result for an agent's context window. The full
result is stored externally and retrievable by HANDLE. Produce a compact
digest that lets the agent decide whether it needs the full result.

Preserve:
- What the tool was called with (query/arguments, abbreviated)
- The result's shape: count of items, types, key field names
- The 3-5 most decision-relevant facts or values, quoted exactly
- Any errors, warnings or surprising values, verbatim
- HANDLE: the exact reference needed to re-fetch the full result

Drop: boilerplate, repeated structure, items irrelevant to the likely task.
Output ONLY the digest — under 120 words, bullet points.

HANDLE: {{handle}}
TOOL CALL: {{tool_call}}
RESULT:
{{result}}

Common misconceptions#

Misconception Reality
"The model remembers the conversation; I just keep sending messages." The model sees only what you send this call. "Memory" is entirely your selection, trimming and summarization — the model has no continuity of its own.
"A bigger context window means I don't need history management." Bigger windows delay the wall; they don't remove it. Cost still grows quadratically, context rot still degrades quality, and a million-token window still overflows eventually. Management is about quality and cost, not just fitting.
"Summarizing old turns is safe because the summary captures what mattered." Summaries are lossy and biased toward what seemed important then. Constraints and verbatim facts get dropped; the summarizer can fabricate. Pin critical facts and test retention — don't trust it blindly.
"Provider compaction means I don't need my own history management." Provider compaction is a safety net for the wall, not a strategy. It can't pin your facts, score importance, manage tool results or maintain working memory — and its output is opaque to debugging.
"Once a fact is in the summary, it's safe." A summary-of-a-summary drifts each generation. After several compactions the goal itself can blur. Keep raw transcript and re-summarize from it when fidelity matters.
"I should delete old tool results to save space." Delete the content, keep the handle. Stub or summarize with a re-fetch reference so the model can retrieve detail on demand — bare deletion invites hallucination.
"Memories should store everything the user says." Store what improves future answers and nothing more. Everything-stored is noise, cost and privacy surface — and every stored memory is a future prompt-injection vector.
"Making the system prompt more emphatic fixes instruction drift." Drift is a position problem, not a volume problem. Re-inject critical rules near the point of attention (end of context, pinned block) rather than shouting louder at the top.
"Trimming history is free because it only removes old tokens." Every edit to the prefix breaks prompt caching from that point forward. Append-only, batch your compactions, and concentrate cache breaks — trimming has a real cost.
"If it fits in the window, the model will use it correctly." Context rot and lost-in-the-middle mean longer ≠ better. The smallest sufficient context usually beats the maximal one.

Key takeaways#

  • A conversation is a budget you allocate every turn, not a transcript the model reads. Context over time is application code: selection, trimming, summarization, state, memory.
  • Long conversations fail in compounding ways: quadratic cost, context rot, instruction drift, compounding errors (the model can't tell its own past guesses from facts), tool-result floods, and the hard wall.
  • The production stack combines strategies: pinned facts/state (never trimmed) + rolling summary over a contiguous oldest-first prefix (old turns, with a real prompt) + recency window (newest verbatim) + importance carry-forward (high-importance victims quoted verbatim into the pinned block) + tool-result lifecycle + external memory. No single strategy suffices.
  • Compression is lossy and biased. Summary drift, lost constraints and fabrication are real; defend with verbatim pinning, must-preserve prompt sections, and retention tests — never trust a summary blindly.
  • Provider compaction is a safety net, not a strategy. OpenAI's is GA on Responses; Anthropic's is rich but beta; Gemini has none for plain chat; OpenRouter's truncates rather than summarizes. Your own manager gives control, visibility and portability — keep it even when the provider compacts.
  • Tool results are the biggest hogs. Manage them by lifecycle: verbatim when recent, summarized-with-handle when older, stubbed when consumed — and never orphan a call from its result.
  • Memory is a write-back pipeline: extract durable facts, validate and dedupe, store user-owned, retrieve and inject budgeted. Store preferences and decisions; never secrets, excess PII, or transient state.
  • Long tasks span many windows: keep durable state in files and git (a structured task or test file, short progress notes, a start-up script), and prefer a fresh window with a prescriptive start-up prompt over compaction when the state is on disk (6.5).
  • Sub-context isolation keeps the main window clean by delegating noisy sub-tasks to fresh contexts that return only distilled summaries.
  • Fight instruction drift by re-injecting near the point of attention — pinned block and end-of-context reminders — not by making the system prompt louder.
  • Cache-friendliness and correctness both favour append-only histories. Batch compactions, update state at events not every turn, and never edit history in place (it also breaks Claude's preserved thinking).
  • Handle the limit proactively: count before you send, compact at ~60–70% of budget (a heuristic — test it), shed in order (tool results → old turns → memories → summary → recent), and be transparent only when detail was actually lost.
  • Test long-conversation behaviour with fact-retention probes, constraint-retention tests and a regression set — you can't eyeball whether summaries preserve what matters.

Terms introduced in this lesson#

Term Meaning
Context engineering Deciding which tokens enter the window each call, in what order — extended here to managing that set over many turns (02.7)
Context rot Degradation of accuracy/recall as context grows — the quality reason to manage over time (02.7)
Rolling summary A running summary where each compaction folds the previous summary plus newly-old turns into a new one
Hierarchical summary Layered summaries (turn → episode → session) for conversations spanning hours or days
Selective retention Marking some turns as must-keep so they survive compaction that drops the rest
Importance score A per-turn weight deciding compaction priority; from heuristics, a classifier, or code that knows what matters
Carry-forward Quoting a high-importance victim turn's user/assistant text verbatim into the pinned block before it is summarized, so protection survives compaction
Working memory / session state A small structured JSON object (goal, stage, facts, decisions, open tasks) injected as pinned context
Compaction Replacing old turns with a summary — client-side (yours) or server-side (provider's) (02.7)
Compaction item / block The opaque (OpenAI) or signed (Anthropic) object a provider's compaction returns, passed back unchanged
Context editing Anthropic's rule-based clearing of old tool results or thinking blocks, vs summarization
Memory tool Anthropic's memory_20250818: Claude reads/writes files under /memories; your code executes the ops
Short-term vs long-term memory Within-conversation state vs durable cross-conversation facts
Write-back The extract → validate → store → retrieve → inject pipeline that creates long-term memory
Multi-window workflow A long task run across several context windows, with durable state in files and git rather than in the conversation (6.5)
Context awareness A model's ability to track how much of its context window remains; harnesses should tell it whether compaction or note-saving is available so it does not wrap up early
Sub-context isolation Delegating a sub-task to a fresh context that returns only a distilled summary
Instruction drift Behaviour degrading over many turns as the system prompt recedes and recent text dominates
Re-injection / reminder Repeating critical instructions near the point of attention (end of context, pinned block)
Append-only history Never editing past messages — preserves prompt-cache hits and Claude's thinking-block binding
Stable prefix The unchanging head of a request (system + tools) that prompt caching reuses
Proactive compaction threshold Compacting at ~60–70% of budget rather than waiting for the wall
Shedding order The sequence for dropping content under pressure: tool results → old turns → memories → summary → recent
Fact-retention probe A test that plants a fact early and checks recall after many turns
Constraint-retention test A test that plants a rule early and checks the model still obeys it later
Handle / just-in-time retrieval A lightweight reference (path, ID, query) kept in context so content is fetched only when needed

All terms are also collected in the glossary.


Exercises#

  1. Tune the manager. In demo_manager.py, change compaction_ratio to 0.5 and keep_recent to 4. Re-run and compare the turn-10 stats and drop log. Which setting preserves more verbatim detail, and what does it cost? Hint: with compaction_ratio=0.5 and keep_recent=4, compaction starts at turn 5 instead of turn 10 and fires several times, so the drop log grows from three entries to seven and only the last five turns are verbatim at turn 12 (nine with the defaults). The request is smaller, but you pay for more summarizer calls, more summary drift and more cache breaks (Part 9); keep_recent protects only the newest turns, not important older ones.
  2. Break the summary. In retention_test.py, replace naive_summarizer with one that returns a fixed 20-word string. Re-run runs B and C — does the fact survive in each, and why? (Hint: in run C the fact turn's importance=0.9 carries it forward verbatim into the pinned block even though the summary is useless — compare the Session facts: message in the rendered output.)
  3. Add a constraint probe. Extend retention_test.py with a second fact: a user constraint ("never offer discounts over 10 percent") planted at turn 2, then probe at the end whether the manager's sent context still contains it verbatim vs only inside the summary. What does this tell you about where constraints should live?
  4. Provider compaction. Write the OpenAI context_management version of the demo loop (Responses API, store=False, append response.output) and the Anthropic threshold version (client.beta.messages, compact_20260112). Which parts of ConversationManager become unnecessary, and which remain essential?
  5. Tool-result policy. Add a kb_search tool to the demo that returns the POLICY text as a tool message via add_tool_result. Then implement stubbing: after compaction, replace old tool results with [cleared: kb_search, N tokens — re-fetch if needed]. Verify tool calls stay paired with results.
  6. Cache awareness. Instrument render() to report the size of the stable prefix (system + pinned + summary) vs the volatile tail (kept turns). At which turn does the prefix stop being cache-friendly, and what single change would restore it?

Check yourself#

  1. Why does re-sending full history make cost grow roughly with the square of turn count?
  2. Name four of the seven ways long conversations degrade, and which two are specific to managing-over-time rather than context size.
  3. What's the difference between a sliding window "by turns" and "by tokens", and why do you budget by tokens but think in turns?
  4. List the three mechanisms of selective retention and give an example of each.
  5. What are the six things a good summarization prompt must preserve, in priority order?
  6. Explain summary drift and why pinning verbatim facts beats trusting the summary to carry them.
  7. Which provider compaction features are GA vs beta as of November 2026, and which provider has none for plain chat?
  8. Why is provider compaction "a safety net, not a strategy"?
  9. Name four tool-result management techniques and when each applies.
  10. What's the difference between short-term and long-term memory, and what moves a fact from one to the other?
  11. What should never be stored in long-term memory?
  12. How does sub-context isolation keep the main window clean, and what's the bottleneck risk?
  13. Why does making the system prompt "louder" fail to fix instruction drift?
  14. What two reasons make append-only histories both cache-friendly and correctness-required on Claude?
  15. At what threshold do you start compacting, why is it a heuristic, and what's the shedding order under pressure?

Further resources#


← 04.6 — Context Engineering: Selecting and Ordering Context | Module 04 overview | 04.8 — Prompt Patterns for Common Tasks →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close