GNGiseldo Neo and Alana NeoBooks
Building AI Agents8 / 18

Context: the memory that costs money

“A conversation’s history is the only asset of an agent that only ever grows.”

Objective

Understand why an agent’s cost grows faster than the number of steps, measure tokens honestly, and implement context compaction with a sliding window and a rewritten summary — the version that converges instead of growing forever.

5.1 Quadratic cost

Every conversation with a model is stateless on the provider’s side: you resend the entire history at each step. This means an agent’s cost grows roughly quadratically with the number of steps, because each step resends everything that came before.

A concrete example. Suppose each step adds cc tokens to the history. In step 1, you send cc. In step 2, you send 2c2c. In step nn, you send ncnc. The total is:

total=c∑k=1nk=c n(n+1)2\text{total} = c\sum_{k=1}^{n} k = c\,\frac{n(n+1)}{2}

For n=30n = 30 steps, that is 465 units of cc — not 30. A thirty-step agent does not cost thirty times as much as a one-step agent; it costs fifteen times more than linear.

Understanding this changes the design. The goal stops being “make fewer calls” and becomes “make each call carry less”.

5.2 Measure before optimizing

Before deciding how to save, measure — with the model’s own tokenizer, when available (OpenAI 2023). And measure for real: estimates of “4 characters per token” are quite inaccurate, especially with code, accented characters and languages such as Portuguese.

Listing 5.1. Token counting with an explicit fallback.

def count_tokens(text: str) -> tuple[int, str]:
    try:
        import tiktoken
        enc = tiktoken.get_encoding("cl100k_base")
        return len(enc.encode(text)), "tiktoken/cl100k"
    except Exception:
        return max(1, round(len(text) / 3.6)), \
               "heuristic ~3.6 chars/token (ESTIMATE)"

The rule the code implements is important: if you cannot measure, say that you are estimating. Never present an estimate as a measurement.

About the 3.6 factor. Portuguese text with diacritics falls close to 3.5 to 4 characters per token in modern vocabularies; Python code tends to fall close to 3.2 to 3.6, because punctuation and indentation consume tokens. The factor is an average and is not suitable for precision decisions — it is good for orders of magnitude. For precision, use the tokenizer of the model you are using.

5.3 Three compaction strategies

When the history grows beyond the budget, there are three families of solutions.

Truncate. Discard the oldest messages. Simple, cheap and brutal: you lose the beginning of the conversation, which often contains the goal.

Sliding window with summary. Keep the NN most recent messages and replace the rest with a summary. This is what most serious harnesses do.

Hierarchical summarization. Summarize summaries. Useful for very long sessions, expensive and prone to drift.

The naive implementation of the sliding window has a subtle flaw: if each compaction stacks a new summary, the context does not converge — it becomes a pile of summaries that grows forever. The fix is to rewrite the summary, not to append.

5.4 The naive version, and what it reveals

Listing 5.2 shows the implementation that looks right and is not.

Listing 5.2. Compaction that stacks summaries (the antipattern).

def compact(self) -> None:
    system = [m for m in self.messages if m.role == "system"]
    rest = [m for m in self.messages if m.role != "system"]
    if len(rest) <= self.keep_recent:
        return
    old, recent = rest[:-self.keep_recent], rest[-self.keep_recent:]
    facts = [m.content[:60] for m in old if m.role == "tool"]
    summary = f"[summary of {len(old)} msgs] facts: " + " | ".join(facts[-3:])
    self.summaries.append(summary)          # <- stacks
    self.messages = system + [Msg("system", summary)] + recent

After eight steps, this is the final history:

Listing 5.3. Output of naive compaction: the pile of summaries grows.

system: You are a diagnostic agent.
system: [summary of 4 msgs] facts: result 1: item 1 is ok, latency 12ms,
system: [summary of 2 msgs] facts: result 3: item 3 is ok, latency 12ms,
system: [summary of 1 msgs] facts:
system: [summary of 1 msgs] facts: result 4: item 4 is ok, latency 12ms,
system: [summary of 1 msgs] facts:
system: [summary of 1 msgs] facts: result 5: item 5 is ok, latency 12ms,
...

Nine summaries after eight steps. The context did not converge; it changed shape. Instead of growing with the original content, it grows with the summaries of the original content.

5.5 The version that converges

The fix is to rewrite the summary and give it a ceiling. With the ceiling, the context converges.

Listing 5.4. Compaction with a rewritten, bounded summary.

SUMMARY_CAP = 200  # chars — the summary never exceeds this

def compact(self) -> None:
    if len(self.recent) <= self.keep_recent:
        return
    leaving, self.recent = (self.recent[:-self.keep_recent],
                            self.recent[-self.keep_recent:])
    facts = [m.content[:40].replace("\n", " ")
             for m in leaving if m.role == "tool"]
    merged = "; ".join(filter(None, [self.summary] + facts))
    self.summary = merged[-SUMMARY_CAP:]   # ceiling: drops the oldest
    self.compactions += 1

Running twenty steps with this compactor:

Listing 5.5. Output: the context stabilizes.

step  4: recent=3 summary= 82ch ~ 70 tok  compactions=1
step  8: recent=3 summary=200ch ~100 tok  compactions=4
step 12: recent=3 summary=200ch ~100 tok  compactions=8
step 16: recent=3 summary=200ch ~100 tok  compactions=12
step 20: recent=3 summary=200ch ~100 tok  compactions=16

The summary stabilizes at 200 characters. The context stops growing. That is what you want.

Common pitfall

Thinking that a sliding window is enough. Without a ceiling on the summary and without truncating tool outputs, the context still grows — slowly, but it grows. Two measures, together, solve it: truncate at the source (Chapter 3) and bound the summary. Neither one alone is enough.

5.6 What can never be compacted

Some things cannot leave the context, no matter how much it grows:

  • The original goal — what the user asked for. Without it, the agent loses its way.

  • The constraints — what is forbidden. Without them, the agent may violate a policy that had been explicit.

  • The current state of the task — what has been done and what remains. Without it, the agent repeats work.

A good compactor treats these three as anchors and compacts only the middle. In practice, this means never putting the system messages and the first user message in the “disposable” part.