Trail content
9 minEnglish narration, Portuguese subtitlesPodcast (RSS)
Chapters
  1. 0:00Opening
  2. 0:59The idea
  3. 1:13Before and after
  4. 1:50A real case
  5. 2:38Why it works
  6. 3:27A challenge
  7. 3:58Safe mechanics
  8. 5:34Risks
  9. 7:05A fact that changes
  10. 7:41When not to use it
  11. 8:09Wrap-up
Transcript

Opening

A school's math tutor runs on WhatsApp. In lesson one, it agreed with a student: hints only, never the finished answer. In lesson six, she asked for a review sheet with an answer key, and the tutor allowed it, as an exception, for that sheet.

In lesson twelve, she asks for help with a new problem. The history holds both rules, several pages of wrong working, three schedule changes, and a note from her mother. And the model returns the finished answer. Or, the next day, it refuses even the review sheet, because the rule is hints only.

With illustrative numbers, by lesson twelve, every call already sends about nine thousand five hundred tokens of history. By lesson forty, past seventeen thousand. And the lesson one rule competes with everything that came after. You met this smell in the last lesson. Now you'll fix it, safely.

The idea

Replace old turns with a summary. Keep the facts that must last in explicit state, outside the raw history. And send the model the state, the summary, and only the recent turns.

Before and after

Before, the entire history goes into every call. Message, everything, model, answer.

After, the new message arrives, and only the latest turns stay in raw form.

Durable facts, like preferences, decisions and ids, plus a summary of the rest, live in a separate block.

The model receives that block, plus the recent turns. And the answer joins the recent turns.

When the recent turns pass a limit, a compaction step updates the summary and the facts, and drops the old turns.

A real case

Here's what the model sees after the lesson twelve compaction. The state block. The student's name. Her level per topic, intermediate in equations, beginner in geometry. Step by step hints as the format.

And the rule, on a single line. Hints only. With the exception beside it, and its scope. The lesson six review sheet.

Then a summary, in a few lines. Lessons one to eleven: quadratic equations, stuck on completing the square. Lesson six, the review sheet exception. Lesson eleven, started geometry. And the eight most recent turns stay whole. The mother's note, and the wrong working from lesson three, don't go in.

Why it works

Raw history mixes three things. Facts that still hold, context that explains the moment, and noise that no longer matters. The model gets all three with equal weight. Separating them gives each a different weight. Facts sit in a short block that's always present. The summary tells the story in a few lines. And the noise goes away.

Explicit state solves the rule that changes. Instead of the model finding two contradictory rules at different points in the history, there's one line, with the exception beside it. Compaction updates that line, and you can read and test what it wrote.

And cost stays flat. The recent turns have a bounded size, the facts grow slowly, and the summary has a word cap.

A challenge

Here's one for you. Say you only add a summary, with no facts block. Why does the tutor still get the hints rule wrong, so often?

Because a summary is a narrative. One paragraph mixes the current rule with the exception, and the two compete again. The model has no single field to consult. A solution mode field, with the exception's scope next to it, makes it explicit what's in force.

Safe mechanics

Step zero, measure. Build an eval from real long sessions, anonymized, with questions that depend on something said early. The hints rule, the account id, the delivery zip code. Record accuracy, cost per turn, and time to the first word, at the end of the sessions.

List your domain's durable facts. Ids, preferences, agreed rules, decisions, and exceptions with their scope. They become a schema.

Write the compaction prompt to ask for two outputs. The updated facts, structured, and a short summary of what happened. And ask for the source, the turn or the lesson, of each change to a fact.

Pick the trigger, a token or turn count. And always keep the latest turns whole. Eight to twelve is a common starting point. Tune it against the eval.

Run compaction off the critical path when you can, between turns or in the background. The student shouldn't wait for the lesson eleven summary to get the lesson twelve hint.

Keep the full history outside the context, for auditing, and for rebuilding the summary if it goes wrong.

Record every compaction on the trace, with the facts before and after. If the solution mode changed without the student asking, you see it right away.

And measure again. Accuracy on questions that depend on early turns should hold or rise. Cost per turn at the end of sessions should drop.

Risks

Now the risks. A summary that loses the right fact. You catch it with eval cases that ask about old facts, and by comparing the facts before and after on the trace.

A summary that makes things up. The compaction model may join things that were never said together. The student asked for answer keys on every sheet. Ask for facts with a reference to their source turn, and reject any fact with no source.

Errors that compound. Each summary builds on the previous one. A small drift in lesson eight becomes a false rule in lesson twenty. Keep the raw history, and rebuild from it now and then, not only from the last summary.

And a prompt cache that keeps resetting. If you compact every turn, the start of the context changes every time, and the cache almost never hits. Compact in blocks, when the recent turns pass a cap, so the prefix stays stable between compactions.

And the common mistake. Compacting only when the window fills. If you wait for the API to reject the context, the session is already expensive, and the model is already lost in the middle. The trigger is a limit you choose, below the window, at the point where the eval still gets the old questions right. Compacting too early hurts too. You drop detail from the current conversation. That's why the latest turns stay whole.

A fact that changes

One more case, where money is involved. A bank's WhatsApp bot stores a payment key in state. An old turn had the wrong key, and it was corrected later. After compaction, the state still shows the old key. What failed? Compaction treated the correction as one more sentence in the summary, not as an update to the key field. A durable fact has to be a field. And the correction has to overwrite the old value, with the correction turn as its source. Otherwise the next payment goes to the old destination.

When not to use it

And when is this the wrong tool? A three turn support session, where the customer is still describing the problem. There's no past to compact. Summarizing now throws away detail the next answer needs.

And an assistant that pastes thirty-seven policies into its system prompt on every call. That isn't session history. It's pasted knowledge. Take it out of the prompt, and retrieve the current passage.

Wrap-up

So here's the idea to take with you. Split the history by what it's for. Facts that must last become fields, with sources. The past becomes a short story. The present stays whole. Measure with questions about the beginning, keep the raw history for audits, and compact in blocks.

In the next lesson, we'll look at the full pattern this refactoring leads to, including agents that compact their own work mid-task: context compaction. See you there.

RefactoringOrganizing data

Replace History with Summary

Trocar Histórico por Resumo

Replace History with Summary is an AI refactoring for LLM systems, in the Organizing data group. Replace old turns with a summary and with facts stored outside the context.

Element
16/35
Level
Intermediate
Read
5 min
Updated
On this page 8
  1. 01Problem
  2. 02Solution
  3. 03Before and after
  4. 04Why it works
  5. 05Safe mechanics
  6. 06Risks
  7. 07Challenge
  8. 08Check your understanding
  9. ··Quick answers

Problem

The session carries its entire history, which only grows, confuses the model, and makes every turn more expensive. This is the Context Rot smell.

The school’s WhatsApp math tutor agreed, in lesson 1: “hints only, never the finished answer”. In lesson 6 the student asked for a review sheet with an answer key, and the tutor allowed it as an exception for that sheet. In lesson 12 she asks for the equation of a new problem. The history holds both rules, several pages of wrong working, three schedule changes, and a note from her mother. The model returns the finished answer. Or, the next day, it refuses even the review sheet, because “the rule is hints only”.

The paper “Lost in the Middle” (Liu et al., 2023) documented the same kind of failure in long-context reading: models find information in the middle of a large context worse than information at the start or the end. A session that lasts weeks is that context, renewed every turn.

The numbers below are illustrative. Suppose a 1,500-token system prompt and about 200 tokens per turn (question plus answer). By lesson 12, with 40 turns, each call already sends about 9,500 tokens of history. By lesson 40, that passes 17,000, and the lesson-1 rule competes with everything that came after.

Solution

Replace old turns with a summary and keep the facts that must last in explicit state, outside the raw history. Send the model the state, the summary, and only the recent turns.

Before and after

 def answer(session, user_msg):
-    session.messages.append(user(user_msg))
-    reply = call_model(SYSTEM, session.messages)          # everything, always
+    session.messages.append(user(user_msg))
+    if tokens(session.messages) > COMPACT_AT:
+        old, recent = split(session.messages, keep_last=8)
+        session.summary = summarize(session.summary, old)  # rolling summary
+        session.facts.update(extract_facts(old))           # durable facts
+        session.messages = recent
+    context = [state_block(session.facts, session.summary), *session.messages]
+    reply = call_model(SYSTEM, context)
     session.messages.append(assistant(reply))
     return reply

Before: the entire history goes into every call.

flowchart LR
  U(["1. Message"]):::io --> H[("2. Entire history")]:::store
  H --> M(["3. Model"]):::llm
  M --> R(["4. Answer"]):::io

After: state, summary, and recent turns, with compaction off the main path.

flowchart LR
  U(["1. Message"]):::io --> H[("2. Recent turns")]:::store
  F[("3. Facts and summary")]:::store --> M(["4. Model"]):::llm
  H --> M
  M --> R(["5. Answer"]):::io
  H -->|"over the limit"| C(["6. Compact"]):::llm
  C --> F
  1. The new message arrives.
  2. Only the latest turns stay in raw form.
  3. Durable facts (preferences, decisions, ids) and a summary of the rest live in a separate block.
  4. The model receives the state block, the summary, and the recent turns.
  5. The answer goes out and joins the recent turns.
  6. When recent turns pass the limit, a compaction step updates the summary and facts and drops the old turns.

What the model now sees

After the lesson-12 compaction, the state block can be:

{
  "student": "Ana",
  "level": {"equations": "intermediate", "geometry": "beginner"},
  "format": "step-by-step hints",
  "solution_mode": "hints_only",
  "solution_mode_exceptions": [
    {"scope": "lesson 6 review sheet", "mode": "full answer key"}
  ]
}

The summary, in a few lines: “Lessons 1 to 11: quadratic equations, stuck on completing the square. Lesson 6: review sheet with answer key, agreed exception. Lesson 11: started geometry, Pythagorean theorem.” The eight recent turns stay whole. The current rule sits on a single line. The mother’s note and the wrong working from lesson 3 do not go in.

Why it works

Raw history mixes three things: facts that still hold, context that explains the moment, and noise that no longer matters. The model gets all three with equal weight. Separating them gives each a different weight: facts sit in a short block that is always present, the summary tells the story in a few lines, and the noise goes away.

Explicit state solves the case of the rule that changes. Instead of the model finding two contradictory rules at different points in the history, there is one line: solution_mode: hints_only, with the lesson-6 sheet exception beside it. Compaction updates that line, and you can read and test what it wrote.

Cost stays flat: context size stops depending on the session’s age. Recent turns have a bounded size; the facts block grows slowly; the summary has a word cap. The destination pattern is Context Compaction.

Check +20 XP on first tryIn lesson 12 the tutor returns the finished answer, against the lesson-1 agreement. The history has 40 turns, including the lesson-6 sheet exception. Why does a summary alone, with no facts block, still fail often?

Safe mechanics

  1. Measure. Build an eval from real long sessions (anonymized) with questions that depend on something said early: the hints rule, the account id, the delivery ZIP code. Record accuracy, cost per turn, and time to first token at the end of the sessions.
  2. List your domain’s durable facts: ids, preferences, agreed rules, decisions, exceptions with scope. They become a schema, in the same spirit as Replace Free Text with Structured Output.
  3. Write the compaction prompt asking for two outputs: updated facts (structured) and a short summary of what happened. Ask for the source (turn or lesson) of each fact change.
  4. Pick the trigger: a token or turn count. Always keep the latest turns whole. A cap of 8 to 12 recent turns is a common starting point; tune it against the eval.
  5. Run compaction off the critical path when you can, between turns or in the background. The user should not wait for the lesson-11 summary to get the lesson-12 hint.
  6. Keep the full history outside the context, for auditing and for rebuilding the summary if it goes wrong.
  7. Record every compaction on the trace, with facts before and after. If solution_mode changed without the student asking, you see it immediately.
  8. Measure again. Accuracy on questions that depend on early turns should hold or rise; cost per turn at the end of sessions should drop.

Risks

  • A summary that loses the right fact. An important detail disappears in compaction. Detect it with eval cases that ask about old facts, and by comparing facts before and after on the trace.
  • A summary that makes things up. The compaction model may join things that were not said together (“the student asked for answer keys on every sheet”). Ask for facts with a reference to their source turn, and reject a fact with no source.
  • Compounding error. Each summary builds on the previous one. A small drift in lesson 8 becomes a false rule in lesson 20. Keep the raw history and rebuild now and then from it, not only from the last summary.
  • Invalidated cache. Changing the start of the context on every compaction can reset the prompt cache. Compact in blocks, not every turn, so the prefix (system prompt plus facts block) stays stable between compactions.

Common mistake: compacting only when the window fills

If you wait for the API to reject the context, the session is already expensive and the model is already lost in the middle. The trigger is a limit you choose, below the window, at the point where the eval still gets the old questions right. Compacting too early also hurts: you drop detail from the current conversation. That is why the latest turns stay whole.

Check +20 XP on first tryYou compact every turn to 'keep the context clean'. The call prefix changes every time, the prompt cache almost never hits, and cost per turn did not drop the way the team expected. Which adjustment comes first?

Challenge

This compaction prompt produces nice summaries that lose information. What is it missing?

Summarize the conversation below in one paragraph, clearly and concisely.
Show solution

It is missing three things: saying what must survive, separating facts from narrative, and handling the previous summary.

You update the memory of a tutoring session.

Input: the current facts (JSON), the previous summary, and the new turns.

1. Update the facts: the student's level per topic, format preferences,
   and agreed rules. If a new rule has a limited scope (one sheet, one
   lesson), record the scope. Cite the source turn for each change.
2. Rewrite the summary in at most 120 words, folding in the previous one.
   Only what helps the next lesson: what was covered, where she got stuck.
3. Do not invent anything that is not in the turns.

Check your understanding

Check +20 XP on first tryThe long-session eval gets the lesson-1 rule questions right, but 8% of compactions invent a preference the student never stated. The raw history is stored. What is the most useful next step?

Check +20 XP on first tryA bank's WhatsApp bot stores, in state, pix_key and the session's agreed limit. Pix is Brazil's instant payment system. An old turn had the wrong key, later corrected. After compaction, state still shows the old key. What failed?

Check +20 XP on first tryYou keep the last 8 turns raw and compact the rest. A lesson-12 question depends on an exercise solved in the turn that just left the recent window. How should the design behave?

Check +20 XP on first tryIn which of these cases is compacting history the wrong tool, and what should you use instead?

Quick answers

What is Replace History with Summary?

Replace History with Summary is an AI refactoring for LLM systems, in the Organizing data group. Replace old turns with a summary and with facts stored outside the context.

What problem does Replace History with Summary solve?

It treats Context Rot.

Which pattern does Replace History with Summary lead to?

The Context Compaction and Short-Term Memory design pattern.

Go further

Relations

Smells it treats 1
Part of the tracks 1
Search