Agent Context Engineering in Practice: Token Budgets, Caching, and Context Management

    This article breaks down context engineering for AI agents, explaining why a large context window does not mean every token should be sent. It walks through a three-step token ledger to show how prefix caching reduces input costs, then details four complementary mechanisms—token metering, compaction, spill, and pruning—along with a practical budget model, threshold configuration, and common pitfalls to avoid when tuning an agent harness.

    1. The Problem: Context Is a Limited and Expensive Resource

    As agents take on longer task chains, conversation history, tool definitions, and tool results keep accumulating, and the context window quickly becomes the bottleneck. Even though mainstream models now offer context windows on the scale of a million tokens, “can fit” does not mean “should fit everything.” There are three reasons:

    1. Cost: The prefix content must be resent on every request, and any portion that misses the cache is billed incrementally.
    2. Latency: Longer inputs increase time to first token and overall inference time.
    3. Attention dilution: Irrelevant history and oversized tool outputs interfere with the model’s judgment of the current goal, reducing instruction adherence.

    A mature agent harness must therefore treat context as a system resource that needs active governance, rather than passively stuffing in whatever fits.

    2. A Token Ledger for a Single Task: Why Input Drops at Step Two

    Consider a simple three-step task. The change in input tokens at each step is revealing:

    Step New Input Cache Read Notes
    Step 1 ~4400 0 System prompt, tool definitions, and history sent in full for the first time
    Step 2 ~380 ~4480 Only the new tool result is added; the prefix hits the cache
    Step 3 ~130 ~4860 The increment shrinks further

    The key mechanism is prefix caching: as long as the prefix of the current request is byte-for-byte identical to the previous one, the server can reuse the already-computed KV (key-value) representation and only compute and bill the new portion. This yields an important engineering rule: keep the prefix stable and append changes at the tail. Any casual modification to the system prompt, the order of tool descriptions, or history messages invalidates the entire cache, and the cost curve rebounds instantly.

    3. Division of Labor and Coordination Among Four Mechanisms

    Context governance is usually split into four orthogonal capabilities, each addressing a different layer of the problem:

    3.1 Metering (token meter)

    Responsible for estimating the usage of each request, outputting a breakdown of the system prompt, tool schemas, history messages, and tool results. The value of metering is not just “watching numbers” but providing the trigger basis for the other three mechanisms. In implementation, it is advisable to keep two paths: “exact tokenization counts” for reconciliation and “fast approximate estimates” for real-time decisions on the hot path.

    3.2 Compaction

    When usage reaches a threshold (commonly 70%–85%), merge earlier, low-information-density segments into a structured summary that retains four elements: goals, constraints, completed actions, and open questions. Compaction must be traceable: the summary should keep reference identifiers to the original segments so that evidence can be traced back later.

    3.3 Spill

    For a single oversized tool result (such as logs, file contents, or retrieval results), write it in full to external storage (such as object storage or local disk), keeping only a head-and-tail preview and locating information in the context. If the model decides it needs the details, it reads them page by page through a tool. This essentially changes “inject everything at once” into “access on demand, page by page.”

    3.4 Pruner

    For tool results that exceed budget, apply structured trimming to form a “head + omission marker + tail” shape, annotating the number of dropped items and retrieval suggestions at the omission point. The difference from spill is that pruning is lossy and immediate, while spill is lossless and traceable.

    The recommended coordination order is: continuous sampling by the meter → spill first when a single result exceeds the limit → prune when the total exceeds budget → compact when the conversation history grows too long.

    4. Budget Design and Threshold Configuration

    A practical budget model can be divided as follows (illustrative):

    1. Total budget = system prompt + tool definitions + history and summaries + current tool result + output reserve
    2. Constraints:
    3. Tool definitions <= 15%
    4. Single tool result <= 8%
    5. Output reserve >= 10%

    Illustrative strategy code:

    1. def prepare_context(state, budget):
    2. if state.single_result_ratio() > 0.08:
    3. state.spill_large_results() # Lossless spill
    4. if state.total_ratio() > 0.80:
    5. state.prune_tool_results() # Lossy pruning
    6. if state.total_ratio() > 0.80:
    7. state.compact_history() # Summary compaction
    8. return state.render(keep_prefix_stable=True)

    5. Common Pitfalls and Practical Advice

    • Pitfall 1: Treating compaction as a cure-all. Compaction loses detail; if something can be solved with spill and paged reads, do not rush to summarize.
    • Pitfall 2: Adjusting the prefix arbitrarily. Timestamps, random IDs, and tool-order jitter all break the cache.
    • Pitfall 3: Looking only at the total, not the structure. Per-item metering is what locates the real source of growth, which is usually tool results rather than the conversation.
    • Advice: Build a unified observability dashboard for the four mechanisms, recording trigger counts, tokens saved, and changes in task success rate, and tune parameters with data rather than intuition.

    6. Conclusion

    The core of context engineering is not “packing more in” but “using it more precisely.” Metering provides visibility, spill guarantees losslessness, pruning controls the upper bound, and compaction maintains long-range continuity; combined with the cache benefits of prefix stability, this balances cost, latency, and effectiveness. This approach aligns with the observability and layered governance direction emphasized in Baidu AI Cloud’s agent engineering practice, and is worth adapting to your own scenarios when implementing it in your own systems.