Reducing Tokens, Tool Calls and Spend

The cheapest token is the one you never send. The most expensive saving is the one that breaks the task.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

Measure where spend goes, then try changes in order of low risk: remove waste such as loops and oversized tool results, make the prompt prefix cacheable, cut unnecessary steps, move patient work to batch and route suitable steps to smaller models. Keep a change only if tests show quality and safety hold and the total cost, including failures, falls.

What you will learn: how to find waste, reduce tokens, tool calls and reasoning, reuse results, weigh parallel work against spend and judge quality against cost.
Prerequisites: Agent Cost Model and Token Economics and Agent Evaluation Framework.

Versions used

The example runs in November 2026 with Python 3.13 and only the standard library. Its costs, success rates and effects of each change are invented to show the method; they are not typical savings.

Beginner Find the waste first

Look before cutting

Take a sample of real runs and read them. Record for each step the input, cached input and output tokens, the tool called and whether the step helped. Patterns usually stand out quickly:

What you seeLikely causeFirst fix
The same call repeatedUnclear error or no memory of the resultBetter error messages; detect repetition
Huge input after one toolRaw records or whole pages returnedReturn only needed fields
Many searches for one factWeak retrievalImprove search before the prompt
Long preambles in outputNo format guidanceAsk for concise, structured replies
Runs hitting the step limitTask unclear or impossibleStop early and ask or escalate
Expensive model for trivial stepsOne model for everythingRoute by step type

Rank opportunities by money: frequency times cost per occurrence. An ugly but rare waste may not be worth an hour.

An order to try things in

Wasteloops, failures
Cacherepeated prefix
Trimcontext and steps
Routesmaller models
Reworkcode instead

The order is a guide to risk. Removing a loop cannot make answers worse. Changing the planning model can.

Intermediate Tokens, caches and calls

Send fewer tokens

  • Tool definitions: offer only the tools relevant to the current task or phase, and keep descriptions clear but short.
  • Tool results: filter, paginate and summarize on the server. Return identifiers for details fetched only when needed.
  • History: clear old raw results that have been used, or compress them while keeping decisions, identifiers and open items (Context Assembly, Retrieval, Compression and Caching).
  • Retrieval: pass a few well-ranked passages, not many weak ones.
  • Documents: send the relevant sections, and keep the rest in files the agent can search.
  • Output: set sensible length limits and structured formats.
Compression loses things

A summary can drop the one constraint that mattered, such as "do not contact this customer". Keep rules and identifiers outside the summary, and test long tasks before and after.

Make prefixes cacheable

Prompt caches reuse an identical beginning. Arrange context from most stable to most variable:

1. Fixedtool definitions and system instructions
2. Slowreference material shared by many tasks
3. Growinghistory, appended without rewriting earlier text

Things that silently break the cache include a timestamp or request identifier at the top, tools listed in varying order, and rewriting earlier messages. Check the usage figures for cached tokens after each change; do not assume.

Discounts and write charges differ by provider and model. Anthropic's pricing page shows cache reads priced at a small fraction of base input and writes above it, so a prefix that is written and never read again costs more than not caching it.

Reuse results

ReuseSafe when
Cache read-only tool resultsData changes slowly and the key includes the user's permissions
Cache embeddingsText and embedding model are unchanged
Cache exact answersSame input, versions and data
Similarity cacheLow-risk questions, tested with near misses
Save a plan or templateMany tasks share structure

See Scaling, Hardware, Quotas and Caching for key design and invalidation.

Shrinking a tool result: an illustration

Imagine a search tool that returns twenty full records of about 800 tokens each, 16,000 tokens in all, when the agent needs a name, status and date. Returning those three fields for five best matches might take a few hundred tokens, with an identifier for fetching a full record if required. Because the result stays in history, the saving repeats on every later call: over eight further steps, 16,000 tokens would have been sent eight more times, about 128,000 input tokens, partly at cached rates if caching applies.

Check two things after such a change. Does the agent now make extra calls to fetch details it often needs? And can it still tell when no result matched? A trimmed reply should say how many records matched in total, so that "five shown" is not read as "five exist" (Designing Tool Schemas and Contracts).

Fewer tool calls and less reasoning

  • Offer a tool that does a common sequence in one call, such as "get order with shipments".
  • Do deterministic work in code: arithmetic, sorting, validation and fixed routing.
  • Let the agent run a small program that filters data, in a safe sandbox, so raw rows never enter the context.
  • Make errors actionable so the next attempt succeeds.
  • Set step, time and spend limits, and detect repeated states.
  • Where a model offers adjustable reasoning effort, test lower settings by task type instead of using one level everywhere.

Removing a step saves its own cost and the cost of carrying its result through later steps. But do not remove verification simply because it looks like extra work; test what it catches.

Move patient work to batch

Classification backfills, nightly summaries and evaluation runs often do not need an immediate answer. Both Anthropic and OpenAI advertise batch processing at half the standard token price, in return for asynchronous completion. Interactive agent loops fit badly, because each step waits for the one before. Plan for partial failures and for results arriving in any order.

Expert Models, parallelism and trade-offs

Route to suitable models

Small models can be accurate enough for classification, extraction and formatting. Planning and ambiguous judgment often benefit from stronger ones. Options include fixed assignment by step, a cheap first attempt with escalation when a check fails, and a trained router.

Escalation is only as good as its check. If the check is the small model's own confidence, errors slip through. Prefer checks in code, and include the cost of failed first attempts. Switching models mid-conversation may also lose cached prefixes. See Model Routing, Fallbacks and Gateways and Choosing Models: Reasoning, Open-Weight and Hosted.

For high, steady volume of a narrow task, fine-tuning or distilling a small model can pay off. Count data preparation, evaluation and upkeep (Fine-Tuning vs RAG vs Prompting vs Long Context).

Parallelism and cost

PatternTimeSpend
Run independent tool calls togetherLessAbout the same, sometimes fewer model turns
Split a large job into partsLessRepeated instructions in every part
Several subagents exploringLess wall timeOften much higher
Race two models and take the firstLess in slow casesPays for work thrown away
Generate several answers and voteSimilarMultiplied by the number of answers

Cache entries may not be ready for calls started at the same instant, so many parallel calls with one new prefix can each pay to write it. Check your provider's behavior; sending one first and then the rest can help.

Judge quality against total cost

The example starts with a task costing 0.10 that succeeds 92 percent of the time, with 2.00 to handle a failure. Changes are applied one at a time. A change is kept only if success stays at or above 91 percent and expected total cost falls.

"""Apply savings one at a time and keep only those that hold quality (invented)."""
BASE = {"cost": 0.100, "success": 0.920}
CHANGES = [   # name, cost multiplier, success change measured on the test set
    ("cache the stable prompt prefix", 0.72, 0.000),
    ("trim tool results", 0.85, +0.004),
    ("small model for classification", 0.90, -0.003),
    ("small model for planning", 0.70, -0.065),
    ("drop the verification step", 0.88, -0.040),
]
FLOOR = 0.910
FAILURE_COST = 2.00     # staff time when a task fails


def total(cost, success):
    return cost + (1 - success) * FAILURE_COST


if __name__ == "__main__":
    cost, success = BASE["cost"], BASE["success"]
    print(f"{'start':<34}cost ${cost:.4f} success {success:.1%} "
          f"total ${total(cost, success):.4f}")
    for name, factor, delta in CHANGES:
        c, s = cost * factor, success + delta
        keep = s >= FLOOR and total(c, s) < total(cost, success)
        print(f"{name:<34}cost ${c:.4f} success {s:.1%} total ${total(c, s):.4f} "
              f"{'keep' if keep else 'reject'}")
        if keep:
            cost, success = c, s
    print(f"\nmodel spend down {1 - cost / BASE['cost']:.0%}, success {success:.1%}")

Output:

start                             cost $0.1000 success 92.0% total $0.2600
cache the stable prompt prefix    cost $0.0720 success 92.0% total $0.2320 keep
trim tool results                 cost $0.0612 success 92.4% total $0.2132 keep
small model for classification    cost $0.0551 success 92.1% total $0.2131 keep
small model for planning          cost $0.0386 success 85.6% total $0.3266 reject
drop the verification step        cost $0.0485 success 88.1% total $0.2865 reject

model spend down 45%, success 92.1%

Caching and trimming are clear gains. The two rejected changes lower model spend and raise total cost, because failures are far more expensive than tokens in this scenario. With a very low failure cost, the answer could reverse.

Look at the third change. It improves expected total by only 0.0001 while success drifts down by 0.3 points. No realistic test set could confirm differences that small, so a careful team would treat it as unproven and decide on other grounds, or gather much more evidence. The program's rule is mechanical; your judgment should not be.

Run the comparison properly

  • Same cases for both versions, repeated where outputs vary.
  • Safety cases must still all pass.
  • Check results by task type; a saving may harm one group.
  • Remeasure after combining changes, since effects interact.
  • Confirm with a gradual release and watch delayed outcomes (CI/CD, Infrastructure as Code and Safe Releases).

The cost of the surroundings

Savings often hide outside the main model calls:

AreaPossible savingDo not
Traces and logsSample routine successes, shorten retention, drop duplicated payloadsDrop records of actions, denials or failures
EvaluationSelect tests by change, batch large runs, use code checks before model gradersSkip safety cases before release
IndexesRe-embed only changed content, remove duplicates, consider smaller vectors after testingLose access labels or freshness
Idle infrastructureScale down test environments, remove unused deploymentsRemove spare capacity that your recovery plan needs
Human reviewShow evidence clearly, order by risk, reduce unnecessary requestsReduce review without evidence that quality allows it

Guardrails on spend

Efficiency work lowers the typical cost. Limits cap the worst case: maximum steps and tokens per run, daily budgets per user and agent, alerts on unusual spend and a clear behavior when a limit is reached, such as returning partial results and asking to continue. Attackers can try to make an agent consume resources, so these limits are a security measure too (Agent FinOps, Budgets and Chargeback).

Keeping the gains

Savings erode as features are added: a longer instruction here, another tool there, a verbose reply from a new service. Add budgets for input tokens and steps per task to the release gate, report them by release and investigate a jump even when quality is fine. Review tool lists and instructions periodically and delete what no longer earns its place. Record why each optimization exists, with the test that protects it, so that nobody removes a cache-friendly ordering or a result filter while tidying code.

When to stop optimizing

Estimate the saving per month and compare it with the effort to make and maintain the change. A clever routing layer that saves little adds a component to test and debug. Revisit the list when volume grows or prices change; an idea not worth doing now may be later.

A two-week efficiency sprint

A short, bounded effort works better than vague pressure to spend less:

DaysWorkOutput
1–2Collect runs, agree success rules and record the baselineCost per success by task type
3–4Read expensive runs and rank causesShort list with estimated monthly value
5–7Fix loops, errors and oversized resultsTested changes
8–9Improve cache layout and move patient jobs to batchMeasured hit rate and bill effect
10Canary, report and decide the next itemBefore and after, including what was rejected

Report rejected ideas with their evidence. They protect the team from repeating them and show that quality was weighed. Then add a regression check on steps and tokens per task, so that the gains do not quietly erode with later releases.

Common mistakes

MistakeBetter approach
Switching to a cheaper model firstRemove waste and cache before changing quality
Measuring tokens onlyCompare cost per success and expected total
Changing prompts in ways that break cachingKeep stable content first and check cache hits
Cutting verification blindlyTest what it prevents
Assuming parallel means cheaperCount repeated and discarded work
Quoting savings from one exampleTest a representative set

Checklist

  • Real runs have been read and waste ranked by money.
  • Tool results and tool lists are trimmed.
  • Cache hit rate is measured.
  • Deterministic work runs in code.
  • Patient work uses batch where it fits.
  • Every change was compared on the same cases.
  • Safety cases still pass.
  • Per-run and daily limits are enforced.

Frequently asked questions

What usually saves the most?

It depends on your runs; oversized context, repeated steps and low cache use are common places to look first.

Does a shorter prompt always cost less?

Not if the change breaks caching, causes extra steps or increases failures, so measure the whole task.

Is multi-agent design more expensive?

It often uses more tokens through repeated context and coordination, which must be justified by better results.

Can we cut evaluation cost?

Run small relevant sets on each change, use batch for large runs and keep full safety coverage before release.

References and further reading

Next steps