
Agentic AI Costs: How One Loop Burned ₹5,000 in 10 Minutes (And How to Prevent It)
AI agents can rack up massive API bills when they loop, retry, or process large context windows. Here's what goes wrong, real rupee numbers, and exactly how to cap spending before it happens.
Author
AICredits Team
Published
3 May 2026
Reading time
9 min read
The incident
A developer building a code-review agent left it running overnight to process a backlog of pull requests. The agent was instructed to: read each PR, think through the changes, write a review, and post it.
Simple enough. Except the PR list was fetched from an API that returned a cursor for pagination — and the agent misread the cursor as a signal to continue indefinitely. By morning it had processed the same 12 PRs 47 times each.
Bill: ₹4,980 in 10 hours.
This isn't an edge case. It's a near-universal experience for anyone building agents. The problem isn't the model — it's that agents are loops, and loops have no natural stopping point.
Why agents cost so much more than chatbots
A single chatbot exchange — one user message, one assistant reply — costs a predictable amount. An agent is different:
-
Every step includes the full conversation history. Token counts grow with each turn. A 10-step agent run with 1,000 tokens per step doesn't cost 10 × 1,000 = 10,000 tokens. It costs 1,000 + 2,000 + 3,000 + ... + 10,000 = 55,000 tokens due to context accumulation.
-
Agents retry on failure. A tool call that returns an error often causes the agent to try again — sometimes repeatedly. Each retry sends the full context again.
-
Agents explore. Unlike a chatbot that answers one question, an agent might take 3 different approaches to solve a problem, backtrack, and try again.
-
Agents run unattended. You're not there to notice when something goes wrong.
The real numbers
Let's make this concrete with Claude Sonnet 4 pricing on AICredits (₹274 per million input tokens, ₹1,370 per million output tokens):
| Scenario | Tokens per step | Steps | Total tokens | Cost (INR) | |---|---|---|---|---| | Simple chatbot | 500 in / 300 out | 1 | 800 | ₹0.15 | | 5-step agent | 2k in / 500 out avg | 5 | ~17,500 | ₹6.50 | | 20-step code agent | 8k in / 1k out avg | 20 | ~210,000 | ₹91 | | Runaway loop (47×) | 8k in / 1k out avg | 940 | ~9.8M | ₹4,980 |
The runaway scenario is 33,000× more expensive than a chatbot exchange. And it happened in 10 hours — not 10 months.
Claude Code sessions have similar dynamics: a complex refactoring task with large file context can easily hit 200,000 tokens per session, costing ₹80–150. That's fine for intentional use. But multiply by 10 parallel sessions, or leave one session in a loop overnight, and you're looking at a very bad morning.
Prevention strategy 1: Per-key budget caps (most important)
The single most effective protection is setting a hard spending limit on each API key. When the key hits its budget, requests return 402 Payment Required and the agent stops.
In AICredits: go to Dashboard → API Keys, create or edit a key, and set a Budget Limit.
The key insight is to use separate keys for separate purposes:
Production app key → ₹10,000/month budget
Development key → ₹500/month budget
Claude Code key → ₹2,000/month budget
Experiment / notebook → ₹200/month budget
A runaway agent on the development key can only spend ₹500 before it stops. Your production key is unaffected. This is the difference between a ₹500 surprise and a ₹50,000 one.
Prevention strategy 2: Max steps in your agent loop
Every agent loop should have an explicit step limit. Most frameworks support this; if yours doesn't, add it yourself:
import anthropic
client = anthropic.Anthropic(
base_url="https://api.aicredits.in",
api_key="sk-your-key",
)
MAX_STEPS = 15 # hard limit — never exceed this
def run_agent(initial_message: str) -> str:
messages = [{"role": "user", "content": initial_message}]
tools = [...] # your tool definitions
for step in range(MAX_STEPS):
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=4096,
tools=tools,
messages=messages,
)
if response.stop_reason == "end_turn":
# Agent is done naturally
return response.content[0].text
if response.stop_reason == "tool_use":
# Execute tools, append results, continue loop
tool_results = execute_tools(response.content)
messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": tool_results})
continue
# Unexpected stop reason — bail
break
# Hit the step limit
return f"[Agent stopped after {MAX_STEPS} steps to prevent runaway cost]"For LangChain and LangGraph, use the max_iterations parameter:
from langchain.agents import AgentExecutor
executor = AgentExecutor(
agent=agent,
tools=tools,
max_iterations=10, # hard step limit
max_execution_time=120, # hard time limit in seconds
early_stopping_method="generate",
)Prevention strategy 3: Token budget tracking
Track cumulative token usage across the agent run and stop if you exceed a threshold:
import anthropic
client = anthropic.Anthropic(
base_url="https://api.aicredits.in",
api_key="sk-your-key",
)
TOKEN_BUDGET = 50_000 # stop the agent after this many input tokens
total_input_tokens = 0
def run_agent_with_budget(messages, tools):
global total_input_tokens
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=2048,
tools=tools,
messages=messages,
)
total_input_tokens += response.usage.input_tokens
print(f"Step used {response.usage.input_tokens} tokens. Total: {total_input_tokens}")
if total_input_tokens > TOKEN_BUDGET:
raise RuntimeError(
f"Token budget exceeded ({total_input_tokens} > {TOKEN_BUDGET}). "
f"Stopping agent to prevent runaway cost."
)
return responseAt Sonnet pricing, 50,000 input tokens costs about ₹14 — a reasonable limit for an exploratory task. For a production workflow you might set it to 200,000 (₹55).
Prevention strategy 4: Context window pruning
Context accumulation is the silent cost multiplier. Each step adds to the conversation history, which gets sent again with every request. A 20-step agent where each step adds 500 tokens sends ~10× more tokens in step 20 than step 1 — even if the task itself hasn't changed.
Prune old messages before they inflate your costs:
def prune_messages(messages: list, max_tokens: int = 20_000) -> list:
"""
Keep the system prompt + last N messages that fit within token budget.
Simple approximation: 1 token ≈ 4 chars.
"""
# Always keep system messages
system = [m for m in messages if m["role"] == "system"]
non_system = [m for m in messages if m["role"] != "system"]
# Estimate token count and trim from the front
while non_system:
approx_tokens = sum(len(str(m.get("content", ""))) // 4 for m in system + non_system)
if approx_tokens <= max_tokens:
break
# Drop the oldest user/assistant pair
non_system = non_system[2:]
return system + non_systemFor Claude Code specifically, you can use /compact to summarise and compress the conversation history when it gets long.
Prevention strategy 5: Structured task decomposition
Agents that are given vague, open-ended tasks tend to run longer and cost more. Breaking a task into explicit, bounded subtasks caps each individual step:
# Bad: open-ended, hard to bound
task = "Review this entire codebase and suggest all possible improvements."
# Better: specific, bounded subtasks
subtasks = [
"List all files in src/ that exceed 200 lines.",
"For each file in the list, identify the top 1 refactoring opportunity.",
"Write a one-paragraph summary of findings.",
]
# Each subtask is a separate, bounded API call — no runaway loop
for subtask in subtasks:
result = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024, # tight output limit per subtask
messages=[{"role": "user", "content": subtask}],
)
process(result)A practical budget for common agent types
Based on typical usage patterns:
| Agent type | Recommended budget cap | Why | |---|---|---| | Claude Code (personal) | ₹2,000/month | ~20 full coding sessions | | Code review agent | ₹500/run | ~5,500 tokens per PR × 10 PRs | | RAG Q&A agent | ₹100/day | Mostly retrieval, short context | | Research / web agent | ₹200/task | Multiple tool calls, moderate context | | Data processing agent | ₹50 per 1,000 records | Scale with volume |
Set these as budget caps on the API key used for each agent. When the cap hits, the agent fails loudly — which is far better than it failing silently at 10× the intended cost.
Monitoring: catch problems before they become bills
The best time to notice a runaway agent is before the budget runs out, not after. Use the AICredits usage dashboard to set up monitoring:
- Dashboard → Usage shows per-request cost, model, and token counts in real time
- Sort by cost descending to immediately spot unusually expensive requests
- Look for requests with very high
input_tokens— this is the signature of context accumulation
A single request costing more than ₹10 should raise a flag. A sequence of requests where input token count keeps growing is almost certainly a runaway loop.
Summary: the five levers
| Lever | Where to set it | Protection level | |---|---|---| | Per-key budget cap | AICredits dashboard | Hard stop — catches everything | | Max steps | Your agent loop code | Stops infinite loops | | Token budget | Per-run counter in code | Catches context accumulation | | Context pruning | Message history management | Reduces cost without stopping | | Structured subtasks | Task design | Prevents expensive exploration |
Use all five for production agents. At minimum, always set a per-key budget cap — it's the only protection that requires zero code changes and catches every failure mode.
Related Articles
Continue in Docs
Need implementation commands and endpoint details? Go to quickstart or API reference.