Truncate a long tool result to a token budget keeping head and tail

EasyAgents

Why it matters Agent runtimes truncate tool output on every step; without it one large file read can blow the context window.

Tool results such as logs or web pages can be huge. Agents keep the start and the end, where the useful lines usually are, and replace the middle with a marker.

Write truncate_tool_output(tokens, budget, head_frac). tokens is a list of strings, budget an int >= 1. If len(tokens) <= budget, return the list unchanged (a copy). Otherwise the marker uses one token of the budget: avail = budget - 1, h = int(avail * head_frac), t = avail - h, omitted = len(tokens) - h - t. Return tokens[:h] + ["[" + str(omitted) + " tokens omitted]"] + the last t tokens (no tail if t == 0).

Signaturedef truncate_tool_output(tokens, budget, head_frac)

Example

truncate_tool_output(list("abcdefghij"), 5, 0.5) gives ['a', 'b', '[6 tokens omitted]', 'i', 'j'].

Understand the idea

Agents read tool outputs straight into their context window. A stack trace, a long web page or a big file can easily be larger than the space left. Cutting only the end loses error messages that usually appear last; cutting only the start loses headers. A common compromise keeps a head and a tail and drops the middle, with a marker saying how much was removed.

Example: 10 tokens a to j with a budget of 5. One token goes to the marker, leaving 4: 2 for the head (a, b) and 2 for the tail (i, j). The 6 middle tokens become "[6 tokens omitted]". The result has exactly 5 tokens.

Rule: if n <= B keep all; else h = floor((B - 1) * f), t = B - 1 - h, output head + marker + tail.

Coding agents apply this to shell output and file reads on every step.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 5.

  • Sample 1: exampletruncate_tool_output(list('abcdefghij'), 5, 0.5)
  • Sample 2: fitstruncate_tool_output(['x', 'y'], 2, 0.5)
  • Test 3: head heavytruncate_tool_output([str(i) for i in range(20)], 8, 0.75)
  • Test 4: all tailtruncate_tool_output(list('abcdef'), 3, 0.0)
  • Test 5: tiny budgettruncate_tool_output(list('abcdef'), 1, 0.5)