DEV Community

Cover image for How to cut your AI agent's input tokens: what worked, what failed, and a bench to measure yours
Anis Meziani
Anis Meziani

Posted on

How to cut your AI agent's input tokens: what worked, what failed, and a bench to measure yours

Includes a 7-point checklist and open bench

Before every single thought, our BI agent re-read 17,000 tokens of instructions and tool manuals.

Then the whole conversation. Then every table it had pulled since the first question. In our offline replay of a three-question conversation, ten model calls consumed 286,522 input tokens before optimization. Real runs behaved differently, as you'll see below.

Nobody had decided that. It's just what an agent does by default: every model call starts from zero, so everything the agent "knows" gets sent again. Every call, every turn, every retry.

This post is a field report on how we brought it down: how we measured, which cuts paid off and in what order, what didn't work, and a checklist you can run on your own agent tomorrow. It ends with five questions we can't answer alone. The optimizations reported here are implemented, and the benchmark is open source, so you can check every number. Some experiments and benchmark improvements are still in progress, and I'll say which.

It's the third post in a series about what breaks when AI agents run in production, after agents that forgot everything after a restart and agents that redid work they had already done. This one is about the opposite of amnesia: agents that remember too much, and pay for it on every call.

TL;DR: six lessons

  1. Measure before you cut. Without a bench and quality checks, our best-looking cut would have quietly broken the answers.
  2. Start with the tools. Instructions plus 36 tool declarations cost 17,000 tokens before the question. Removing the tools the agent never calls was the cheapest win.
  3. Forget the past, never the present. Shortening old tool results saved 21 to 26%. Shortening the current turn broke quality on 4 scenarios.
  4. Stable prompts are cacheable prompts. In our benchmark, ordering the schema tables deterministically raised the reusable prefix of a SQL prompt from 11% to 98%, with the same tokens.
  5. The biggest real gain came from fewer calls, not smaller ones: −41% on a question, because the model asked once instead of five times.
  6. Your bench will lie to you a little. Ours overestimated real gains by 9 to 16%, underestimated one by a lot, and missed a failure entirely.

1. Measure before you cut

Know what you're paying for

Here's what our BI agent sent to the model on every call, before we changed anything:

Layer What it is Paid when
Instructions the agent's system prompt every call
Tool declarations name, description and schema of each of 36 tools every call
History every message of the conversation every call
Past tool results every table, file and query result pulled so far every call
Current turn the question, and the results the model is working on now every call of this turn

The first two layers alone came to about 17,000 tokens: the whole first call weighed 17,070, a one-line question included. The model paid them before reading a word of the question, and again at each of the 3 to 5 calls a question takes.

We're not alone. The industry now calls it the "MCP tax": one measurement published in May found around 71,000 tokens of overhead for seven MCP servers, about 35% of a 200K context window, before the first prompt. And the cost isn't only money: research on context rot keeps showing that models get worse as their input grows, well before the window is full. A useless token is paid twice, on the bill and in the answer.

Build the bench first

We built a bench before touching anything. It lives in bench/bi_tokens:

  • Five scenarios of our BI agent: creating a dashboard, asking a question about it, chatting with it, a three-question conversation, and a forecast.
  • An offline replay with a scripted model, so each change is compared on identical calls, input tokens counted call by call.
  • Quality checks on every scenario: the right facts, grounded in the data. A cut that saves tokens but fails a check is rejected.
  • Real runs afterwards, with costs read from the usage table where every model call is recorded.

That last part matters more than it sounds. Section 3 explains why.

2. The cuts, ranked by effort and gain

Here's what we did, in the order we'd do it again:

Cut Effort Measured gain Watch out for
Remove the tools the agent never calls low −10 to −15% per scenario, first call −18.5% on real runs nothing observed
Shorten old tool results, past turns only low −21 to −26% on conversations never touch the current turn
Describe big payloads instead of pasting them low base64 page images no longer re-sent at every turn the agent must still reach the full data through tools
Make the prompt prefix cache-friendly low reusable prefix 11% → 98% (benchmark, upper bound) depends on your provider and on which tables are selected
Fewer round trips medium −41% on a question, real run only pays if the model uses it
Trim the instructions low about −2% small, do it last

Remove the tools the agent never calls

Our BI templates had inherited the generic chat tools of the platform, the ones a general assistant needs and a BI agent never calls. Most agent stacks ship this way; we just measured ours.

We removed ten of them from the BI templates, and trimmed what remained: declarations lost their pydantic titles and "Returns" sections, and tool responses are capped. 36 tools down to 26, and the first call went from 17,070 to 13,598 tokens on the bench. On real runs, together with the instruction trim described below, it went from about 14,500 to 11,800.

Lesson: an agent's toolbox is a cost line. Declare tools per agent, not per platform.

Shorten old tool results, never the current turn

After a few questions, most of the context was old tool results: tables the agent had pulled two turns ago and already answered from. Now, in every turn before the current one, a large tool result keeps its small fields (ids, titles, status, a message) and loses its bulk, with a note telling the model it can call the tool again if it needs the data.

def compact_previous_turns(contents):
    # The current turn starts at the last user message that isn't a tool result.
    current = current_turn_start(contents)
    for content in contents[:current]:          # earlier turns only
        for part in content.parts:
            if is_large_tool_result(part):
                part.response = keep_small_fields(part.response)  # ids, titles, status
Enter fullscreen mode Exit fullscreen mode

It runs on a copy: the stored session keeps everything, only what the model re-reads is shortened. And the answer the model gave at the time stays in the history, so what it concluded isn't lost.

Lesson: storing everything is cheap. Re-sending everything is what costs.

Describe big payloads instead of pasting them

  • Big files. A large CSV used to be pasted into the context. Now the agent gets the header, the first 20 rows and the row count, and works on the full data through its tools.
  • Images. In our pipeline, a base64-encoded PDF page was estimated at roughly 100,000 to 150,000 text tokens, depending on the page and its encoding (an estimate written down in our code when we hit it, not a formal benchmark), and it used to be re-sent at every later turn. Now images go to the model as images, and base64 is stripped from older turns. The model saw the page once; its own description of it is the source of truth after that.

Lesson: the model needs to know what's in a file, not to hold the file.

Make the prompt prefix cache-friendly

Providers cache prompt prefixes, but only if the beginning of your request is exactly the same as before. Our text-to-SQL tool injected the relevant tables of the schema in order of relevance. Relevance changes with every question, so the prefix did too.

We now write the selected tables in name order: same tables, same tokens, only the order changes. Share of each request that repeats the previous request's prefix, in our benchmark:

Schema Relevance order Name order
25 tables, all selected every time 11% 98%
80 tables, 62 or 63 selected per question 11% 93%

How we measured this, and what the number is not

The method. The benchmark sends 10 fixed questions against a fixed schema. For questions 2 to 10, it counts how much of each request matches the previous request's prefix, using OpenAI's caching rules: prefixes of at least 1,024 tokens, counted in 128-token blocks. The tokens sent and the tables selected are identical before and after; only the order changes. The script is bench/sql_prompt_cache/measure.py.

What the number is not.

  • Not the share actually served from the cache. That depends on the provider routing your requests to the same cache, and only shows up in the cached tokens your provider reports. Ours is an upper bound.
  • Not a cost reduction. Cached tokens are cheaper, not free, and pricing differs by provider.
  • Not a guarantee. Ordering alone doesn't make a prefix stable. It works best when the same tables come back from one question to the next, which is why the 80-table row is lower.

Two more things we learned the hard way:

  • Some providers cache nothing unless you ask. On Claude models, nothing was cached until we set cache markers: every call of a turn paid the instructions and tool declarations, 5,000 to 17,000 tokens depending on the agent, at the full rate.
  • Count cached tokens for what they cost. Our usage quotas counted cached input at full price. They now count it at 25%, otherwise users are charged for savings already made.

Lesson: keep the stable parts of your prompt stable. When your provider supports prompt caching, deterministic ordering can turn repeated context into reusable context.

Fewer round trips

Every extra model call re-pays the whole stack. So the cheapest call is the one that doesn't happen.

  • One grouped query instead of five. We gave the dashboard query tool a group_by parameter. On a real run, the model asked one grouped question instead of one query plus four filtered ones: from 71,617 to 42,130 input tokens, −41.2%, same correct answer.
  • Repair inside the tool, not in the agent's loop. When the database rejects a generated SQL query, the SQL tool now regenerates it once with the database error, instead of sending the error back to an agent that would re-read its whole context to try again.
  • Query and chart in one call for our Data Analyst agent, instead of two.

The catch: this kind of cut only pays if the model actually uses it. group_by adds 72 tokens to every call's declarations whether or not the model reaches for it. On real runs, it reached for it on 4 of 7 dashboard queries.

Lesson: look at how many calls a question takes before you look at how big each call is.

Trim the instructions, last

Removing an instruction block that described tools the agent didn't have saved about 2%. Worth doing, because the model was being told about tools it couldn't call. But it's the smallest win on this list, so it comes last.

3. What didn't work, or not the way we expected

This is the part I'd want to read in someone else's post.

Compacting the current turn. It looked like the obvious next step after shortening old results. The quality checks on facts and grounding failed on 4 scenarios. Within a turn, the model is still working on its results; take them away and it starts answering from memory. Without the bench, we'd have shipped it.

Trusting the bench too much. Our scripted replay overestimated real totals by 9 to 16%, because a real model doesn't always take the same path as a script. It also underestimated one gain by a lot: −13.8% on the bench for a dashboard question, −41.2% for real, because the real model changed its behavior (one grouped query) in a way a script can't.

A blind spot we didn't see. On real runs, the forecast scenario failed: the orders file has several rows per date, and our forecast engine expects one and doesn't aggregate them. None of the cuts caused it, but the bench never saw it, because it replays a canned forecast answer instead of calling the real engine. We left the forecast numbers out of the results, and aggregating by date before forecasting is on our list.

A cache we don't control. Depending on the session, between 17% and 66% of our input was already served from the provider's implicit cache, without us doing anything. Nice when it happens, impossible to plan for. That's why stable ordering matters: it turns luck into something you can count on.

The fix we almost made. Twice in one real run, the model tried to group by a period filter the tool didn't accept for grouping. Those two failed attempts cost about 27,000 input tokens. The reflex was a stricter docstring. We did the opposite: the tool now accepts what the model reached for, and its error lists the values it does accept. When a model keeps reaching for something, that's often a spec for the tool, not a mistake to forbid.

4. Memory that earns its tokens

None of this means agents should remember less. It means every token they re-read has to earn its place.

  • Sessions live in the database, so the conversation survives restarts. That was the point of the first post.
  • A window without amnesia. Our data and BI agents send a window of recent messages, and the text of the turns that fall out of it is kept: the agent forgets the bulk of what it pulled, not what was said.
  • Long-term memory, scoped per agent and per user, so one user's memories never leak into another's.
  • A case bank, on trial. Inspired by the Memento paper, each finished run becomes a case (task, tools called, outcome), and similar cases are shown before the next run. It's behind a flag, because memory isn't free either. We wrote the go/no-go down before the first real measurement: at least +10 points of success rate with 4 past cases, no rise in tool errors, at most +10% input tokens per task. The results aren't in yet.

And one guardrail ties it all together: a retry re-pays everything. When a provider hits its quota, our whole queue pauses instead of retrying every few seconds at full input cost, and a run is capped at 25 model calls, so a loop can't spin forever on your bill.

5. The results

Offline bench, all cuts combined (input tokens, scripted model, quality checks passing on these scenarios):

Scenario Before After Change
Dashboard creation 104,285 86,925 −16.6%
Dashboard question 75,227 64,811 −13.8%
Dashboard chat 151,177 98,321 −35.0%
Three-question conversation 286,522 196,983 −31.3%
First call 17,070 13,598 −20.3%

Real runs (input tokens read from our usage table, correct answers):

Measure Before After Change
First call floor ~14,500 ~11,800 −18.5%
Dashboard creation 82,212 63,526 −22.7%
Dashboard question 71,617 42,130 −41.2%

6. A checklist for your own agent

If you only take one thing from this post, run these seven checks:

  1. Weigh your first call. How many tokens does your agent send before the user's question? If you don't know, start there.
  2. Compare declared tools with called tools. Over your last few hundred runs, which tools were never called? Remove them from that agent.
  3. Look at what you re-send from past turns. Shorten old tool results. Never the current turn.
  4. Find the files and images in your context. Send a preview and let the agent reach the rest through tools. Send images as images.
  5. Check that your prefix is stable. Order what you inject deterministically, set cache markers where your provider needs them, and check the cached tokens your provider actually reports.
  6. Count calls per question. Look for loops and retries that re-pay the whole stack, and cap calls per run.
  7. Build a bench with quality checks before you cut, and confirm every gain on real runs.

Reproduce it, and make the bench yours

1. Reproduce our measurements. The bench, the scenarios and the results are in the repo:

git clone https://github.com/apowerb/apowerb && cd apowerb
python bench/bi_tokens/replay.py --estimates --compare bench/bi_tokens/results/main.json
Enter fullscreen mode Exit fullscreen mode

2. If you want to go further, contribute. The bench only knows our agents today. You can add a scenario that looks like your traffic (one JSON file in bench/bi_tokens/scenarios), make the forecast scenario call the real engine so the bench can't miss a failure like ours again, or fix the forecast by aggregating repeated dates. Comment on GitHub before you start, so we agree on the shape. The tech team reviews every PR, and contributors are credited by name.

The questions we don't have good answers to yet

This is where I'd genuinely like your experience. The last two posts got better because readers answered questions like these.

  1. Static tools or tools on demand? We declare a fixed toolbox per agent. The other school loads tool definitions only when the model asks for them. That saves the declarations, but costs an extra call to find the right tool. Where does on-demand start to pay: 30 tools, 50, 100? Have you measured it?
  2. Where does compaction stop? We never touch the current turn. But some turns pile up ten tool results before the model answers. Do you summarize inside a long turn, with a model that costs tokens itself, or truncate with a rule that might drop the one row that mattered?
  3. Implicit or explicit cache? Between 17% and 66% of our input came from our provider's implicit cache, depending on the session. We have an explicit cache wired in but turned off by default, because it means managing lifetimes and paying to write the cache. Has an explicit cache ever paid for itself in your agents, and at what traffic?
  4. How much should a cached token count? We weight cached input at 25% in our quotas. But providers price it differently, and some charge a premium to write the cache, which we don't track yet. How do you bill or budget cached tokens for your users?
  5. How do you build a bench that can't lie? Ours replays canned tool answers to stay cheap and repeatable, and that's exactly how it missed a real failure. Do you call real engines in your bench, and how do you keep it affordable and stable?

Answer in the comments, even with a single number. The best answers will shape the next changes in the repo, credited to you.

And if you only have time for one: how many tokens does your agent pay before it reads the user's question?

Before every single thought, our BI agent re-read 17,000 tokens of instructions and tool manuals.

Then the whole conversation. Then every table it had pulled since the first question. In our offline replay of a three-question conversation, ten model calls consumed 286,522 input tokens before optimization. Real runs behaved differently, as you'll see below.

Nobody had decided that. It's just what an agent does by default: every model call starts from zero, so everything the agent "knows" gets sent again. Every call, every turn, every retry.

This post is a field report on how we brought it down: how we measured, which cuts paid off and in what order, what didn't work, and a checklist you can run on your own agent tomorrow. It ends with five questions we can't answer alone. The optimizations reported here are implemented, and the benchmark is open source, so you can check every number. Some experiments and benchmark improvements are still in progress, and I'll say which.

It's the third post in a series about what breaks when AI agents run in production, after agents that forgot everything after a restart and agents that redid work they had already done. This one is about the opposite of amnesia: agents that remember too much, and pay for it on every call.

TL;DR: six lessons

  1. Measure before you cut. Without a bench and quality checks, our best-looking cut would have quietly broken the answers.
  2. Start with the tools. Instructions plus 36 tool declarations cost 17,000 tokens before the question. Removing the tools the agent never calls was the cheapest win.
  3. Forget the past, never the present. Shortening old tool results saved 21 to 26%. Shortening the current turn broke quality on 4 scenarios.
  4. Stable prompts are cacheable prompts. In our benchmark, ordering the schema tables deterministically raised the reusable prefix of a SQL prompt from 11% to 98%, with the same tokens.
  5. The biggest real gain came from fewer calls, not smaller ones: −41% on a question, because the model asked once instead of five times.
  6. Your bench will lie to you a little. Ours overestimated real gains by 9 to 16%, underestimated one by a lot, and missed a failure entirely.

1. Measure before you cut

Know what you're paying for

Here's what our BI agent sent to the model on every call, before we changed anything:

Layer What it is Paid when
Instructions the agent's system prompt every call
Tool declarations name, description and schema of each of 36 tools every call
History every message of the conversation every call
Past tool results every table, file and query result pulled so far every call
Current turn the question, and the results the model is working on now every call of this turn

The first two layers alone came to about 17,000 tokens: the whole first call weighed 17,070, a one-line question included. The model paid them before reading a word of the question, and again at each of the 3 to 5 calls a question takes.

We're not alone. The industry now calls it the "MCP tax": one measurement published in May found around 71,000 tokens of overhead for seven MCP servers, about 35% of a 200K context window, before the first prompt. And the cost isn't only money: research on context rot keeps showing that models get worse as their input grows, well before the window is full. A useless token is paid twice, on the bill and in the answer.

Build the bench first

We built a bench before touching anything. It lives in bench/bi_tokens:

  • Five scenarios of our BI agent: creating a dashboard, asking a question about it, chatting with it, a three-question conversation, and a forecast.
  • An offline replay with a scripted model, so each change is compared on identical calls, input tokens counted call by call.
  • Quality checks on every scenario: the right facts, grounded in the data. A cut that saves tokens but fails a check is rejected.
  • Real runs afterwards, with costs read from the usage table where every model call is recorded.

That last part matters more than it sounds. Section 3 explains why.

2. The cuts, ranked by effort and gain

Here's what we did, in the order we'd do it again:

Cut Effort Measured gain Watch out for
Remove the tools the agent never calls low −10 to −15% per scenario, first call −18.5% on real runs nothing observed
Shorten old tool results, past turns only low −21 to −26% on conversations never touch the current turn
Describe big payloads instead of pasting them low base64 page images no longer re-sent at every turn the agent must still reach the full data through tools
Make the prompt prefix cache-friendly low reusable prefix 11% → 98% (benchmark, upper bound) depends on your provider and on which tables are selected
Fewer round trips medium −41% on a question, real run only pays if the model uses it
Trim the instructions low about −2% small, do it last

Remove the tools the agent never calls

Our BI templates had inherited the generic chat tools of the platform, the ones a general assistant needs and a BI agent never calls. Most agent stacks ship this way; we just measured ours.

We removed ten of them from the BI templates, and trimmed what remained: declarations lost their pydantic titles and "Returns" sections, and tool responses are capped. 36 tools down to 26, and the first call went from 17,070 to 13,598 tokens on the bench. On real runs, together with the instruction trim described below, it went from about 14,500 to 11,800.

Lesson: an agent's toolbox is a cost line. Declare tools per agent, not per platform.

Shorten old tool results, never the current turn

After a few questions, most of the context was old tool results: tables the agent had pulled two turns ago and already answered from. Now, in every turn before the current one, a large tool result keeps its small fields (ids, titles, status, a message) and loses its bulk, with a note telling the model it can call the tool again if it needs the data.

def compact_previous_turns(contents):
    # The current turn starts at the last user message that isn't a tool result.
    current = current_turn_start(contents)
    for content in contents[:current]:          # earlier turns only
        for part in content.parts:
            if is_large_tool_result(part):
                part.response = keep_small_fields(part.response)  # ids, titles, status
Enter fullscreen mode Exit fullscreen mode

It runs on a copy: the stored session keeps everything, only what the model re-reads is shortened. And the answer the model gave at the time stays in the history, so what it concluded isn't lost.

Lesson: storing everything is cheap. Re-sending everything is what costs.

Describe big payloads instead of pasting them

  • Big files. A large CSV used to be pasted into the context. Now the agent gets the header, the first 20 rows and the row count, and works on the full data through its tools.
  • Images. In our pipeline, a base64-encoded PDF page was estimated at roughly 100,000 to 150,000 text tokens, depending on the page and its encoding (an estimate written down in our code when we hit it, not a formal benchmark), and it used to be re-sent at every later turn. Now images go to the model as images, and base64 is stripped from older turns. The model saw the page once; its own description of it is the source of truth after that.

Lesson: the model needs to know what's in a file, not to hold the file.

Make the prompt prefix cache-friendly

Providers cache prompt prefixes, but only if the beginning of your request is exactly the same as before. Our text-to-SQL tool injected the relevant tables of the schema in order of relevance. Relevance changes with every question, so the prefix did too.

We now write the selected tables in name order: same tables, same tokens, only the order changes. To measure the effect, our benchmark sends 10 fixed questions against a fixed schema, and counts, for questions 2 to 10, how much of each request matches the previous request's prefix, using OpenAI's caching rules (prefixes of at least 1,024 tokens, in 128-token blocks):

Schema Reusable prefix, relevance order Reusable prefix, name order
25 tables, all selected every time 11% 98%
80 tables, 62 or 63 selected per question 11% 93%

Three things this number is not. It's not the share actually served from the cache: that depends on the provider routing your requests to the same cache, and shows up in your usage data. It's not a cost reduction either. And ordering alone doesn't guarantee a stable prefix: it works best when the same tables come back from one question to the next, which is why the second row is lower.

Two more things we learned the hard way:

  • Some providers cache nothing unless you ask. On Claude models, nothing was cached until we set cache markers: every call of a turn paid the instructions and tool declarations, 5,000 to 17,000 tokens depending on the agent, at the full rate.
  • Count cached tokens for what they cost. Our usage quotas counted cached input at full price. They now count it at 25%, otherwise users are charged for savings already made.

Lesson: keep the stable parts of your prompt stable. When your provider supports prompt caching, deterministic ordering can turn repeated context into reusable context.

Fewer round trips

Every extra model call re-pays the whole stack. So the cheapest call is the one that doesn't happen.

  • One grouped query instead of five. We gave the dashboard query tool a group_by parameter. On a real run, the model asked one grouped question instead of one query plus four filtered ones: from 71,617 to 42,130 input tokens, −41.2%, same correct answer.
  • Repair inside the tool, not in the agent's loop. When the database rejects a generated SQL query, the SQL tool now regenerates it once with the database error, instead of sending the error back to an agent that would re-read its whole context to try again.
  • Query and chart in one call for our Data Analyst agent, instead of two.

The catch: this kind of cut only pays if the model actually uses it. group_by adds 72 tokens to every call's declarations whether or not the model reaches for it. On real runs, it reached for it on 4 of 7 dashboard queries.

Lesson: look at how many calls a question takes before you look at how big each call is.

Trim the instructions, last

Removing an instruction block that described tools the agent didn't have saved about 2%. Worth doing, because the model was being told about tools it couldn't call. But it's the smallest win on this list, so it comes last.

3. What didn't work, or not the way we expected

This is the part I'd want to read in someone else's post.

Compacting the current turn. It looked like the obvious next step after shortening old results. The quality checks on facts and grounding failed on 4 scenarios. Within a turn, the model is still working on its results; take them away and it starts answering from memory. Without the bench, we'd have shipped it.

Trusting the bench too much. Our scripted replay overestimated real totals by 9 to 16%, because a real model doesn't always take the same path as a script. It also underestimated one gain by a lot: −13.8% on the bench for a dashboard question, −41.2% for real, because the real model changed its behavior (one grouped query) in a way a script can't.

A blind spot we didn't see. On real runs, the forecast scenario failed: the orders file has several rows per date, and our forecast engine expects one and doesn't aggregate them. None of the cuts caused it, but the bench never saw it, because it replays a canned forecast answer instead of calling the real engine. We left the forecast numbers out of the results, and aggregating by date before forecasting is on our list.

A cache we don't control. Depending on the session, between 17% and 66% of our input was already served from the provider's implicit cache, without us doing anything. Nice when it happens, impossible to plan for. That's why stable ordering matters: it turns luck into something you can count on.

The fix we almost made. Twice in one real run, the model tried to group by a period filter the tool didn't accept for grouping. Those two failed attempts cost about 27,000 input tokens. The reflex was a stricter docstring. We did the opposite: the tool now accepts what the model reached for, and its error lists the values it does accept. When a model keeps reaching for something, that's often a spec for the tool, not a mistake to forbid.

4. Memory that earns its tokens

None of this means agents should remember less. It means every token they re-read has to earn its place.

  • Sessions live in the database, so the conversation survives restarts. That was the point of the first post.
  • A window without amnesia. Our data and BI agents send a window of recent messages, and the text of the turns that fall out of it is kept: the agent forgets the bulk of what it pulled, not what was said.
  • Long-term memory, scoped per agent and per user, so one user's memories never leak into another's.
  • A case bank, on trial. Inspired by the Memento paper, each finished run becomes a case (task, tools called, outcome), and similar cases are shown before the next run. It's behind a flag, because memory isn't free either. We wrote the go/no-go down before the first real measurement: at least +10 points of success rate with 4 past cases, no rise in tool errors, at most +10% input tokens per task. The results aren't in yet.

And one guardrail ties it all together: a retry re-pays everything. When a provider hits its quota, our whole queue pauses instead of retrying every few seconds at full input cost, and a run is capped at 25 model calls, so a loop can't spin forever on your bill.

5. The results

Offline bench, all cuts combined (input tokens, scripted model, quality checks passing on these scenarios):

Scenario Before After Change
Dashboard creation 104,285 86,925 −16.6%
Dashboard question 75,227 64,811 −13.8%
Dashboard chat 151,177 98,321 −35.0%
Three-question conversation 286,522 196,983 −31.3%
First call 17,070 13,598 −20.3%

Real runs (input tokens read from our usage table, correct answers):

Measure Before After Change
First call floor ~14,500 ~11,800 −18.5%
Dashboard creation 82,212 63,526 −22.7%
Dashboard question 71,617 42,130 −41.2%

6. A checklist for your own agent

If you only take one thing from this post, run these seven checks:

  1. Weigh your first call. How many tokens does your agent send before the user's question? If you don't know, start there.
  2. Compare declared tools with called tools. Over your last few hundred runs, which tools were never called? Remove them from that agent.
  3. Look at what you re-send from past turns. Shorten old tool results. Never the current turn.
  4. Find the files and images in your context. Send a preview and let the agent reach the rest through tools. Send images as images.
  5. Check that your prefix is stable. Order what you inject deterministically, set cache markers where your provider needs them, and check the cached tokens your provider actually reports.
  6. Count calls per question. Look for loops and retries that re-pay the whole stack, and cap calls per run.
  7. Build a bench with quality checks before you cut, and confirm every gain on real runs.

The questions we don't have good answers to yet

This is where I'd genuinely like your experience. The last two posts got better because readers answered questions like these.

  1. Static tools or tools on demand? We declare a fixed toolbox per agent. The other school loads tool definitions only when the model asks for them. That saves the declarations, but costs an extra call to find the right tool. Where does on-demand start to pay: 30 tools, 50, 100? Have you measured it?
  2. Where does compaction stop? We never touch the current turn. But some turns pile up ten tool results before the model answers. Do you summarize inside a long turn, with a model that costs tokens itself, or truncate with a rule that might drop the one row that mattered?
  3. Implicit or explicit cache? Between 17% and 66% of our input came from our provider's implicit cache, depending on the session. We have an explicit cache wired in but turned off by default, because it means managing lifetimes and paying to write the cache. Has an explicit cache ever paid for itself in your agents, and at what traffic?
  4. How much should a cached token count? We weight cached input at 25% in our quotas. But providers price it differently, and some charge a premium to write the cache, which we don't track yet. How do you bill or budget cached tokens for your users?
  5. How do you build a bench that can't lie? Ours replays canned tool answers to stay cheap and repeatable, and that's exactly how it missed a real failure. Do you call real engines in your bench, and how do you keep it affordable and stable?

Answer in the comments, even with a single number. The best answers will shape the next changes in the repo, credited to you.

Reproduce it, then tell us your numbers

1. Reproduce our measurements. The bench, the scenarios and the results are in the repo:

git clone https://github.com/apowerb/apowerb && cd apowerb
python bench/bi_tokens/replay.py --estimates --compare bench/bi_tokens/results/main.json
Enter fullscreen mode Exit fullscreen mode

2. Share your own numbers in the comments. Run the checklist on your agent and post what you find, even just the first one: how many tokens it pays before the user's question. The last two posts got better because readers answered, and I'd bet this one will too.

3. If you want to go further, contribute. The bench only knows our agents today. You can add a scenario that looks like your traffic (one JSON file in bench/bi_tokens/scenarios), make the forecast scenario call the real engine so the bench can't miss a failure like ours again, or fix the forecast by aggregating repeated dates. Comment on GitHub before you start, so we agree on the shape. The tech team reviews every PR, and contributors are credited by name.

How many tokens does your agent pay before it reads the user's question?


Code : https://github.com/apowerb/apowerb
Docs : https://docs.apowerb.com/
Deploy with Docker Compose or Helm : https://github.com/apowerb/apowerb-hosting
Try it out : https://apowerb.com

Top comments (58)

Collapse
 
max_quimby profile image
Max Quimby •

The "fewer calls beats smaller calls" lesson is the one I keep relearning. We spent a while shaving tool-result size and got modest wins, then realized a single turn that made the model call out five times was costing more than all the context we'd trimmed — collapsing that to one call dwarfed everything else.

One trap worth flagging on the pruning side: when you shorten or drop old tool results, the agent sometimes just re-calls the tool to recover the data it threw away, so the "saving" shows up as a new call two turns later. We only caught it because total tokens per conversation barely moved even though per-call tokens dropped.

On caching — the deterministic ordering point is huge and underrated. A prefix that's 98% reusable vs 11% is the same tokens on paper but a completely different bill. How are you deciding which quality regressions are acceptable? Your note that the bench missed a failure entirely is the part that would keep me up at night.

Collapse
 
anis_meziani_52aab42304a8 profile image
Anis Meziani •

Thanks Max, the re-call trap is a real gap for us. Our bench replays a scripted model, so it never re-fetches by construction, and our real runs were single questions, not long conversations. Your "per-call down, total flat" check is exactly what we haven't run on real traffic yet.

Up for an issue on a re-fetch rate (same tool, same arguments, after compaction)? Your check as the spec, credited to you.

On regressions: none accepted on the bench, one failed check rejects the cut. The missed failure keeps me up too: the fix is making the forecast scenario call the real engine instead of a canned answer.

How did you fix the re-calls: more fields kept, or summaries instead of truncation?

Collapse
 
glenallen profile image
Glen Allen •

One important takeaway is that optimizing AI agents isn't just about reducing prompt length; it's about managing context and tool usage intelligently. Removing unused tool definitions, compacting older tool results, and reducing unnecessary model calls can significantly improve efficiency without sacrificing answer quality. At IT Path Solutions, we see evaluation and real-world testing as essential parts of building reliable AI agents. Measuring token consumption alongside response accuracy helps teams make optimizations that deliver genuine cost savings while preserving performance.

Collapse
 
mmarchand04 profile image
Mathis Marchand •

This is a brilliant and much-needed breakdown of token optimization for AI agents in production!
Providing a 7-point checklist alongside an open-source bench is incredibly valuable for the community.
Thanks for sharing this transparent field report on your successes and failures to help us save time and money.

Collapse
 
paul_irolla_6b5ae261d0224 profile image
Paul Irolla •

Splitting the fixed prefix from the work is the step many benches skip: those tokens are re-sent with every request before any task starts. Did they come mostly from tool schemas, or from the system prompt?

Collapse
 
anis_meziani_52aab42304a8 profile image
Anis Meziani •

Thanks Paul. Mostly the tool schemas. On the first call, before any cut, the tool declarations were 52,014 characters and the system prompt 11,191: about 82% tools. After removing 10 unused tools and trimming the rest, it's 40,778 vs 9,790, still about 80% tools.

The bench already logs that split for every call (system prompt, tools, history), but in characters. Tokens are only counted for the whole call. Counting them per layer would be a small PR in replay.py. If you're up for it, it's yours, credited by name.

Collapse
 
alexshev profile image
Alex Shev •

Offline replay is a good starting point, but the live-run difference matters. Comparing token savings alongside task success and retrieval misses would show when a shorter context becomes too lossy.

Collapse
 
anis_meziani_52aab42304a8 profile image
Anis Meziani •

Agreed. The bench already pairs savings with quality: every answer is checked for the right facts, and for numbers that don't appear in what the model actually saw. That check is what told us compacting the current turn was too lossy (4 scenarios failed).

On live runs, we only checked answers by hand so far. Tracking success rate and re-fetches next to tokens there is the next step. How do you measure retrieval misses on your side?

Collapse
 
alexshev profile image
Alex Shev •

For retrieval misses I track expected support IDs per scenario, then measure whether any supporting chunk reached the model at k. That gives retrieval recall separately from answer quality; traces also reveal when the right chunk arrived but was ignored.

Thread Thread
 
anis_meziani_52aab42304a8 profile image
Anis Meziani •

Nice, that's close to our facts check: each scenario lists the facts the answer needs, and we check they reached the model, separately from the answer. "Arrived but ignored" is the case we don't separate yet. Up for opening an issue on it? github.com/apowerb/apowerb/issues

Thread Thread
 
alexshev profile image
Alex Shev •

That split would make the benchmark much more diagnostic. I would model three states: support was retrieved, support was selected into context, and support was used in the answer. A miss at each stage points to a different fix, so it is worth keeping them separate.

Thread Thread
 
anis_meziani_52aab42304a8 profile image
Anis Meziani •

Agreed, three states is the right model. Today our facts check covers the second (in context), and the grounding check part of the third. Retrieved vs selected isn't separated at all.

I opened an issue with your three states as the spec, credited to you: github.com/apowerb/apowerb/issues/511

Feel free to take it from there, comments or a PR.

Collapse
 
kevinhall profile image
Kevin Hall •

Your 80% on tools matches what I measured on a hosted MCP server: per Actor tool, the output schema inferred from sample rows was the larger half in 9 of 20 tools, up to about 32K tokens in one. If any of your 36 declarations carry a generated output schema, I would check that half before the descriptions.

Collapse
 
anis_meziani_52aab42304a8 profile image
Anis Meziani •

Good catch, and it matches what we found, in another form. Our declarations go out in the OpenAI format through LiteLLM: name, description, input parameters, no output schema field. The output half hid in the docstrings instead: the "Returns" sections, which we cut along with the unused tools. 32K for one tool is wild. Was that schema actually helping the model, or just inferred by default?

Collapse
 
kevinhall profile image
Kevin Hall •

Inferred by default, the server builds it from sample rows. Whether the model gets better calls from it I have not measured, so I cannot say it earns its tokens.

Thread Thread
 
anis_meziani_52aab42304a8 profile image
Anis Meziani •

Cheap test: same tasks with and without the schema, compare failed calls next to tokens. If nothing moves, 32K is pure tax.

Collapse
 
kartik-nvjk profile image
Kartik N V J K •

Two failed attempts to group by a period filter, about 27,000 input tokens gone, and my reflex would have been a stricter docstring too. I like that you widened the tool and made the error list the values it accepts. I'd add a log of rejected argument values per tool across runs, so whatever the model keeps reaching for shows up before anyone touches the prompt.

Collapse
 
anis_meziani_52aab42304a8 profile image
Anis Meziani •

Great idea. Today rejected values only live in each session's trace, which is how we found these two by hand. A per-tool log across runs would have shown the pattern without anyone digging. Up for opening an issue? github.com/apowerb/apowerb/issues

Collapse
 
baigorria profile image
Guillermo Baigorria •

The 17% to 66% cached share on your real runs caught my eye.

In my experience, much of that spread comes from the cache expiring, not from the prefix changing. Calls after a tool come seconds apart. The next question comes after the person reads the answer and types, and by then the cache is often gone.

Something that could help with your Q3 is logging the cached share next to the time since the previous call, for example:

  • after a tool, 4 s later: 95% cached
  • next question, 6 min later: 30% cached

If the share drops only after long gaps, the prefix is fine and the cache is just expiring. If it drops after short gaps too, something in the prefix changes, like the compaction at the turn boundary discussed above. Long gaps are also where an explicit cache with a longer lifetime could pay for its writes.

Collapse
 
aifrontierpost profile image
AI Frontier Post •

Cutting the first call from 17,070 tokens to 13,598 tokens is useful, but the 72 token group_by add on every call shows the trap. A grouped query only pays when the model actually uses it, so call counts matter more than call size.

Collapse
 
anis_meziani_52aab42304a8 profile image
Anis Meziani •

Agreed. The declaration costs 72 tokens per call, and one grouped query saved about 29,500 on a real run. So it pays off if the model uses it even rarely, and on real runs it used it on 4 of 7 dashboard queries.

Do you track usage per tool to decide what stays declared?

Collapse
 
robertpaschal profile image
Odinaka Robert Nnamani •

The deterministic table ordering detail stuck with me: same tables, same tokens, just sorted by name, and the reusable prefix jumps from 11% to 98%. Worth checking before trimming anything else.

Collapse
 
anis_meziani_52aab42304a8 profile image
Anis Meziani •

Thanks! Cheapest fix on the list. Just note 98% is an upper bound: check the cached tokens your provider actually reports.

Collapse
 
robertpaschal profile image
Odinaka Robert Nnamani •

Fair point. A reusable prefix and a served cache hit are different numbers, so the provider report is the one to trust here.