Search⌘ K
AI Features

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 as full_text and once as raw_response, plus an HTTP status code.

  • Turn 8: The assistant pulls the CI test log from the v2.31 deploy. It has 30 PASSED lines, 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.

session_results.py · Python 3.14.0
import json
from note_store import NOTE_STORE, search_documents
from render_request import count_tokens
AREAS = ["cart", "discounts", "shipping", "payment", "tax", "inventory", "receipts", "refunds", "currency", "sessions"]
def ci_log():
lines = ["===== test session starts: checkout v2.31 deploy gate =====", "collected 30 items"]
for area in AREAS:
for case in ("basic", "edge_cases", "errors"):
lines.append(f"tests/test_{area}.py::test_{area}_{case} PASSED")
if (area, case) == ("tax", "basic"):
lines.append("WARNING: test_tax_basic timed out after 2.0s calling the tax service; retry 2 passed")
return "\n".join(lines + ["===== 30 passed, 1 warning in 41.2s =====", "Deploy gate: PASSED for checkout v2.31"])
SEARCH = [{"doc_id": n["doc_id"], "text": n["text"]} for n in search_documents("checkout latency roll back", top_k=2)]
NOTE_3 = NOTE_STORE[2]["text"]
SESSION = [ # (turn, tool, raw result)
(2, "search_documents", SEARCH),
(4, "search_documents", SEARCH), # a retry after a timeout returns the same result
(6, "read_note", {"doc_id": "note-3", "full_text": NOTE_3, "raw_response": NOTE_3, "status": 200}),
(8, "get_ci_log", ci_log()),
]
if __name__ == "__main__":
history = ""
for turn, tool, result in SESSION:
history += f"\n[turn {turn}] {tool}: " + (result if isinstance(result, str) else json.dumps(result))
print(f"after turn {turn} ({tool:<16}): {count_tokens(history):>4} tokens")

In the code above:

  • Lines 8–15: We define ci_log(), which builds the deploy’s test log: one PASSED line 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: ...