Pruning Hooks for Deduplication, Extraction, and Truncation
Learn how to measure tool-result growth and build a pruning hook that deduplicates repeated outputs, extracts needed fields, and truncates long logs. Preserve complete results in files, recover omitted details through tools, and reduce context size without losing information.
We'll cover the following...
In Chapter 4, we improved retrieval accuracy. The on-call assistant now retrieves relevant notes, filters out outdated content, and verifies quotations. However, retrieved content is only one source of context. During an incident, the assistant makes many tool calls. It performs searches, retries failed requests after time-outs, reads notes, and retrieves deployment test logs. In the current implementation, each tool call adds its full result to the conversation history, increasing the context size for subsequent turns.
In this lesson, we'll measure how quickly tool results increase context size. Then we'll build a pruning hook, a function that processes each tool result before adding it to the conversation history. It performs three operations: removing exact duplicates, retaining only the fields required for the current step, and shortening long logs while preserving their full contents in a file.
Measure a session’s tool history
Let’s look at four tool calls from one incident session:
Turn 2: The assistant calls
search_documents()and gets two runbook notes back.Turn 4: The same call times out while logging and is retried. It returns exactly the same result.
Turn 6: The assistant reads
note-3. The tool wrapper returns the text twice, once asfull_textand once asraw_response, plus an HTTP status code.Turn 8: The assistant pulls the CI test log from the v2.31 deploy. It has 30
PASSEDlines, one warning in the middle about a tax-service timeout, and a short summary at the end.
None of these results is wrong. Each one is simply added to the history in full. Let’s measure the history after each turn.
In the code above:
Lines 8–15: We define
ci_log(), which builds the deploy’s test log: onePASSEDline per test, a warning after the tax test, and a two-line summary.Lines 18–19: We run a real search and take the text of
note-3.Lines 20–25: We define
SESSION, the four tool calls with their turn numbers and raw results. Turns 2 and 4 share the same search result.Lines 28–31: ...