Trim an agent's chat history to fit a token budget
Agent loops grow the conversation every turn and eventually overflow the context window. The simplest guard keeps the system prompt plus the most recent turns that fit. The kept turns must be a contiguous tail, otherwise a tool result can end up without the call that produced it.
Write trim_history(messages, budget). Each message is a dict with keys "role" and "tokens" (int).
- If messages[0]["role"] == "system", it is always kept and its tokens count toward the budget.
- Then walk from the newest message backwards, keeping messages while the running total stays <= budget. Stop at the first message that does not fit (do not skip it and keep older ones).
Return the sorted list of kept indices. If even the system message alone exceeds the budget, return [0] anyway.
def trim_history(messages, budget)Example
tokens [system 10, user 50, assistant 30, user 20], budget 65: keep 0, then 3 (30 total), then 2 (60), then 1 would make 110, stop. Result [0, 2, 3].
Understand the idea
An agent's chat history grows every turn until it no longer fits the model's context window. A simple fix keeps the system prompt and then as many of the newest messages as fit. The kept messages must form one unbroken run at the end; if you skip a big message and keep older small ones, a tool result can lose the call that produced it. Worked example: tokens [system 5, user 40, assistant 10, tool 30, user 15], budget 60. Keep the system message: 5. Walk from the newest: user 15 gives 20, tool 30 gives 50, assistant 10 gives 60 (allowed, since 60 <= 60), user 40 would give 100, so stop. Kept: [0, 2, 3, 4]. With budget 55, adding the assistant message would reach 60, so stop there with [0, 3, 4], even though nothing older is tried. Rule: if message 0 is a system message, always keep it and count its tokens; then walk backwards while the running total stays within budget, stop at the first miss; return the kept indices sorted. If the system message alone is too big, return [0]. Used in every agent framework's memory manager.