AI Agents

Controlling AI Agent Costs in Production Workloads

Learn how to control production AI agent costs by fixing retry loops and redundant tool calls — not by switching to a cheaper model. Practical patterns inside.

By Laxaar Engineering Team Nov 27, 2026 10 min read
Controlling AI Agent Costs in Production Workloads

Production AI agents have a billing problem that most engineering teams discover the hard way: a workflow that costs $0.03 in a demo quietly costs $3.80 in production. The culprit is almost never the system prompt. It's retry loops that spiral when a tool returns an unexpected shape, redundant calls to the same lookup tool within a single task, and unbounded context windows that grow with every turn. Switching to a cheaper model shaves maybe 20% off that bill. Fixing the loops and caps can cut it by 90%.

We've seen this pattern across dozens of agentic projects at Laxaar. Teams obsess over per-token pricing tables, run benchmarks on smaller models, and still watch their invoices climb. The real leverage is in agent architecture, not model selection. Cost is a product of how many tokens you generate, and that's driven almost entirely by how many times your agent retries, how much context it drags along, and how many tool round-trips it makes per task.

This guide documents the specific controls we apply to production AI agents before any deployment leaves staging.

What you'll learn

Why agent costs spiral in production

The token costs for a single agent run are predictable. The token costs for a thousand concurrent agent runs with real users, real edge cases, and real failures are not. Not unless you've designed for it.

Here's what happens at scale. An agent hits a tool that returns a null field it didn't expect. It retries. The retry fails for a different reason. It retries again, this time with more context in the prompt to explain what went wrong. Each retry carries the full conversation history plus the failed output of the previous attempt. By the fourth retry you've generated 6x the tokens of a successful run, and that's before the agent decides to call a second tool to investigate the original failure.

Retry amplification is the single biggest cost driver we see. A 2% failure rate on tool calls with uncapped retries can account for 30–40% of total token spend once you model the compounding. This isn't a model problem. A smarter model doesn't make your tools more reliable.

The second driver is context bloat. Many agent frameworks append every observation and tool result to the running context. An agent doing 12 tool calls in a workflow with verbose JSON responses can accumulate 40,000 input tokens by the final step even if the actual task could have been completed with 3,000.

Token budget enforcement per task

A token budget is a hard cap on the total tokens an agent may spend completing a single task instance. It's the most direct cost control available, and it's underused because setting it requires knowing what a normal run costs. That means you need observability first (more on that below).

Set budgets at the task level, not the model level. A document summarization task and a multi-step data enrichment task should have different budgets. The summarization task might cap at 8,000 tokens. The enrichment task might cap at 40,000. When a run exceeds its budget, the agent should return a partial result and a budget_exceeded status rather than continuing silently.

class TaskBudget:
    def __init__(self, max_input_tokens: int, max_output_tokens: int):
        self.max_input = max_input_tokens
        self.max_output = max_output_tokens
        self.input_used = 0
        self.output_used = 0

    def check(self, input_tokens: int, output_tokens: int) -> bool:
        self.input_used += input_tokens
        self.output_used += output_tokens
        return (
            self.input_used <= self.max_input
            and self.output_used <= self.max_output
        )

    @property
    def exceeded(self) -> bool:
        return (
            self.input_used > self.max_input
            or self.output_used > self.max_output
        )

This isn't a UX nicety. It's a financial control. Treat it as such: alert when tasks routinely hit 80% of budget, and treat budget exhaustion as a signal to investigate the underlying tool or prompt, not to raise the cap.

Stopping retry loops before they compound

Retry logic is necessary. Uncapped retry logic is expensive. The fix is a retry policy with three properties: a maximum attempt count, exponential backoff with jitter, and a classification of which errors are even worth retrying.

Not all tool errors should trigger a retry. A 404 Not Found on a lookup endpoint means the data isn't there. Retrying won't fix that. A 429 Rate Limited response is worth retrying after a back-off. A malformed response from a third-party API might be worth one retry with a fallback schema. Classifying errors before the retry policy runs is the difference between resilience and cost amplification.

RETRYABLE_ERROR_CODES = {429, 503, 504}
MAX_ATTEMPTS = 3

async def call_tool_with_policy(tool_fn, *args, **kwargs):
    for attempt in range(MAX_ATTEMPTS):
        try:
            return await tool_fn(*args, **kwargs)
        except ToolError as e:
            if e.status_code not in RETRYABLE_ERROR_CODES:
                raise  # don't retry — fail fast
            if attempt == MAX_ATTEMPTS - 1:
                raise
            wait = (2 ** attempt) + random.uniform(0, 1)
            await asyncio.sleep(wait)

The opinionated take: most teams should set MAX_ATTEMPTS to 3 and treat anything higher as a sign they haven't fixed the underlying reliability problem. Four retries with full context propagation costs as much as four separate successful runs.

Deduplicating tool calls within a single run

Agents often call the same tool with the same arguments multiple times within a single task. This happens because the agent's context doesn't naturally surface "you already called this" as a constraint. A customer-profile lookup called once at step 2 and again at step 7 doubles that tool's cost contribution to the run.

A simple in-memory cache keyed on (tool_name, args_hash) within a single agent run eliminates most of this. The cache doesn't need to persist across runs; it just needs to live for the duration of one task execution.

import hashlib, json

class RunScopedToolCache:
    def __init__(self):
        self._cache: dict[str, any] = {}

    def key(self, tool_name: str, args: dict) -> str:
        payload = json.dumps({"tool": tool_name, "args": args}, sort_keys=True)
        return hashlib.sha256(payload.encode()).hexdigest()

    def get(self, tool_name: str, args: dict):
        return self._cache.get(self.key(tool_name, args))

    def set(self, tool_name: str, args: dict, result) -> None:
        self._cache[self.key(tool_name, args)] = result

This is particularly valuable for tools that hit external APIs with per-call pricing. Wrap every tool call through the cache before it leaves the agent runtime. At Laxaar we've seen this reduce tool-call token costs by 15–25% on workflows with more than six steps, without any change to agent logic or prompts.

Context window hygiene that cuts input tokens

Every token in the input context costs money on every LLM call. In multi-turn agent loops, context grows by default. You have to actively shrink it.

The patterns that deliver the most savings:

Summarize intermediate results. After a tool returns a large JSON response, extract only the fields the remaining steps need. A customer record with 40 fields where the next step only needs account_status and plan_tier should be trimmed before it enters the next prompt.

Drop observation history past a horizon. Keep the last N observations verbatim and replace older observations with a compressed summary. An agent that's made 10 tool calls doesn't need the full output of call 1 in the prompt for call 11.

Use structured context blocks, not raw conversation history. Passing a running transcript of every turn is the most expensive representation of agent state. A structured state object with named fields is both smaller and more reliable.

ApproachAvg input tokens at step 10Relative cost
Full transcript appended~42,0001.0x (baseline)
Last 3 turns + summary~12,0000.29x
Structured state object~6,5000.15x
Structured state + field trimming~3,2000.08x

These are real numbers from a 12-step data enrichment workflow. The difference between the baseline and the structured-plus-trimming approach is not a model switch. It's the same model, the same task, different context management.

Model routing by task complexity

Model routing is the right cost lever, but it works best after you've fixed the structural problems above. Routing to a cheaper model doesn't help if that model retries more often or produces outputs that cause downstream retries.

The routing rule we use at Laxaar: classify each step in the agent workflow by required reasoning depth, then assign model tier accordingly.

  • Tier 1 (cheapest): Extraction, classification, format conversion. No multi-step reasoning needed.
  • Tier 2 (mid-range): Tool selection, conditional branching, short-horizon planning. Moderate reasoning.
  • Tier 3 (most capable): Complex decomposition, ambiguous instructions, multi-constraint optimization.

Most production agent workflows have 60–70% of steps in Tier 1. Routing those to a smaller model while reserving the capable model for Tier 3 steps cuts the effective cost per run by 40–60% without meaningfully affecting output quality on those tasks.

The trade-off to acknowledge honestly: multi-model routing adds operational complexity. You now have two or three model dependencies, potentially different rate limits, and you need evals per tier to verify quality doesn't degrade on Tier 1 routing before you ship it.

Observability you need before you can optimize

None of the above optimizations work without per-task cost visibility. You can't set a budget without knowing what a normal run costs. You can't identify retry spirals without trace-level data. You can't find redundant tool calls without a log of every call per run.

At minimum, instrument the following:

  • Total input and output tokens per task run, not per LLM call. Aggregate to the task level.
  • Tool call count and latency per run. Flag runs where the same tool is called more than twice.
  • Retry count and error classification per tool. A heatmap of which tools cause retries surfaces your real reliability problems.
  • Cost per successful completion vs cost per failed/partial run. This ratio tells you how much you're spending to not get value.

Our AI agent development practice treats this observability layer as non-negotiable before any agent goes to production. You can explore our broader AI automation services if you're evaluating how to instrument agents you're building in-house.

If you're starting from scratch with agent tooling, the ai-agent-development hiring and build decisions get cleaner once you've instrumented a production run and seen where your actual spend goes.

Frequently Asked Questions

Does switching to a cheaper model meaningfully reduce agent costs?

It helps at the margins, but the structural multipliers (retry loops, context bloat, redundant tool calls) generate far more cost variance than the per-token rate difference between models. Fix those first. A well-structured agent on an expensive model is almost always cheaper per task than a poorly-structured agent on a cheap model.

What's a reasonable token budget to start with for a new agent task?

Run 50–100 representative task instances in staging with no budget cap and observe the p50 and p95 token counts. Set your production budget at 2x the p95. That gives you headroom for real-world variance while still catching runaway runs. Revisit the budget after the first two weeks in production.

How do we handle agents that legitimately need many tool calls?

Some workflows genuinely require many tool calls. That's fine. The goal isn't to minimize tool calls but to eliminate redundant ones. Use the run-scoped cache for repeated calls, and if a workflow design calls for 15 sequential tool calls, consider whether any of those can be parallelized or batched to reduce the number of LLM turns.

Can we apply these patterns to agents built on third-party frameworks like LangGraph or CrewAI?

Yes, with some wrapping. Token budget enforcement and tool caching are best applied at the framework boundary rather than inside it. Wrap the LLM client to count tokens, and wrap the tool registry to check the cache before dispatch. Most frameworks expose these integration points. The retry policy is trickier if the framework owns the retry logic. You may need to disable the built-in retry and implement your own.

What percentage of agent spend typically comes from failed runs?

In our experience across production deployments, failed and partial runs account for 20–45% of total token spend on agents without explicit retry caps and error classification. That range is wide because it depends heavily on the reliability of the underlying tools. The more third-party APIs an agent calls, the higher this proportion tends to be.


Production AI agent costs don't spiral because of bad model choices. They spiral because nobody put a cap on retries, nobody trimmed the context, and nobody cached the lookup that gets called five times per run. Fix those things first. The per-token rate is the last dial worth touching.

If you're designing a new agentic system or trying to bring an existing one under budget, the Laxaar team is ready to help. We can audit your current agent architecture, find where spend is leaking, and get the controls in place that actually move the number.

Working on something like this?

Get a fixed scope, timeline, and price within one business day — no obligation.

AI AgentsLLM Cost OptimizationProduction AI
Grow your business with us

Take your business to the next level.

Tell us what you're building. We'll come back inside one business day with a fixed scope, timeline, and team — or an honest “this isn't a fit”.

ENGINEERING PHILOSOPHY

Code is useless if it's not comprehensible to those who maintain it. We write code the next person can actually understand.