On this page
AI agent costs are driven mostly by how many tokens each run consumes, and agents consume far more than single prompts because they resend a growing context on every step. To control them, measure cost per successful task, put hard budgets on every run, route easy work to smaller models, use prompt caching, and keep context lean. Most savings come from architecture decisions, not from negotiating a better rate.
Key takeaways
- The metric that matters is cost per successful task. Cheaper runs that fail more often can cost more in total.
- Agent costs grow faster than step count: each model call resends the accumulated history, so a long run’s input tokens compound.
- Enforce hard limits per run (steps, tokens, and spend) in code, not in the prompt.
- The biggest levers are usually workflow-vs-agent design, model routing, prompt caching, and trimming tool outputs.
- Attribute cost to tenants, features, and agent versions through tracing, so you can see which change caused a jump.
Why agents cost more than you expect
A chatbot answering one question makes one model call. An agent working through a task makes many, and each call carries everything that came before it.
Consider an agent that runs for ten steps. On step one, the model sees the system prompt, tool definitions, and the user’s request. On step two, it sees all of that plus the first response and the first tool result. By step ten, the model is reprocessing nine steps of history, every retrieved document, and every tool output to decide one more action.
Rough arithmetic makes the point. Suppose the fixed prefix (system prompt plus tool schemas) is 4,000 tokens and each step adds 1,500 tokens of reasoning and tool output. The input tokens across ten calls are:
step 1: 4,000
step 2: 5,500
step 3: 7,000
...
step 10: 17,500
total input ≈ 107,500 tokens for one run
That is roughly 27 times the size of the prefix, for a run that never felt long to the user. Double the per-step output, by returning a full JSON record instead of three fields, and the total climbs sharply. This compounding is why context size and step count are the two numbers to watch first.
Output tokens are usually priced higher than input tokens, and extended reasoning modes can add many output tokens per call. Check your provider’s current pricing, since rates and discount structures change often.
Measure the right thing: cost per successful task
Cost per run is easy to compute and easy to misread. A more useful unit is:
cost per successful task = total spend across all runs / number of runs that met the success criteria
This captures retries, failures, and escalations. It also prevents a common mistake: switching to a cheaper model, watching cost per run fall, and missing that success rate fell more. If the cheaper configuration fails twice as often and each failure gets retried or handed to a person, you may have saved nothing.
Include the cost of human handling where an agent escalates. An agent that resolves most cases cheaply but sends hard ones to a specialist has a blended cost, and that blended number is what belongs in an ROI model. Our ROI framework for AI agents and ROI calculator show how to build that view.
You can only compute this if success is defined and measured, which is one more reason to build an eval suite early. See how to evaluate AI agents.
The cost levers, ranked by typical impact
Not all optimizations are equal. The table below orders common levers roughly by how much they tend to matter, though the right order depends on your workload.
| Lever | What it does | Trade-off |
|---|---|---|
| Use a workflow instead of an agent where possible | Replaces open-ended loops with fixed, predictable steps | Less flexibility for unusual inputs |
| Model routing | Sends simple steps to smaller, cheaper models | Needs evals to confirm quality holds |
| Prompt caching | Reuses the processed stable prefix across calls | Prefix must stay byte-identical; cache entries expire |
| Trim tool outputs | Returns only the fields the model needs | Requires tool redesign |
| Context compaction | Summarizes or drops old turns in long runs | Risk of losing a detail needed later |
| Hard run budgets | Caps steps, tokens, and spend per run | Some legitimate long runs get cut off |
| Batch processing | Uses discounted asynchronous APIs for non-urgent work | Results arrive later, not in real time |
| Semantic or exact response caching | Skips the model for repeated questions | Stale answers if source data changes |
Start with architecture
The cheapest model call is the one you don’t make. Many tasks described as “agentic” are really a fixed sequence: classify, retrieve, draft, check. Running that as a workflow with a few targeted model calls costs a fraction of letting an agent decide each step. Anthropic’s Building effective agents makes the same recommendation: start with the simplest pattern that works. Our post on workflows vs. agents walks through the patterns.
Route by difficulty
Within an agent, steps differ in difficulty. Choosing which tool to call next, extracting a field from a document, or classifying intent often works well on a small model. Planning a multi-step fix or writing a nuanced customer reply may need a larger one.
Two routing patterns hold up in practice:
- Static routing by step type. Assign models per node in your workflow. Simple and predictable.
- Escalating routing. Try the small model first, validate the output (schema check, confidence, or a verifier), and fall back to the larger model only on failure.
Validate any routing change against your eval suite. Quality drops from routing often show up only on harder cases.
Make prompt caching work for you
Most major model providers offer prompt caching, which discounts input tokens for a prefix that matches a recent request. For agents, this can matter a lot, since the system prompt and tool definitions repeat on every step.
Caching only works if the prefix is stable. Common ways teams break it without noticing:
- Putting a timestamp, request ID, or user name at the top of the system prompt.
- Reordering tool definitions between calls.
- Injecting retrieved documents before the stable instructions instead of after.
Structure prompts as: stable instructions and tool schemas first, then slowly changing context (user profile, session memory), then the per-step content last. Check your provider’s documentation for minimum cacheable lengths, how cache entries expire, and whether caching is automatic or needs explicit markers.
Shrink what tools return
Tool outputs are often the largest source of context growth. A get_customer tool that returns a 200-field record when the agent needs five fields wastes tokens on every subsequent step of the run, because that record stays in history.
Design tools to return compact, purpose-built responses, support pagination and filtering, and truncate long text with a clear marker so the model knows more exists. Our guide to tool design for AI agents covers this in depth.
Enforce budgets in code
Instructions like “be efficient” in a system prompt do not limit spend. Hard limits have to live in the orchestration layer. Below is a TypeScript budget guard that wraps every model call in a run.
type ModelPricing = {
inputPerMTok: number; // USD per million input tokens
cachedInputPerMTok: number; // USD per million cache-read input tokens
outputPerMTok: number; // USD per million output tokens
};
// Load from config. Never hard-code provider prices, they change.
type PricingTable = Record<string, ModelPricing>;
type Usage = {
inputTokens: number; // uncached input tokens
cachedInputTokens: number; // input tokens served from cache
outputTokens: number;
};
export class BudgetExceededError extends Error {
constructor(
public readonly limit: "steps" | "tokens" | "spend",
message: string,
) {
super(message);
this.name = "BudgetExceededError";
}
}
export class RunBudget {
private steps = 0;
private totalTokens = 0;
private spendUsd = 0;
constructor(
private readonly pricing: PricingTable,
private readonly limits: { maxSteps: number; maxTokens: number; maxSpendUsd: number },
) {}
/** Call before each model request. */
checkBeforeCall(): void {
if (this.steps >= this.limits.maxSteps) {
throw new BudgetExceededError("steps", `Step limit of ${this.limits.maxSteps} reached`);
}
if (this.totalTokens >= this.limits.maxTokens) {
throw new BudgetExceededError("tokens", `Token limit of ${this.limits.maxTokens} reached`);
}
if (this.spendUsd >= this.limits.maxSpendUsd) {
throw new BudgetExceededError("spend", `Spend limit of $${this.limits.maxSpendUsd} reached`);
}
}
/** Call after each model response with the usage the provider reports. */
record(model: string, usage: Usage): void {
const price = this.pricing[model];
if (!price) throw new Error(`No pricing configured for model "${model}"`);
this.steps += 1;
this.totalTokens += usage.inputTokens + usage.cachedInputTokens + usage.outputTokens;
this.spendUsd +=
(usage.inputTokens * price.inputPerMTok +
usage.cachedInputTokens * price.cachedInputPerMTok +
usage.outputTokens * price.outputPerMTok) /
1_000_000;
}
snapshot() {
return { steps: this.steps, totalTokens: this.totalTokens, spendUsd: this.spendUsd };
}
}
And how it fits into the loop:
async function runAgent(task: string, deps: AgentDeps): Promise<AgentResult> {
const budget = new RunBudget(deps.pricing, {
maxSteps: 15,
maxTokens: 250_000,
maxSpendUsd: 0.75,
});
const messages: Message[] = [{ role: "user", content: task }];
try {
while (true) {
budget.checkBeforeCall();
const model = deps.router.pick(messages); // small model by default, large when needed
const response = await deps.llm.complete({ model, messages, tools: deps.tools });
budget.record(model, response.usage);
messages.push(response.message);
if (response.toolCalls.length === 0) {
return { status: "completed", output: response.text, cost: budget.snapshot() };
}
for (const call of response.toolCalls) {
const result = await deps.tools.invoke(call);
// Cap tool output size so one large result can't bloat every later step.
messages.push(toolMessage(call.id, truncate(result, 6_000)));
}
}
} catch (err) {
if (err instanceof BudgetExceededError) {
await deps.escalate(task, messages, err.limit);
return { status: "escalated", reason: err.limit, cost: budget.snapshot() };
}
throw err;
}
}
The important behavior is what happens at the limit. The run doesn’t crash or silently stop. It escalates to a person with the full context and records why. Budget exhaustion becomes a measurable stop reason, and a rising rate of it tells you something changed. For the escalation pattern itself, see human-in-the-loop agent design.
Set per-run limits from observed data. Look at the distribution of steps and spend for successful runs in your evals and early production traffic, and set the cap comfortably above the high end of that range. Add per-tenant and per-day limits on top, so one runaway integration or abusive user can’t exhaust the monthly budget. The OWASP Top 10 for LLM Applications lists unbounded consumption as a distinct risk for this reason.
Context compaction for long-running agents
Some agents legitimately run for many steps: research tasks, coding agents, long support conversations. For these, compaction keeps costs bounded:
- Summarize older turns into a short running summary once history passes a threshold, and keep recent turns verbatim.
- Drop stale tool results after the agent has acted on them, keeping a one-line note of what was learned.
- Move durable facts to memory that is retrieved when relevant, rather than carried in every call.
Compaction can drop a detail the agent needs later, so test it on your longest eval cases. Our posts on context engineering and agent memory cover the techniques.
Make cost visible
You can’t manage what you can’t attribute. Record token usage and computed cost on every model call span, and roll it up to the run, with tags for tenant, feature, agent version, and model. Then you can answer the questions that come up in every cost review:
- Which feature or customer drives the most spend?
- Did last week’s prompt change increase average steps per run?
- What share of spend goes to runs that ultimately failed or escalated?
- How much of our input is being served from cache?
Our guide to observability for AI agents shows how to capture these attributes with OpenTelemetry.
FAQ
What drives the cost of an AI agent?
Mostly token volume: input tokens resent on every step plus output tokens generated, multiplied by the number of steps. Long tool outputs, large system prompts, and runs that loop or retry are the usual culprits. Infrastructure and tool API costs exist but are typically smaller than model spend.
Is it cheaper to use a smaller model for agents?
Per call, yes. Per successful task, not always. A smaller model that needs more steps or fails more often can cost more overall. Route by step difficulty and confirm with evals that success rate holds.
How do I set a budget for each agent run?
Measure steps, tokens, and spend for successful runs in your eval suite and early traffic, then set hard caps above the normal range. Enforce them in the orchestration code, and escalate to a human when a run hits the limit rather than failing silently.
Does prompt caching work with agents?
Yes, and agents benefit more than most workloads because the system prompt and tool definitions repeat on every step. Keep the stable prefix identical across calls and place variable content at the end. Check your provider’s documentation for cache lifetimes and minimum lengths.
Working with TechnoKeen
TechnoKeen designs agents with cost controls built in: routing, caching, budgets, and per-tenant attribution. If your agent bill is growing faster than its value, get in touch and we’ll help you find where the tokens are going.
- #AI agent costs
- #LLM cost optimization
- #token budgets
- #model routing
TechnoKeen Engineering
TechnoKeen is an enterprise agentic AI company. Our engineers design, deploy, and govern AI agents for organizations in regulated and complex industries, and share what we learn in the field.
About TechnoKeen →