AI Agents by HandAll problemsAbout

All problems › Agent problem · hard · ~20 min

Compact long history

context compaction token budget SDK blocks

Solve it in your browser →

Keep a long chat under budget (~20 min)

compact_history.py is the help-desk Agent without streaming. Help-desk chats run long: every send re-sends the whole history, tool results included, so cost and latency grow with every turn until the conversation no longer fits. compact_at, SUMMARY_SYSTEM and SUMMARY_PREFIX are provided; _compact is a stub.

Goal: when the conversation gets too big, replace it with a summary written by the model, so the next requests are small but the assistant still remembers what matters.

  1. After every model response, remember its response.usage.input_tokens.
  2. At the start of send, before adding the new user message: if the most recent request used more than compact_at input tokens, compact. Never compact in the middle of a tool loop.
  3. Compacting is one extra model call: system=SUMMARY_SYSTEM, no tools, and a single user message containing the conversation as plain text: user messages, assistant text, tool calls (name and input) and tool results. Facts that only appeared in a tool result (a ticket's status, an article's steps) must reach the summarizer.
  4. Afterwards the old messages are gone. The summary (with SUMMARY_PREFIX) is carried forward, either in the system prompt or at the start of the history, your choice, and the new user message is sent as usual. If the conversation is compacted again later, what the earlier summary said must not be lost.
  5. Compaction is an optimization: if the summary call raises, keep the full history and carry on with the send as if nothing happened.
  6. The tool loop, is_error results and max_turns keep working.

Before you write code, decide what the summary request can and can't contain (what does the API require of a request whose messages include tool_use blocks?), and where you'll put the summary.

Be ready to discuss: what's lost in a summary and how you'd test that it isn't, what a token threshold measures that a message count doesn't, and when you'd use server-side compaction or context editing instead of doing it yourself.

Try it: python -m compact_history Check it: pytest tests/test_compact_history.py

Starter code and hidden tests open in the editor. Nothing to install.