On this page (12 sections)
- Why agent costs vary
- 1. Multi-step execution
- 2. Context that grows with every step
- 3. Retries and errors
- 4. Tool loops and dead ends
- 5. Model and configuration choices
- Start by measuring the right unit
- Method 1: budgets per task
- Method 2: model routing
- Method 3: caching
- Prompt caching
- Response and semantic caching
- Method 4: smaller and specialized models
- Method 5: batching
- Method 6: context trimming
- Method 7: evaluation-gated changes
- Method 8: monitoring and alerts
- Common mistakes
- Where Gepton can help
In short: a chatbot answers a question with one model call; an agent may make ten, fifty or more, and the number changes with every task. Running costs vary because of the number of steps, the size of the context carried through them, retries and tool loops. You make them predictable by measuring cost per completed task, capping each run with a budget, sending each step to the smallest model that does it well, reusing work through caching, moving non-urgent jobs to batch processing, keeping context lean, and allowing no change into production without an evaluation that checks quality and cost together. Monitoring and alerts close the loop. This guide explains each method. It deliberately contains no figures: provider rates change often, so work from your provider's current documentation and your own measurements.
Why agent costs vary
Most model providers bill by tokens, the units of text a model reads (input) and writes (output), and in some cases by tool use, images or audio. For a single call, the bill is easy to reason about. Agents break that simplicity in five ways.
1. Multi-step execution
An agent plans, calls a tool, reads the result, decides what to do next, and repeats until the task is done. The number of steps depends on the task and on the model's own choices. Two similar requests can take very different paths: one finds the answer in the first search, the other needs six lookups and a clarification.
2. Context that grows with every step
Each step usually re-sends the system prompt, tool definitions, conversation so far and all earlier tool results. Input grows with every turn, so a long run costs more than the sum of its steps looks like it should. Large tool outputs, such as a full web page, a long document or a big database result, are the usual cause.
3. Retries and errors
Timeouts, rate limits, malformed tool arguments and failed validations trigger retries. Each retry can re-send the full context. A flaky downstream API can quietly multiply cost.
4. Tool loops and dead ends
Agents sometimes repeat the same action, search again with slightly different wording, or oscillate between two tools without progress. Without limits, a loop runs until something external stops it.
5. Model and configuration choices
Larger models cost more per token than smaller ones. Extended reasoning or "thinking" modes produce more output tokens. Output is usually billed at a higher rate than input. A default set during a prototype, such as the largest model with maximum reasoning for every step, often survives into production.
The result is a wide distribution of cost per task with a long tail: most runs are modest and a few are very expensive. Averages hide that tail, and the tail is what surprises finance teams.
Start by measuring the right unit
Provider invoices report tokens by model and day. You need cost per completed task, per workflow, per customer and per step. Instrument every run so each model call records the workflow, run ID, step, model, input tokens, cached tokens, output tokens, latency and outcome. Tracing tools that follow the OpenTelemetry generative AI conventions, or agent observability platforms, make this straightforward. Then compute:
- Cost per successful task, not per call. A lower-cost setup that fails more often can cost more per success.
- The distribution, not just the mean: median, 90th and 99th percentile cost per task.
- Where tokens go by step: planning, retrieval, tool results, final answer.
- Cache hit rate and retry rate.
With this in place, a handful of workflows and steps usually explain most of the spend, and you know where to act first.
Method 1: budgets per task
A budget turns an open-ended loop into a bounded one. Set limits per run on the number of steps, tool calls, total tokens and wall-clock time, and decide what happens when a limit is hit: stop and return a partial answer, hand off to a human, or ask the user whether to continue. Add budgets at other levels too: per user, per tenant and per workflow per day, enforced by the gateway or orchestration layer rather than by the prompt. Set the limits from the measured distribution, for example a little above the 99th percentile of successful runs, and review them when the workflow changes.
Guard against loops explicitly: detect repeated identical tool calls, cap retries per step with backoff, and make tools return short, structured errors the agent can act on instead of long stack traces it will re-read.
Method 2: model routing
Not every step needs the most capable model. Classification, extraction, formatting, simple lookups and tool-argument filling often work well on small models; complex planning, ambiguous requests and final answers to hard questions may need a larger one. Routing sends each request or step to the smallest model that meets the quality bar. Common patterns:
- Static routing by step: the planner uses a larger model, workers use smaller ones.
- Classifier routing: a fast model or rules decide the difficulty of each request first.
- Cascades: try the small model, check the result with validation rules or a confidence signal, and escalate only on failure.
Routing needs evaluations per route, otherwise savings on easy cases hide failures on hard ones. Keep reasoning effort as a separate setting per step: many steps need little or none.
Method 3: caching
Prompt caching
Major providers offer prompt caching, which reuses the processed state of a repeated prompt prefix so identical leading content is billed at a reduced rate and processed faster. It suits agents well, because the system prompt, tool definitions and early conversation repeat on every step. The mechanics differ by provider. OpenAI's prompt caching is applied automatically to prompts above a minimum length. Anthropic's prompt caching uses cache breakpoints set per request or automatically, with a short default lifetime that refreshes on use and a longer option. Google offers implicit and explicit context caching for Gemini. The practical rules are the same everywhere:
- Put stable content first (tool definitions, system prompt, fixed reference material) and changing content last.
- Do not put timestamps, request IDs or per-user data near the top of the prompt; one changed character early in the prompt invalidates everything after it.
- Keep tool definitions identical across requests, in the same order.
- Append to conversations instead of rewriting earlier turns.
- Check the cached-token fields in the usage data to confirm hits, and watch cache lifetimes for traffic with gaps.
Response and semantic caching
Where the same question gets the same answer, such as policy lookups, product facts or repeated classification of identical inputs, store and reuse the final answer. Exact-match caching is safe and simple. Semantic caching, which matches similar questions by embedding, needs care: set conservative thresholds, scope caches per tenant, never share cached answers that contain personal data, and expire entries when source content changes. Tool results can also be cached, for example the same database lookup within a run.
Method 4: smaller and specialized models
When a high-volume step is narrow and well defined, a small model fine-tuned or distilled on examples from a larger one can match its quality on that task. Open-weight models served on your own infrastructure are another option when volume is steady enough to keep hardware busy; they convert per-token cost into capacity cost, which is predictable but requires you to manage utilization. Our model training and fine-tuning service covers this route. Keep the larger model as a fallback for inputs the small one handles poorly.
Method 5: batching
Work that does not need an answer in seconds, such as nightly document processing, bulk classification, evaluations and backfills, can go through a provider's batch interface. Batch jobs are processed asynchronously within a stated window (commonly up to 24 hours), usually at a lower rate than real-time calls and with separate rate limits. See, for example, OpenAI's Batch API documentation; Anthropic and Google offer equivalents. For self-hosted models, continuous batching in the serving layer raises throughput per GPU. Separate interactive and background workloads so each can be tuned on its own.
Method 6: context trimming
Context is usually the largest cost driver in agents, and the one most within your control.
- Summarize or drop old turns once they are no longer needed, keeping a short running state instead of the full history.
- Shape tool outputs: return only the fields the agent needs, paginate, and truncate long text with a pointer to fetch more.
- Retrieve less, better: fewer, more relevant passages through better chunking and reranking.
- Load tools on demand: large tool catalogs add tokens to every call; expose only the tools relevant to the current step.
- Tighten prompts: remove duplicated instructions and examples that evaluations show make no difference.
- Cap output length and ask for structured output where free text is not needed.
Trimming interacts with caching: removing content from the middle of the prompt can break cache reuse. Design both together.
Method 7: evaluation-gated changes
Every cost method above can reduce quality. The safeguard is an evaluation set built from real tasks, with a scored baseline for the current setup. Any change, whether a new model, a routing rule, a trimmed prompt or a new cache, must pass the evaluation before release, and the report should show quality, latency and cost per task side by side. Run the same gate when a provider releases a new model version: newer models can use more or fewer tokens for the same task. Roll out gradually and compare live metrics against the control group. See AI evaluation and observability for how we set this up.
Method 8: monitoring and alerts
Predictability comes from seeing drift early. Useful signals:
- Cost per successful task per workflow, with trend lines.
- Percentile cost per task, so the tail is visible.
- Runs that hit step, token or time limits.
- Cache hit rate, retry rate and tool error rate.
- Spend per tenant and per day against the budget, with forecast to month end.
- Sudden changes after a deploy, a prompt change or a provider model update.
Alert on rate of change and on budget thresholds, not only on totals, and route alerts to the team that owns the workflow. Tag every call with workflow and tenant so spend can be charged back; the same practice is central to cloud cost FinOps.
Common mistakes
- Estimating from a few demo runs instead of the distribution of real tasks.
- Optimizing cost per call rather than cost per successful task.
- Putting dynamic content at the top of prompts and never getting cache hits.
- Letting agents return whole documents or raw API responses into context.
- Switching to a lower-cost model without an evaluation, then paying for failures in retries and human rework.
- Budget limits that exist only as prompt instructions, which the model may ignore.
Where Gepton can help
Our AI cost optimization service measures cost per task across your agents, builds the evaluation baseline, and applies routing, caching, context reduction, batching and budgets one change at a time. By default we gate every change on your evaluation set so quality holds. If you are still planning an agent, we can build these controls in from the start. Projects are scoped and quoted after a 30-minute call.
Frequently asked questions
Why does the same agent cost different amounts for similar tasks?
Because the agent decides its own path. The number of steps, the size of tool results carried in context, retries after errors and occasional loops all vary by task. That is why you should track the distribution of cost per task, including high percentiles, rather than an average.
What is prompt caching and how do I benefit from it?
Prompt caching lets a provider reuse the processed form of a repeated prompt prefix, so repeated leading content is billed at a reduced rate and processed faster. To benefit, place stable content such as tool definitions and the system prompt first, keep it identical across requests, and put changing content at the end. Check the cached-token fields in usage data to confirm it is working.
Will a smaller model hurt quality?
Sometimes. That is why every switch should be tested on an evaluation set built from real tasks, with results compared against the current setup. Small models often do well on narrow steps such as classification or extraction, while complex planning may still need a larger model. Routing lets you use both.
How do we stop agent loops?
Enforce limits outside the model: maximum steps, tool calls, tokens and time per run, retry caps with backoff, and detection of repeated identical tool calls. Make tools return short, actionable errors. Decide in advance what happens at a limit: stop, return a partial result or hand off to a person.
Can we forecast AI agent spend?
Yes, once you measure cost per successful task per workflow and know expected task volumes. Forecasts improve when budgets cap the tail, when model versions are pinned, and when changes pass an evaluation that reports cost. Re-forecast whenever you change models, prompts or routing.
Should we self-host models to control costs?
It can help when volume is high and steady enough to keep hardware well used, or when data must stay in your environment. It replaces per-token billing with capacity you must manage, including GPUs, serving, scaling and upgrades. For uneven or low volume, hosted APIs with routing and caching are often simpler.
Why does this guide give no figures?
Provider rates, cache discounts and model line-ups change frequently and differ by provider and region, so any number would soon be out of date. The methods here apply regardless. Use your provider's current documentation and your own measurements to size savings.