Neural Mastery
← Practice
Truncate Oversized Tool Outputeasy

Truncate Oversized Tool Output

easy Agents in Production 15 min

NumPy allowed · plain Python earns 10 bonus points

Implement tool-output truncation with a clear indicator, protecting an agent's context window from being consumed by one oversized tool result.

Task

Implement truncate_tool_output(output, max_chars). If len(output) <= max_chars, return it unchanged. Otherwise return the first max_chars characters followed by the literal string '... [truncated N more chars]' where N is the number of characters that were cut.

Function Signature

truncate_tool_output(output: str, max_chars: int) -> str

Examples

Example 1: under limit unchanged
Input: output = 'short' max_chars = 100
Output: 'short'
Example 2: over limit truncated with indicator
Input: output = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' max_chars = 100
Output: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa... [truncated 50 more chars]'
Example 3: exactly at limit unchanged
Input: output = '1234567890' max_chars = 10
Output: '1234567890'

Constraints

  • max_chars >= 0
Python3Saved ✓
def truncate_tool_output(output, max_chars):
# Your implementation here
pass

Case 1: under limit unchanged
Input: output = 'short' max_chars = 100
Expected: 'short'
Case 2: over limit truncated with indicator
Input: output = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' max_chars = 100
Expected: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa... [truncated 50 more chars]'
Case 3: exactly at limit unchanged
Input: output = '1234567890' max_chars = 10
Expected: '1234567890'