Cost Management for Agents
“Intelligence is cheap. Reliable, scalable intelligence is expensive.”
TL;DR
An agent running on a frontier model can cost millions per year at scale. Control costs with four architectural primitives: model routing (send simple tasks to cheap models), semantic caching (return cached responses for similar queries without an LLM call), budget enforcement (per-user and per-feature spending limits), and circuit breakers (hard step limits to prevent runaway loops). The key insight is that, for many agent tasks, a cheap model that is good enough beats a frontier model that is slightly better at many times the price. For the token-level optimization that feeds into cost control, see Token Efficiency Optimization, and for monitoring spend in production, see Observability and Tracing.

1. Introduction
When you move from a “Demo” (10 queries/day) to “Production” (10M queries/day), the economics of AI Agents shift dramatically. For illustration, assume an agent on a frontier model running a ReAct loop (Reason+Act) costs $0.30 per task. If you have 10,000 active users doing 5 tasks a day, your daily bill is $15,000 (about $5.5M/year).
Cost Management is not just about “switching to cheaper models”. It involves architecting systems that are financially aware, using routing, caching, and budget enforcement as core primitives.
2. Core Concepts: The Token Economy
To optimize cost, we must understand the billing unit.
- Input Tokens: Cheaper. (Reading context).
- Output Tokens: 3x-10x More Expensive. (Generation).
- Frequency: Agents are “chatty”. A single user “task” might involve 10 back-and-forth LLM calls (Thought -> Tool -> Observation -> Thought…).
The Formula:
Cost = (Input_Vol * Input_Rate) + (Output_Vol * Output_Rate) + (Tool_Compute_Cost)
Optimization targets the Frequency (fewer calls) and the Rate (cheaper models).
3. Architecture Patterns: The Cost Gateway
We shouldn’t hardcode API keys in our agent code. We need a Model Gateway (like LiteLLM or Helicone).
[Agent Logic] -> [Cost Gateway] -> [Provider (OpenAI/Anthropic)]
|
+-------+-----------+
| |
[Budget Check] [Semantic Cache]
(Stop if over) (Return cached)
The Router Pattern: The Gateway inspects the prompt.
- Tier 1 (Complex): “Write a legal contract” -> Route to a frontier model.
- Tier 2 (Simple): “Extract the date from this string” -> Route to a small model (the “mini”, “Flash” or “Haiku” tier of each provider).
4. Implementation Approaches
4.1 Semantic Caching
Exact string matching (Redis) rarely hits on free-form text: “How are you?” != “How are you doing?”. Semantic Caching uses Embeddings.
- Embed query:
vec = embed("How are you?") - Search Vector DB for neighbors.
- If distance is below a strict threshold (e.g., cosine distance < 0.1, tuned on your data), return the cached response.
4.2 Waterfall Routing / Fallbacks
Try the cheapest model first. If it fails (or returns low confidence/bad format), retry with the expensive model.
5. Code Examples: The Budget-Aware Router
from openai import OpenAI
# $ per 1M tokens (OpenAI list prices for GPT-4.1 at its April 2025 launch;
# check the current price page before relying on them)
PRICING = {
"gpt-4.1": {"input": 2.00, "output": 8.00},
"gpt-4.1-mini": {"input": 0.40, "output": 1.60},
}
class BudgetExceeded(Exception):
pass
class CostRouter:
def __init__(self, client, budget_limit=5.0):
self.client = client
self.total_spend = 0.0
self.budget_limit = budget_limit
def cost(self, model, input_tokens, output_tokens):
rate = PRICING[model]
return (input_tokens * rate["input"] + output_tokens * rate["output"]) / 1_000_000
def route(self, prompt, complexity="low", max_output_tokens=500):
# 1. Model selection
model = "gpt-4.1" if complexity == "high" or len(prompt) > 8000 else "gpt-4.1-mini"
# 2. Budget check against a worst-case estimate (~4 characters per token)
estimate = self.cost(model, len(prompt) // 4, max_output_tokens)
if self.total_spend + estimate > self.budget_limit:
raise BudgetExceeded(f"Spent ${self.total_spend:.4f}; next call could cost ${estimate:.4f}")
# 3. Execution
response = self.client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": prompt}],
max_tokens=max_output_tokens,
)
# 4. Accounting: true up with the real usage, input and output priced separately
usage = response.usage
self.total_spend += self.cost(model, usage.prompt_tokens, usage.completion_tokens)
return response
router = CostRouter(OpenAI(), budget_limit=10.0)
# Simple query -> cheap model
router.route("What is 2+2?", complexity="low")
# Hard query -> expensive model
router.route("Draft a patent claim for...", complexity="high")
6. Production Considerations
6.1 The “Agent Loop” Trap
An agent gets stuck in a loop:
- Thought: “I need to search Google.”
- Action: Search “Python”.
- Observation: “Python is a snake.”
- Thought: “That’s not code. I need to search Google.”
- Action: Search “Python”. … System Design Fix: Implement a Max Steps Circuit Breaker. Hard limit of 10 steps. If not solved, return “I failed” rather than burning $100.
6.2 FinOps Tagging
Every request should have metadata: {"user_id": "123", "feature": "email_writer"}.
This allows you to answer: “Is the Email Writer feature profitable?”
7. Common Pitfalls
- Summarization Recursion: You summarize history to save tokens. But resizing the summary costs tokens. Sometimes summarization costs more than just reading the raw logs if the thread is short.
- Over-Caching: Caching “Write me a poem about X” is bad (User wants variety). Caching “What is the capital of X?” is good.
- Fix: Only cache deterministic queries.
8. Best Practices
- Usage-Based Throttling: Rate limit users not just by Request Count, but by Dollar Amount. “You have $1.00 credit per day.”
- Separation of Concerns: Don’t ask the “Planner” (a frontier model) to do the “Extraction” (JSON formatting). Extract with a small model or a regex.
9. Connections to Other Topics
- Token Efficiency Optimization: cutting the tokens behind every call.
- Observability and Tracing: cost per trace and per feature, so you know where money goes.
- Error Handling and Recovery: circuit breakers and bounded retries.
10. Real-World Examples
- Model gateways: Open-source and hosted gateways such as LiteLLM and OpenRouter expose routing, fallbacks and per-key spend limits as configuration, so you rarely need to build this layer from scratch.
- Learned routers: RouteLLM (Ong et al., 2024) trains a router on preference data to decide when a query needs the strong model, and reports cutting cost by more than 2x in some settings while keeping response quality.
11. Future Directions
- Speculative Decoding: Using a small model to “guess” the next few tokens, and the large model to “verify” them in parallel. Mostly a latency win; on self-hosted models it can also make better use of the GPU at low batch sizes.
- Local-First Agents: Running a small open model on the user’s own device, falling back to a cloud frontier model only when stuck.
12. Key Takeaways
- Routing is ROI: For many tasks, a cheap model that is good enough beats a frontier model that is slightly better at many times the price. Measure the quality gap on your own evals.
- Cache Deliberately: Semantic caching turns repeated questions into fast, near-free responses, as long as you only cache deterministic queries.
- Circuit Breakers: Never let an agent run
while(true).
For latency rather than cost, see Streaming and Real-Time Agents.
FAQ
How much do AI agents cost to run in production?
For illustration, assume an agent on a frontier model running a ReAct loop costs $0.30 per task. At 10,000 active users doing 5 tasks per day, that is $15,000 daily, or about $5.5 million per year. The cost comes from three components: input tokens (reading context), output tokens (generation, which is 3-10x more expensive), and frequency (a single user task may involve 10 or more LLM calls in the reasoning loop).
What is model routing for cost optimization?
Model routing inspects each prompt and routes it to the cheapest model that can handle the required complexity. Simple tasks like date extraction or formatting go to a small model at a fraction of the cost, while complex tasks like legal drafting or multi-step reasoning go to a frontier model. For many agent tasks this keeps most of the quality at a small fraction of the price.
How do circuit breakers prevent runaway AI agent costs?
Circuit breakers set a hard limit on the number of steps an agent can take per task, typically around 10. Without them, an agent stuck in a reasoning loop, repeatedly searching for the same thing or retrying a failing tool, can make dozens of expensive LLM calls on a single request. The circuit breaker forces the agent to return a failure message rather than burning through budget.
What is semantic caching and how does it save money?
Semantic caching embeds queries as vectors and searches for similar cached queries rather than requiring exact string matches. If a new query falls within a similarity threshold of a cached one, the stored response is returned without an LLM call. This is effective for deterministic queries like factual lookups but should not be used for creative tasks where users expect variety.