Truncate Oversized Tool Output With Preview

Basics
BasicsContext EngineeringCompactionOpenAIAnthropicGoogle

Problem

Implement truncate_tool_output(output, max_chars) that returns output unchanged if len(output) <= max_chars, and otherwise returns output[:max_chars] + "...[TRUNCATED]".

Why It Matters: A single verbose API or SQL tool response can dump 50,000 characters into an agent's context window—truncation protects token budgets and prevents context overflow.

Function Signature

def truncate_tool_output(output: str, max_chars: int) -> str:
    """Truncate long tool outputs to max_chars + '...[TRUNCATED]'."""

Sample Input & Output

Example 1: Oversized Tool Output

Input:

output = "abcdefghij", max_chars = 4

Expected Output:

"abcd...[TRUNCATED]"

Explanation: Length 10 > 4, so only the first 4 characters are kept followed by ...[TRUNCATED].

Example 2: Exact Boundary Length (No Truncation)

Input:

output = "abcd", max_chars = 4

Expected Output:

"abcd"

Explanation: When len(output) == max_chars, the string fits cleanly and must NOT be truncated.

Constraints & Edge Cases

  • Return a str.
  • Check len(output) <= max_chars (inclusive).
  • Exact suffix string must be '...[TRUNCATED]'.

Constraints & Evaluation Criteria

  • Return a `str`.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
'abcdefghij', max_chars=5
Expected Output / Criteria
'abcde...[TRUNCATED]'