Setting a Cost Budget per Agent Task
Engineering

Setting a Cost Budget per Agent Task

An agent loop grows its own context at every step; a budget written in code decides when it stops and what it hands over.

Short answer

A cost budget per agent task is the most one task may spend on model tokens, paid tools, steps and time before the agent must stop and hand it over. Set it per task class from measured runs, where the success curve flattens, enforce it in the orchestrator and tool gateway rather than the prompt, and stop with a status report and a checkpoint.

What is a cost budget per agent task?

A cost budget per agent task is the most an agent may spend on one task (model tokens, paid tool calls, steps and time) before it must stop and hand the task over. It is set per task class, because a routine order-status question and a complex shipping dispute are worth different amounts, and it is enforced in the code around the model, not requested in the prompt. Without it, a single confused run can cost more than the answer is worth, and a malicious input can turn that into a repeatable attack.

The budget is not just a ceiling on the bill. It is a product decision about when the agent should give up, what it hands to a person, and how much you are willing to pay for each extra task it solves.

Why do agent costs get out of hand?

Because an agent is a loop, and every turn of the loop sends the conversation so far back to the model. The OpenAI Agents SDK documentation describes the agent loop plainly: call the model with the current input; if it produces tool calls, run them, append the results and run the loop again; stop when the output is final. Each tool result makes the next call larger, so a task that takes twice as many steps usually costs more than twice as much.

Three patterns cause most overruns: retry loops where the agent repeats the same search with slightly different wording, large tool outputs (a whole document, a long table) pasted into the context and carried through every later step, and paid external APIs called once per step. OWASP calls the abuse version of this "Denial of Wallet". Its entry on unbounded consumption describes attackers exploiting the cost-per-use model of AI services, and lists rate limiting, user quotas, timeouts and monitoring of resource use as mitigations. Framework defaults do not solve this: in current LangGraph versions the default recursion limit is 1,000 super-steps, a guard against infinite loops rather than a cost budget.

What should the budget include?

Count everything a task consumes, and divide by successful tasks, not by attempts:

  • Model input and output tokens for every step, including retries and failed runs.
  • Cached input at its own price. Anthropic's prompt caching documentation, for example, prices cache reads at 0.1 times the base input price and cache writes at 1.25 times (five-minute cache) or 2 times (one-hour cache), and reports cached tokens in separate usage fields. Caching lowers the cost of a repeated prefix; it does not remove the need for a limit.
  • Paid tools: search APIs, document conversion, data providers, per-call fees.
  • Infrastructure time for long-running steps or sandboxes.
  • Human time for reviewing the result and for handling the tasks the agent hands over.

The figure that matters is cost per successful task: total spend on a class of tasks, including the runs that failed, divided by the number of tasks solved correctly.

How do you set the limit?

Set it from measurements, not from a guess. Anthropic's guide to evaluating AI agents tracks the number of turns, tool calls and total tokens alongside task success; run your held-out tasks the same way and look at the distribution for each task class. Successful runs usually cluster at a low step count, and a tail of long runs adds cost without adding successes. Put the limit where the success curve flattens, then check what the extra spend buys between candidate limits. Write the result down as a stop-rule specification:

Stop ruleExample value for a routine taskWhat happens when it triggers
Maximum model steps12Stop, return a status report, hand over
Warning threshold80 percent of any limitTell the agent what remains and ask it to finish or hand over
Same tool with the same arguments2 callsTreat as a loop; stop that path
Quota per paid tool3 search callsRemove the tool for the rest of the task
Total input tokensSet from the measured distributionStop and hand over
Wall-clock time5 minutesSave a checkpoint and hand over
External spendA fixed amount per taskAsk a person to approve before continuing

The values above are illustrative; yours come from your own measurements. Use narrower limits for requests from unauthenticated users or low-value task classes, and keep a separate, larger budget for task classes that a person has explicitly approved.

Where should the limits be enforced?

In the orchestrator and the tool gateway, where the model cannot negotiate with them. The OpenAI Agents SDK raises a MaxTurnsExceeded exception when the turn limit is passed, or, through an error handler, returns a controlled final output instead of an error. LangGraph raises GraphRecursionError at its limit and offers a remaining-steps value so the graph can route to a fallback before the hard stop. Neither counts money, so put spend and per-tool quotas in the gateway that executes tool calls, and keep provider-level spending limits as a backstop. OWASP's AI agent security cheat sheet lists token, cost, retry and tool-chain limits among its controls and recommends tracking token usage and cost per session and per user. One rule has no exceptions: the model cannot approve its own budget extension because it claims the next call will solve the task. Extensions come from a person or from a rule written in code.

What should happen when the budget runs out?

The agent stops cleanly and leaves the task in a state someone else can pick up. Return a short status: what was verified, what remains uncertain, which actions were taken and the next safe step. Save a checkpoint without unnecessary personal data so a person or a separately approved run can continue. Never report a partly finished task as a success. If a write action, such as creating an order or sending a message, is in an unknown state, check its real state before stopping or restarting; a budget stop must not create a duplicate transaction or hide a half-finished one from the user. Tell the user plainly that the task has been handed over and what happens next.

How do sub-agents and retries share the budget?

The budget belongs to the task, not to each model call or each agent. When an orchestrator delegates parts of a task to sub-agents, give each one a slice of the parent budget and count its spend against the same total; otherwise three sub-agents with "their own" limits can spend three times what the task is worth. Retries after a timeout or a tool error draw from the same budget, and before retrying a write action the agent must check whether the first attempt succeeded. Record the budget used, the limit that stopped the run and the task class in every trace, so that reviews of expensive runs start from data rather than from the invoice.

Hypothetical example: choosing a step limit for order-status questions

All figures here are hypothetical, and the prices are illustrative, not any provider's list price: input at $3 and output at $15 per million tokens, with no caching. Each step starts from a 6,000-token system prompt and tool definitions, adds about 1,500 tokens of history, and writes about 300 tokens. A 4-step run then uses about 33,000 input tokens and costs about $0.12. A 25-step run uses about 600,000 input tokens and costs about $1.91: six times the steps, sixteen times the cost.

A held-out set of 200 routine questions gives this pattern: 182 are solved within 6 steps (4 on average), 6 more need 7 to 12 steps, 4 stop early because the customer gave no order number, and 8 loop without solving. Compare three limits:

Step limitSolvedHanded overSpend for 200 tasksSpend per solved task
618218$24.45$0.134
1218812$28.34$0.151
2518812$39.11$0.208

Raising the limit from 12 to 25 adds 38 percent to the spend and solves nothing more. Raising it from 6 to 12 solves 6 more tasks for about $0.65 each, which is worth it if a person handling the same question costs more. A loop detector (the same search twice) would stop the 8 looping runs well before 12 steps and lower the spend further.

How do you keep the limits right over time?

Monitor the distribution of steps, tokens and spend per task class in production, and alert on sudden changes per user or per tenant. Re-run the held-out set at several budget levels whenever the model, prompt, tool set or prices change, because a cheaper model that needs more steps can cost more per solved task. Review the handed-over tasks every week: if many of them stop just short of the limit, the limit may be too tight; if most of them are loops, fix the loop rather than raising the limit.

Common mistakes

  • Asking the model in the prompt to "keep costs low" instead of enforcing limits in code.
  • Relying on a framework's default step limit as a cost budget.
  • Measuring cost per attempt instead of cost per successful task.
  • Letting large tool outputs ride along in the context for every later step.
  • Stopping at the limit without a status report, a checkpoint or a check of unfinished write actions.

Cost and step limits are built together with the prototype, alongside approval steps and action logs, on our AI agent development service. To lower the cost of each step itself, see our guide to model routing.

Key takeaways

  • Budget per task class and measure cost per successful task, failed runs included.
  • Count tokens (cached ones at their own price), paid tool calls, infrastructure time and human review.
  • Set limits where the success curve flattens on held-out tasks, and check what each extra step of budget buys.
  • Enforce step, loop, per-tool, token, time and spend limits in the orchestrator and tool gateway; the model never extends its own budget.
  • At the limit, return a status report and a checkpoint, and reconcile any write action left in an unknown state.

Frequently asked questions

How do you calculate the cost of an AI agent task?

Add every model call's input and output tokens at their prices, with cached tokens at their own rate, plus paid tool calls, infrastructure time and human review. Divide the total for a task class, failed runs included, by the number of tasks solved correctly to get the cost per successful task.

Why does an agent cost more than a single LLM call?

Because it runs in a loop and sends the growing conversation back to the model at every step, with tool results appended. Cost therefore grows faster than the number of steps, and retries or large tool outputs multiply it.

Is a framework's max-turns or recursion limit enough?

No. Limits such as max_turns in the OpenAI Agents SDK or LangGraph's recursion limit count steps, not money, and LangGraph's default is 1,000 super-steps. Add per-tool quotas and token and spend limits in the tool gateway, with provider-level spending caps as a backstop.

Should the agent know its remaining budget?

Yes, as information: telling the agent what remains at a warning threshold helps it finish or hand over in time. The limit itself must still be enforced in code, and the model must never be able to grant itself an extension.

What should an agent return when it hits the limit?

A short status report covering what was verified, what is uncertain, which actions were taken and the next safe step, plus a checkpoint a person can continue from. Any write action in an unknown state must be checked before stopping or restarting.

All articles