Skip to Content

Distillation, not dilution

How Sophos engineers handled oversized results in our Case Investigation Agent

As part of Sophos’ Managed Detection and Response (MDR) service, our engineers built a Case Investigation Agent. For each case it’s deployed on, the agent produces an attack timeline, recommended actions , and a verdict with supporting evidence, all of which are reviewed by a human analyst.

In order to gather that evidence, the agent calls a range of tools. Some pull customer telemetry from our data lake, some check the reputation of URLs and domains, and others decode obfuscated command lines.

Any readers familiar with building and deploying investigative AI tools might have already guessed what the problem is. The agent is capable of gathering large amounts of data – sometimes thousands of rows deep – from these tools, and most tool results in our observed workload remained within the model’s context window. However, every so often, a single tool call could return a payload that would tokenize to several million input tokens. And GPT-4.1, the model we used, tops out at 1 million tokens.

Clearly, we couldn’t hand over the whole result to the LLM, so the questions became: what could we try, and what would the trade-offs be?

While we tested several approaches, the most effective seemed to be distillation: reducing large tool results to the evidence needed for an investigation (note that this is distinct from model/knowledge distillation, in which a smaller model is trained to reproduce a larger model’s behavior).

In the spirit of sharing lessons learned, we’ll discuss the details of our distillation method and the other approaches we tried, the failure modes we found, what eventually worked the best, how we benchmarked it, and what we learned.

Putting chunking back in the trunk

Our first approach was to improve the tools and reduce the noise deterministically. But we quickly realized there was no one-size-fits-all solution; small results would fit the LLM but miss details. Next, we tried to engineer a new solution: chunking. This approach involved splitting any oversized result into pieces, summarizing each piece on its own, and merging those summaries into one.

distillation-image2.png

Figure 1: Chunking splits the payload, summarizes each piece with its own model call, then merges the summaries into one

Chunking worked, for the most part, but came with several disadvantages, all of which grew worse with bigger payloads:

  • Silent failure: The merged summary overflowed the model's context, and the ‘stitch step’ died without a trace
  • Expensive: Every chunk is its own model call, so we had to pay to push the whole payload through the model
  • Noisy: Each chunk is judged in isolation, so the model over-flags benign activity and buries genuine signals

Engage code mode

Our next step was to try ‘code mode’: rather than feeding the model the data from the tools, we let it write code to process the result and read only the parts it decided it needed – therefore distilling the results. And instead of dumping the full tool result into the model’s context, we gave it a locked-down Python sandbox, and let it filter and explore the data programmatically.

The sandbox we used is Pydantic Monty. Inside that environment, the model runs code to explore the data, and drills down until it can reach a conclusion about what happened. The full payload is processed inside the restricted execution environment, and the model receives only selected intermediate outputs and the final summary, subject to configured output limits.

distillation-image3.png

Figure 2: The model works through the raw data in the sandbox, reading only the small outputs it chooses to surface, and loops until it can write the summary

As an example, in one real incident, a file-events tool call returned 7,548 rows, most of them relating to routine background scans and file reads. The evidence that mattered came down to a few dozen rows involving malicious activity. Distillation let the model filter the noise in a few lines and spend its attention on those, instead of reading all 7,548 at once.

Only a handful of short queries were needed in that case. The model saw events cluster in the usual system and antivirus directories, as well as a temporary folder. Inside that folder was an executable that had been run and then deleted. At the same second, a quarantine entry was written to the antivirus log. The model concluded that the suspicious file had been quarantined, without needing to place all 7,548 rows in the model context.

We opted to use Monty for three reasons:

  • Safety: Our approach runs model-generated code against investigation data, so the execution environment has to be locked down. We run it in Monty, Pydantic's sandboxed Python interpreter. According to Monty’s security model there is "no ambient authority": with no mounts and no host functions configured, the sandbox "cannot read a file, read an environment variable, open a socket, or spawn a process," so code reaches the host only through functions we explicitly provide. Monty is a language-level sandbox, enforcing this at the interpreter level rather than through OS isolation, so those dangerous capabilities are not present in the environment to begin with. We provide exactly one function: a read-only accessor for the payload rows we already loaded into memory. It takes no arguments and does no I/O, so there is nothing for the model’s code to steer and nothing to validate. Today we run the open-source build, where the interpreter is the boundary. Pydantic also offers Full Monty, a hosted version that, by their description, adds OS-level isolation so a sandbox escape would reach an empty container rather than the host.
  • Agility: Our agent runs during live investigations, so we needed a sandbox we could drop into the request path without much setup. In our experience, Monty is light enough to run inline. It starts in a few milliseconds as a local subprocess, without the need to provision containers or VMs (in Pydantic’s published benchmark, an OSS Monty sandbox checkout from an existing pool took about 0.8 ms; creating a new pool took about 5 ms)
  • Compatibility:
    Monty fits with the tooling we already use. We trace and evaluate our AI systems with Pydantic Logfire, so every model call and piece of generated code becomes a span(a labeled record of an operation that we can open and inspect). The spans from a single run branch out into a trace(the full ‘tree’ of what happened), and those traces feed our evaluations.

We configured some guardrails to ensure that the solution summarized instead of dumping raw data, and that it did not come back empty.

The path to the shipped version

Chunking ran on GPT-4.1, but for the distiller we switched to a reasoning model, GPT-5.2. Chunking just reads text and summarizes it, which 4.1 handles fine. However, the distiller needed to reason about the data and write code to parse it, which are capabilities best suited to a reasoning model.

We iterated through several versions of this approach. The earliest builds did most of the work for the model. We told it what it could compute: summary statistics, plus a set of handwritten rules that scored each row for how suspicious it looked. Those rules recalled about 65% of the must-keep clues overall, but on threats they weren’t designed for, that dropped to around 38%. This was likely because handwritten rules only catch what someone already thought to look for, which is not a sustainable pattern.

We then took a different tack; rather than handing the model our conclusions, we let it do the reasoning itself, by putting the model in a loop: write some code, look at the result, decide what to do next, and repeat until it had what it needed. We also dropped the hand-written scoring rules that graded each row, since the whole point was to stop pre-deciding for the model what counted as suspicious. This handled new threats far better, jumping up to 68% recall. But we'd also kept the toolkit of ready-made helper functions from the pipeline, and it leaned on those too heavily for our liking. The model treated the toolkit as a signal of how we wanted the job done, so it kept reaching for those pre-built moves instead of analyzing the data on its own terms.

The version we eventually shipped takes the toolkit away entirely. It still gets the same briefing every version did (the investigation step, the detections, the shape of the data, and what its output feeds downstream), but with the ready-made helpers gone, it works straight from the rows and writes all its own logic.

That version scored the best recall of any we built, hitting around 77%, where the chunking approach was struggling to reliably produce a summary, and it was also the simplest. That figure comes from the hardest cases we had, not the everyday ones, and the investigation agent still gathers the indicators from other evidence, so a clue the distiller misses in one payload is rarely its only trace. The somewhat counterintuitive finding was that the more freedom we gave the model, the better it worked.

Building the benchmark

To test this capability, we assembled an evaluation dataset from 25 production cases. Our data selection was informed by two requirements: a spread of sizes, from results just over the model's context limit to those that broke our chunking approach (i.e., those that cost between 1.7 to 3 million tokens), and a batch of genuine compromises, so that some cases had real malicious indicators to check against.

We ran both the chunking and distillation approaches over the whole set on the real payloads (and kept the baseline chunker and grading models fixed across every comparison, so the variable between runs was the approach itself, rather than the setup). It’s worth noting that the dataset was deliberately comprised of stress tests, rather than representative samples; it reflected the edge cases this capability exists for, rather than the frequent, small results that don’t trouble the model.

For compromise cases, we created an answer key of specific indicators that a useful summary should preserve, independent of what the distiller produced. We used that key as the reference set for the recall evaluation.

The results

The harness was built on pydantic-evals. Each evaluation case was a tool result, and four evaluators scored every case, covering token savings (vs chunking), latency, the assessment of an LLM judge (a language model that grades quality the way a human reviewer would), and recall against the answer key.

The evaluation cases, including the multi-megabyte raw payloads pulled from real investigations, live in our self-hosted instance of Logfire's Datasets and were fetched by name when the evaluation ran, so the test set was versioned and shared.

Tracing each run let us open any case and see exactly what the model did, which is how we caught an early bug where the loop hit its step cap and returned nothing. That bug is what led us to add a ‘finalize’ step. If the loop runs out of turns before it produces an answer, it now forces one final synthesis pass, preventing the empty-result failure mode we observed when the loop reached its step cap.

Reliability

In production, oversized results often crashed the tool call and failed to produce a summary. We could still run chunking on these payloads offline for the comparison, but only slowly and at significant expense. In contrast, distillation handled each case in our benchmark dataset cleanly.

Cost

Our distillation approach used, on average, 92.6% fewer tokens than chunking on the benchmark dataset: 125,610 tokens per case, versus 1,700,691.

These numbers do need a caveat, because we derived them in different ways. Both token amounts measure how much work went through the model. For distillation, we used the provider-reported billed token total. For chunking, we summed the input and output tokens across every model call.

In production, this pattern appears to hold. Across the real oversized results we've processed so far (now that our approach is in production), the model's total token usage runs about 70% below what the raw payloads contain, because it never ingests the payload itself. A raw result arrives at around 400,000 tokens on average, but the model uses only about 120,000 to work through it, running code against the data and reading only what it chooses to surface.

distillation-image4.png

Figure 3: Total token usage stays relatively flat while raw payloads climb into the millions, so cost decouples from data size

As the raw payload grows, the tokens the model actually uses (input, plus output, plus reasoning) barely move, staying in a low flat band, while the tokens relating to the raw data climb into the millions. The two lines cross at around 200,000 tokens: below that there's nothing to gain, and above it the gap widens with every step up in size. Ultimately, the extremely large results (the ones this capability exists for), save far more.

Latency

In our benchmarking test, distillation was faster than chunking. More to the point, its speed does not depend on the size of the payload, because the raw data never enters the model. In production, distillation holds a flat band of roughly 80 to 115 seconds per case, whether the result is 400,000 tokens or 3 million, and a timeout we impose caps each run at about 180 seconds.

However, since chunking reads the whole payload, its latency climbs with size and swings widely, several runs pushing past 200 seconds and one taking close to nine minutes.

distillation-image5.png

Figure 4: Distillation's latency stays flat and bounded near the 180s timeout ceiling as payloads grow; chunking climbs and scatters far higher, one run to nearly nine minutes

Quality

Cost and speed only matter if the summaries are good, so our fourth benchmark evaluator was an LLM judge that scored the summaries themselves. We added rigor to the judge in two ways:

  1. It judged blind. For each case, it saw the two summaries side-by-side with no labels, and which one came first varied from case to case, so it didn’t know which came from distillation and which from chunking. This was to avoid the judge simply favoring the newer approach. We also didn’t mention either of the two methods in our prompts, so the judge simply had two summaries, along with the ground truth facts (metadata about the dataset, total events, time-bounds row counts, sample rows, and so on). After judging was complete, we relabeled the summaries, outside of the LLM context.
  2. It judged against facts, as well as the summary texts. In addition to the summaries, we provided it with a set of facts taken from the raw data: row counts, the most common entries, and time ranges. For the real compromises, we provided the judge with the same answer key we used to measure recall, which lists the indicators a good summary had to name, the leads it should flag, and the everyday activity it should not mistake for a threat. On those cases the judge checked two things: did the summary get the facts right, and did it catch what mattered without raising a false alarm on what didn't.

The LLM judge preferred distillation in 96% of cases. Where it explained its choice, the recurring reason was precision: distillation flagged fewer benign items as threats. Chunking summarizes each piece of the data on its own, with no view of the whole, so it tends to escalate ordinary activity that only looks suspicious out of context. Those false positives can increase analyst review burden and may make genuine signals harder to prioritize.

We also checked recall directly, with a separate deterministic evaluator rather than the LLM judge. For each case, we took a handwritten answer key of the indicators a good summary had to preserve, then looked for each one in the summary text as a straight substring match, after normalizing cosmetic differences like defanged IPs. Across the cases with an answer key, distillation retained about 77% of the high-value indicators.

Where distillation falls short

The one case in which the LLM judge preferred chunking was a file lookup where distillation missed a decisive indicator that chunking retained.

It’s worth noting that this is an important trade-off. Distillation reasons about the data instead of dumping every raw row, and so it can occasionally overlook a single buried indicator that exhaustive chunking would surface. We saw a single instance of this across our benchmark dataset – and while chunking didn’t miss the indicator in that case, it still crashed on big payloads and over-flagged benign activity everywhere else.

Distilling the distiller

On our stress-test benchmark, distillation outperformed chunking on token use, latency, completion reliability, and the LLM judge’s preference. However, chunking retained one decisive buried indicator that distillation missed. The trade-off is many more crashes and false positives. As a result of this project, we took away two valuable lessons, which we hope may be useful to other researchers and engineers in the industry.

First, counterintuitively, the less we scaffolded the model, the better it did. Our most elaborate version, with hand-tuned scoring rules and a library of helper functions, was less effective than a bare loop that kept the same prompt context but dropped almost everything else, leaving the model to write its own code against the data. When a model can run code, a lot of the structure we add to ‘help’ it just gets in the way.

Second, distillation could be useful beyond our own use case. Agents that call tools can eventually encounter results too large for their context windows, particularly in high-volume data workflows. The reflex is to shrink the data until it fits the model, but our research suggests the converse approach may be more beneficial: leave the data as it is, but give the model a way to work through it. That method made oversized results manageable in our production workflow, an approach we are carrying into the rest of our agent work.

Sophos would like to thank Pydantic for its continued investment in open source, including Monty, the sandboxed Python interpreter behind our distiller.