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
- The system prompt. Never let trimming remove it.
- The goal. What the user is trying to do, in one or two lines.
- Hard facts. Names, IDs, numbers, decisions already made.
- The latest few turns. The model needs the immediate context to answer.
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:
- Hold a "notes" string next to the chat: goal, facts, decisions.
- 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.
- 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
- Run a long scripted chat, then ask about a fact from the first turn.
- Check that the system prompt is present in every request you log.
- Compare tokens per call before and after: it should level off instead of growing forever.
Checklist
- Never drop the system prompt.
- Keep a short goal-and-facts summary.
- Fill the rest with the newest turns under a fixed budget.
- Keep stable text first for caching.
- Test recall of early facts.
Related: Long-chat drift and Stale tool results.