732. Compact an agent's message history under a token budget
Why it matters Claude Code, Codex and other long-running agents compact context like this when the window fills up.
When an agent's context fills up, old turns are replaced by a summary while recent turns and the system prompt stay.
Write compact_history(messages, budget, summarize). messages is a list of dicts {"role", "content"}; tokens of a message = len(content.split()). messages[0] is the system prompt and always stays. If the total fits the budget, return messages unchanged. Otherwise keep the longest suffix of the remaining messages whose tokens plus the system prompt plus a summary fit: build the summary of the dropped middle with summarize(list_of_dropped) (returns a string), and insert {"role": "system", "content": "Summary: " + text} after the system prompt. Never split a tool result from the assistant message just before it: if the first kept message has role "tool", drop it into the summary too. Return the new list.
def compact_history(messages, budget, summarize)Example 1
if everything fits, the output equals the input.
Constraints
- Python 3 standard library. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Grow the kept suffix from the end; the summary's own tokens count toward the budget.
Hint 2
Return early if it fits.
Hint 3
Try dropping 0, 1, 2 ... messages from the front of the non-system part.
Hint 4
Skip a leading tool message in the kept tail.
Hint 5
Count the summary's tokens.
Common mistakes
- Not counting the summary in the budget.
- Leaving an orphaned tool result at the start of the kept tail.
Understand the idea
When an agent's history gets too long for its context, old turns are squeezed into a short summary. The system prompt always stays, the most recent turns stay, and everything in between is replaced by one summary message. The summary counts toward the budget. A tool result must never appear without the assistant call before it.
tokens are word counts. System prompt 3 tokens, then user 10, assistant 10, tool 10, user 4: total 37, budget 25. Suppose the summary message is 4 tokens. Keeping [user 4] costs 3 + 4 + 4 = 11, fine. Keeping [tool 10, user 4] costs 21, fine. Adding the assistant gives 31, too much. The longest fitting tail starts with a tool message, which would be orphaned, so the tool joins the dropped part. Result: [system, summary, user 4].
if the total fits, return messages unchanged; else find the longest suffix of messages[1:] such that system + summary + suffix fits; if its first message has role 'tool', move it into the dropped list; summary = {'role': 'system', 'content': 'Summary: ' + summarize(dropped)}; return [system, summary] + keptUsed in: long-running coding and chat agents.
Shapes and data flow
[system | m1 m2 m3 m4 m5] -> [system | Summary(m1 m2) | m3 m4 m5] kept tail never starts with a tool message