Skip to content

Trim history without losing the goal

Chat apps re-send the conversation on every call. That is how the model "remembers". It is also why long chats get slow, costly and confused. At some point you have to cut. The trick is to cut the right things.

What to always keep

What you can usually drop: small talk, old drafts the user rejected, long tool output already acted on, and repeated questions.

Simple version: newest turns that fit

Keep the system messages, then walk backward from the newest turn, adding turns until you hit the budget. Everything older is dropped.

def trim(messages, budget, count):
    """Keep the system prompt and the newest turns that fit in `budget` tokens.
    `count` is any function text -> tokens. Returns (kept, dropped)."""
    system = [m for m in messages if m["role"] == "system"]
    rest = [m for m in messages if m["role"] != "system"]
    used = sum(count(m["content"]) for m in system)
    kept = []
    for m in reversed(rest):
        c = count(m["content"])
        if used + c > budget:
            break
        kept.insert(0, m)
        used += c
    dropped = rest[: len(rest) - len(kept)]
    return system + kept, dropped

if __name__ == "__main__":
    words = lambda t: len(t.split())  # stand-in counter for the demo
    msgs = [{"role": "system", "content": "Goal: plan a 3-day trip. Budget fixed."}]
    msgs += [{"role": "user" if i % 2 == 0 else "assistant", "content": f"turn {i} " * 10} for i in range(12)]
    kept, dropped = trim(msgs, 60, words)
    print("kept", len(kept), "dropped", len(dropped), "system kept:", kept[0]["role"] == "system")

In real code, pass a real token counter (see Count tokens before you send) instead of the word counter used in the demo.

Better version: add a running summary

The simple version forgets the goal as soon as the first turns fall off. Fix that with a short summary that you keep updated:

  1. Hold a "notes" string next to the chat: goal, facts, decisions.
  2. When turns are dropped, ask the model (or your code) to fold anything important from them into the notes. Keep the notes short, with a fixed token cap.
  3. Send: system prompt, then notes, then the newest turns.

The summary call costs tokens too, so run it only when you actually drop turns, not every call.

Mind the cache

If your provider caches repeated prompt prefixes, the order matters. Keep stable text (system prompt, tool definitions) first and unchanged. Put the changing parts (notes, recent turns) after it. Editing the start of the prompt every turn can stop the cache from being reused.

How to know it works

Checklist

Related: Long-chat drift and Stale tool results.

All field notes