Context Management for AI Agents: Metering, Compaction, Spilling, and Pruning

    This article explains how AI agent runtimes manage long conversation contexts under token and window limits. Starting from a three-step task with sharply changing input tokens and cache hits, it introduces prefix caching and then details four cooperating mechanisms: metering, compaction, spilling, and pruning. It covers trigger thresholds, what to compress and how much, external storage for oversized tool results, head/tail truncation budgets, and the coordination flow among these mechanisms. It also discusses model-specific prefix-cache behavior, token-billing tradeoffs, structured tool outputs, and engineering practices such as token dashboards, tool-result budgets, traceable compaction, and local rather than global compression.

    Starting with the Token Ledger of a Real Task

    Consider an agent task with only three steps. Each step calls a large model, but the number of input tokens across the three calls changes dramatically: the first step has 4,399 input tokens, the second drops to 378, and the third falls to only 128. At the same time, the latter two steps report 4,480 and 4,864 cached token hits, respectively.

    This steep drop is not an anomaly. It reflects a common optimization in mainstream large-model inference services: prefix caching. If the input prefix of the current request is byte-for-byte identical to part of the previous request, the provider can reuse the key-value (KV) state for that prefix and process only the incremental portion. In the task above, the difference between the first and second steps is just the newly produced tool return. The system prompt, tool list, and existing history all hit the cache, so the second step needs to send only 378 incremental tokens. By the third step, the new content shrinks further, and the input falls to 128 tokens.

    This phenomenon reveals the first core principle of context management: keeping the request prefix complete and stable is the most direct way to reduce token consumption. Conversations cannot stay short forever, however. As historical messages and tool-call records accumulate, the context window will eventually reach its physical limit. At that point, management must move from “maintaining prefix stability” to “actively deciding what to retain, what to compress, and what to move elsewhere.”

    Overall Architecture and the Division of Labor Among Four Mechanisms

    Long conversations cannot be handled by a single technique. They require a set of cooperating strategies. A typical agent runtime builds four layers of mechanisms around the context window, each with a distinct role:

    • Metering: estimates the token usage of each request and provides the data basis for later decisions.
    • Compaction: when context occupancy reaches a preset threshold, summarizes earlier historical messages to free space for new content.
    • Spilling: when a single tool call returns an unusually large result, such as a query returning hundreds of thousands of rows, moves the full result to disk or external storage and gives the model only head and tail preview snippets.
    • Pruning: sets a budget for returned results and, for tool results that exceed the budget, applies “head + omission + tail” truncation.

    The division of labor is clear: metering senses usage, compaction handles continuously accumulating history, and spilling and pruning address sudden cases where a single tool result is too large. The following sections examine each mechanism.

    Metering: Knowing How Much Context Remains

    To manage context, the first problem is measurement: how do we know how much has been used?

    Many frameworks provide metering services or plugins. Their estimates are heuristic: roughly four characters per token, plus role labels, message block boundaries, request structure overhead, and similar factors. This approach does not aim to match the model vocabulary exactly. It serves two practical purposes: first, estimating token consumption before a request is sent, for progress bars or early warnings; second, providing trigger signals for strategies such as compaction and spilling.

    It is important to note that this heuristic estimate significantly undercounts CJK (Chinese, Japanese, and Korean) text and JSON Schema. It should therefore be treated only as a reference indicator of occupancy, not as a billing basis or a precise measurement method. In an actual engineering implementation, metering should count the assembled system prompt, tool function definition list, routing metadata, assistant historical completion messages, tool call returns, reserved buffer context, and guidance text inserted mid-conversation. If any of these is missed, the estimate will be too low, compaction will be triggered too late, and context overflow may result.

    Compaction: Turning Outdated History into Summaries

    Compaction is usually triggered when context occupancy reaches a threshold, such as 80%. Once triggered, the framework selects earlier message fragments in the current conversation, sends them to the model to generate a summary, replaces the compressed original messages with the summary, and recalculates token usage.

    The design of a compaction strategy must answer two key questions: what to compress and how much to compress.

    What to compress is not simply “the oldest messages.” In modern agent conversations, tool-call results are often large and highly time-sensitive. When a user asks a question at turn 10, they are unlikely to read again the full JSON list returned by an API call at turn 2. But some information must be retained, such as the user’s initial requirement constraints, role identity restrictions, and variable values that later turns depend on. A compaction strategy should therefore use a hybrid weighting of semantic priority and time decay.

    How much to compress also requires tradeoffs. If the compaction ratio is too small, limited space is freed and compaction will soon trigger again. If the ratio is too large, the summary loses key details and later turns may produce context hallucinations. A common practice is to set a minimum number of messages retained per compaction and dynamically limit summary length so that it does not exceed a certain proportion of the compressed content. After compaction, the metering module must re-estimate the token count of the summarized history and update occupancy, avoiding the paradox of “compressing more and using more space.”

    Spilling: Graceful Handling of Very Large Tool Results

    Oversized tool results are another frequent pain point in long conversations. When a single tool return reaches tens of thousands of tokens, forcing it into the context window not only crowds out later dialogue space but also slows down each request. Spilling works by writing the full result to external storage, such as local disk or object storage, and keeping only the head and tail fragments plus an addressable reference identifier in the context.

    This has two benefits. First, the model sees a “head excerpt + middle omission notice + tail excerpt,” which is enough to understand the overall shape of the tool result and decide the next action based on business logic. Second, the full result still exists and can be precisely retrieved on demand in later turns, for example by the model issuing a read instruction or by developer logic calling the storage interface.

    Spilling is coupled with model capabilities: one must either choose a model that supports partial tool-result display with summaries, or have the framework bear an additional model call to generate summaries. In either case, the value of spilling is that it prevents very large results from occupying valuable window resources for a long time while preserving a complete path for secondary retrieval.

    Pruning: Keep the Head and Tail, Omit the Middle

    Spilling handles the extreme case where a result is so large that it must be moved away. Pruning handles the edge case where a result is large but could still fit in the window. A typical pruning implementation sets a result budget. When a tool return exceeds the budget, it retains a proportional head fragment and tail fragment, with the middle replaced by an omission marker.

    Two issues require attention when designing pruning strategies. First, some tool results have clear structured semantics, such as JSON arrays or CSV tables. Truncation must preserve a valid preceding fragment; otherwise the model may fail to parse the result and cannot understand it. Second, after pruning, there must be a way to actively retrieve the full result. Some frameworks let the model, upon finding insufficient information in a pruned result, initiate a new tool call to fetch the remaining part. This requires pruning strategy to coordinate with the tool-call protocol.

    The difference between pruning and spilling is that pruning usually does not involve external storage; it only performs static truncation of the context. Spilling changes the physical storage location of the data. The applicable thresholds for both depend on the context window size and the frequency distribution of tool results.

    The Coordination Rhythm of the Four Mechanisms

    In actual operation, the four mechanisms do not trigger in isolation. They form a coordinated flow:

    1. Before each request, the metering module estimates token occupancy and updates the occupancy curve.
    2. When occupancy reaches the configured threshold, compaction starts and summarizes the earliest historical messages. If occupancy remains high after summarization, it continues compressing the next batch of history until occupancy falls back to a safe level.
    3. During request assembly, if a tool result exceeds the spilling threshold, it is spilled in full. If the result falls between the spilling threshold and the pruning threshold, it is pruned according to budget.
    4. After multiple turns, a resource report can be generated from metering records to help developers observe token consumption distribution across task stages and review where optimization opportunities exist.

    The core goal of this coordination structure is to keep the context window within a reasonable occupancy range: neither completely full, which risks overflow, nor over-compressed, which risks losing key information.

    Key Considerations in Designing Context Management Strategies

    When building an in-house agent framework or selecting an open-source option, developers should pay attention to several factors.

    First, different models have different prefix-cache behavior. Some models are highly sensitive to prefix changes. Even inserting a new message into history can invalidate the entire prefix cache and sharply reduce the cache hit rate. The insertion order of tool results should therefore be designed with prefix continuity in mind.

    Second, compaction trigger thresholds should be set in light of token-billing tiers. If a model service bills all input tokens and cache pricing is low, more frequent compaction may increase cost instead. If the cache-hit price is clearly lower than the price of creating new KV state, then “keeping the prefix unchanged as much as possible” is the correct cost strategy.

    Third, the degree of structure in tool results determines the implementation difficulty of pruning and spilling. Results using streaming protocols or paginated designs are naturally suited to a “truncation + on-demand retrieval” architecture. Results that return a complete structure in one call must rely on framework-side spilling as a fallback.

    From Mechanisms to Engineering Practice: Recommendations and Paths

    Based on the analysis above, developers building agent applications can follow these engineering recommendations:

    • Build a token metering dashboard early. Do not wait until context overflow to investigate. From the first version, instrument the request and response boundary to record input/output token counts, cache hits, and time intervals between requests.
    • Set budgets for tool results and enforce them. At the tool function definition layer, require returned results to obey a unified size limit. Over-limit returns should be handled uniformly by pruning or spilling; tools should not truncate results internally on their own.
    • Design compaction to be traceable. After a summary replaces the original text, the original messages should not be deleted directly. They should be archived to external storage so that if later conversation truly needs the original details, they can be retrieved by reference. This avoids the irreversible negative effects of summaries losing details.
    • Use global compaction cautiously and prefer local replacement of specific message blocks. For example, compress only tool-return history while retaining all original user input; or compress only the variable parts of the system prompt while retaining the fixed system instruction prefix. The latter also helps maintain the validity of the prefix cache.

    Conclusion

    The context window is one of the scarcest runtime resources in agent applications. Reliable context management is not simply “truncate when the window is full.” It requires organically combining metering, compaction, spilling, and pruning, then tuning them for the caching behavior and token-billing model of the specific model in use. Understanding the division of labor among these mechanisms helps developers move from passively responding to context overflow to proactively designing resource boundaries, so that agent tasks remain stable, controllable, and cost-friendly in long-running scenarios.