Skip to main content
Back

AgentDiet Cuts Coding Agent Token Costs by 40% Without Hurting Performance

AgentDiet cuts input tokens by up to 60% and total inference cost by up to 36% on coding agents, with no drop in task success rate.

Pro

Paper, Full Access
  • AgentDiet prunes wasted context from LLM coding agent trajectories at inference time, cutting input tokens 39.9%-59.7%.
  • Total computational cost drops 21.1%-35.9% on SWE-bench Verified and Multi-SWE-bench Flash with no accuracy loss.
  • A separate cheaper LLM (GPT-5 mini) handles pruning because agents refuse to clean their own trajectories even when prompted.
  • Three waste categories identified: useless output, redundant edit echoes, and expired search results from earlier steps.
  • Sliding window design preserves KV cache and prevents catastrophic deletions by delaying pruning two steps behind.
  • Open-source artifacts integrate into Trae Agent and any similar tool-calling loop.

Coding agents built on large language models have a dirty secret: they are extraordinarily wasteful with tokens. Every time an agent opens a file, runs a test suite, or greps through a codebase, that output gets welded into the trajectory forever. By step 40, the model is re-reading the same verbose make logs and __pycache__ listings it saw at step 3. A new paper from Peking University and ByteDance called AgentDiet shows that most of that context is garbage, and that stripping it out during execution can slash costs by a third without touching the success rate.

The 99% problem

The scale of the waste is easier to appreciate with numbers. The average trajectory for solving a single GitHub issue collected from the SWE-bench Verified benchmark contains 48.4K tokens in 40 steps, and since each token concatenated into the trajectory is included in every subsequent input to the LLM, the accumulated token usage per issue reaches 1.0M. That snowball effect shows up on billing dashboards too: in September 2025, the daily token usage of Claude 4 Sonnet reached 100 billion on the OpenRouter platform, and 99% of them were input tokens accumulated in the trajectory, while only the remaining 1% were generated by the LLM.

Efficiency has largely been an afterthought in agent research. Existing token-reduction work is mostly aimed at retrieval-augmented generation, where you compress a prompt once before inference. Agents are different: the context grows step by step, so when you compress matters as much as how. And you cannot fine-tune the underlying model when it is a closed API like Claude or Gemini.

Three flavors of trajectory garbage

The authors manually inspected 100 trajectories from Trae Agent, currently a top scorer on SWE-bench Verified, and found waste falls into three predictable buckets:

  • Useless information. Nearly all trajectories begin with a tool call to enumerate all files in the repository, and the tool response includes cache and resource files (e.g., files under the __pycache__ and .egg-info directories). Build logs are similarly bloated with per-directory noise.
  • Redundant information. When the agent uses Anthropic's str_replace_editor, the new string appears in the arguments and gets echoed back in the tool response. The old string was already visible in an earlier read. The agent must have retrieved the context to edit prior to this tool call, so P repeats code from previous steps in the trajectory.
  • Expired information. When the agent greps for a symbol and opens five candidate files before finding the culprit, the other four file contents are dead weight for the rest of the run.

Why the agent cannot clean up after itself

The obvious fix is to give the agent an erase tool and let it prune its own history. The authors tried this. It failed. Even with powerful LLMs such as Claude 4 Sonnet and Gemini 2.5 Pro, the agent often persisted with the original task without calling erase, despite explicit prompts. Even when the user prompt aggressively instructed the model to only call erase and stop working on the bug, Claude kept diving deeper into the Django codebase.

The likely cause is training-time memorization of the program-repair workflow. Once the model is in bug-fixing mode, it is very hard to yank out. So the researchers moved the cleanup out of the agent loop and into a separate module.

A sliding-window reflection module

AgentDiet adds a second, cheaper LLM that runs after each agent step and prunes an earlier step in the trajectory. Three hyperparameters control it:

  • a: how many steps to wait before pruning a step. This gives the main agent time to actually use the raw output before it gets summarized.
  • b: how many steps of surrounding context to feed the pruning model, so it understands what is still relevant.
  • θ: a token threshold below which a step is skipped entirely, avoiding overhead on already-short messages.

The pruning LLM sees only a fixed window (steps s-a-b through s), so the extra token cost per reflection is capped. Because AgentDiet only rewrites a single older step, KV Cache entries corresponding to previous steps are preserved, minimizing overhead from cache invalidation. When the module fires, it replaces the wasteful content with a short placeholder like individual test lines omitted; mostly PASSED while keeping the important bits, such as the one failing test.

Picking the reflection model

The team ran a hill-climbing search over five cost-efficient reflection LLMs plus baselines like random deletion and LLMLingua-2. GPT-5 mini won on both cost and preservation of agent performance. Interestingly, GPT-5 mini maintains the same Pass% as Original, and is also the only model with a decrease in Step and PStep. The converged settings were a=2, b=1, θ=500.

Naive baselines like deleting everything or randomly dropping 75% of tokens did surprisingly well on Pass%, because the delay a=2 and threshold protect the most recent steps. But they inflated total step counts by 13%+, meaning the agent had to redo work to recover lost information.

The numbers on SWE-bench and Multi-SWE-bench

Evaluation ran on 200 held-out instances of SWE-bench Verified and 300 instances of Multi-SWE-bench Flash, which covers seven other languages including Rust, TypeScript, Java, Go, C, and C++. Both Claude 4 Sonnet and Gemini 2.5 Pro were tested as the main agent model.

SetupInput tokensTotal costPass% change
SWE-bench + Claude 4 Sonnet-39.9%-28.6%+2.0
SWE-bench + Gemini 2.5 Pro-40.9%-37.7%+1.5
Multi-SWE + Claude 4 Sonnet-40.4%-32.4%-1.0
Multi-SWE + Gemini 2.5 Pro-59.7%-44.1%+1.0

After subtracting the overhead of GPT-5 mini itself (roughly 5-12% of the original cost), the net computational savings land between 21.1% and 35.9%. In dollar terms, an average SWE-bench instance dropped from around 54 cents to 42 cents with Claude, and from 39 cents to 29 cents with Gemini.

An unexpected side effect

One column jumps out: on Multi-SWE-bench Flash with Gemini 2.5 Pro, average steps dropped from 57.20 to 43.90. The reason is a known Gemini failure mode. Gemini 2.5 Pro shows increasingly abnormal behavior when the context is too long, often resulting in repeated invalid tool calls until the step limit is reached. By trimming the trajectory, AgentDiet cut the number of runs that hit the 100-step ceiling from 66 down to 26. Trajectory reduction here doubles as a robustness fix.

This also punctures a common assumption. Test-time compute framing suggests more tokens equal better performance. Here, less context yielded slightly higher pass rates in most configurations, consistent with prior findings that long-context LLM performance degrades with irrelevant material.

When to reach for it

AgentDiet is a good fit if you are running long-horizon coding agents against proprietary APIs and paying by the token. It requires no model access, no fine-tuning, and hooks into any agent that fits the standard "model calling tools in a loop" pattern. The authors integrated it into Trae Agent by adding roughly the pruning block into the existing loop:

for step s in range(s_max):
    m_assis = LLM_agent(T)
    if is_done(m_assis): break
    E, m_tool = exec_tool(E, m_assis)
    T.append((m_assis, m_tool))
    # Reflection module
    if s - a > 0 and len(T[s-a]) > theta:
        ctx = serialize(T[max(0, s-a-b):s])
        reduced = LLM_reflect(ctx, s-a)
        if len(T[s-a]) - len(reduced) > theta:
            T[s-a] = reduced

Where it is less useful: short single-turn tasks, agents that already use aggressive rule-based truncation, or latency-critical loops where you cannot afford the extra reflection call (though the authors note the reflection step can be parallelized with the next agent step if latency matters more than context quality).

Caveats

The evaluation only covers one agent framework, Trae Agent. The authors argue that current agents are architecturally similar enough for the results to transfer, and the reflection prompt was tuned on just 100 instances yet generalized to seven new programming languages. Still, agents with radically different tool sets, multi-agent orchestration, or majority-voting ensembles were not tested. The pruning also introduces a dependency on a second API vendor, which teams running purely on-prem will need to reconcile.

The artifacts, including the implementation, prompts, and raw trajectories, are open-sourced. For anyone paying real money for coding agents in production, this is a rare optimization that pays for itself immediately and does not require touching the underlying model.