BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Agents17 of 28 in topic

732. Compact an agent's message history under a token budget

HardAgents Pro

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.

Functiondef 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.

Worked example

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] + kept

Used 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
Topics
Agents
Similar questions
  • Validate tool arguments against a schema before callingHard
  • Schedule an agent's task plan into parallel waves with cycle detectionHard
  • Repair a truncated JSON tool call from a streaming modelHard
  • Parse a full multi-step ReAct trace into structured stepsHard
All Agents problems
Report
732 / 903
Python 3solution.pyPython idle
1
2
3
4
def compact_history(messages, budget, summarize):
# your code here
pass
​
compact_history(_M[:2], 100, _sum) == _M[:2]

This case uses generated data, so it runs as written. Press + to add your own case.

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS