How to Prevent AI Agents From Burning Through API Credits
Learn practical strategies to cap AI agent API costs, including token budgets, caching, retries, and observability, with runnable examples.
Before you start
You have an AI agent that calls an LLM API, and the bill is climbing fast. Maybe it is a support bot that loops on the same question, or a coding assistant that retries on every error. The fix is not to stop using agents; it is to put guardrails around every call.
This article walks through concrete techniques to cap spending: setting token budgets, caching responses, limiting retries, and adding observability. You will get copy-paste code for a minimal agent loop, a caching proxy, and a cost tracker. We assume you have an OpenAI-compatible API key and Node.js 18 or later.
All examples use the fetch API and plain JavaScript, so you can run them without extra dependencies. The same patterns apply to Python or other languages.
export OPENAI_API_KEY="sk-your-key"
export AGENT_BUDGET_DAILY=5.00
export AGENT_BUDGET_MONTHLY=100.00Step 1: Set a hard token budget per agent run
The most direct way to stop runaway costs is to cap the total tokens an agent can consume in a single run. Most LLM APIs return usage in the response, so you can accumulate it and stop when you hit the limit.
Here is a minimal agent loop that enforces a token budget. It tracks input and output tokens and aborts the run when the budget is exceeded.
const MAX_TOKENS_PER_RUN = 4000;
let totalTokensUsed = 0;
async function callLLM(messages) {
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`
},
body: JSON.stringify({
model: 'gpt-4o-mini',
messages,
max_tokens: 500
})
});
const data = await response.json();
if (!response.ok) throw new Error(`API error: ${data.error?.message}`);
totalTokensUsed += data.usage.total_tokens;
if (totalTokensUsed > MAX_TOKENS_PER_RUN) {
throw new Error('Token budget exceeded');
}
return data.choices[0].message.content;
}
// Example agent loop
const messages = [{ role: 'user', content: 'Summarize this article' }];
try {
const result = await callLLM(messages);
console.log(result);
} catch (err) {
console.error('Agent stopped:', err.message);
}- Check the usage object in every API response and accumulate total_tokens.
- Set a realistic limit based on your task; a typical support query might need 500-1000 tokens.
- Throw an error or return a fallback when the budget is exhausted.
Step 2: Cache repeated LLM calls
Agents often ask the same question repeatedly, especially when retrying or when multiple users hit the same endpoint. Caching identical requests can cut costs dramatically.
Implement a simple in-memory cache keyed by the messages and model. For production, use Redis or a database, but this example shows the pattern.
const cache = new Map();
const CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour
function cacheKey(messages, model) {
return `${model}:${JSON.stringify(messages)}`;
}
async function callLLMWithCache(messages, model = 'gpt-4o-mini') {
const key = cacheKey(messages, model);
const cached = cache.get(key);
if (cached && Date.now() - cached.timestamp < CACHE_TTL_MS) {
return cached.response;
}
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`
},
body: JSON.stringify({ model, messages })
});
const data = await response.json();
if (!response.ok) throw new Error(`API error: ${data.error?.message}`);
cache.set(key, { response: data.choices[0].message.content, timestamp: Date.now() });
return data.choices[0].message.content;
}- Cache exact matches only; semantic caching is harder and can give stale answers.
- Set a TTL to avoid serving outdated responses.
- For multi-instance deployments, use a shared cache like Redis.
Step 3: Limit retries with exponential backoff
When an API call fails due to rate limits or transient errors, agents often retry aggressively, multiplying costs. Implement a retry policy with exponential backoff and a maximum retry count.
This function retries up to 3 times with delays of 1, 2, and 4 seconds. It also respects the Retry-After header when present.
async function callLLMWithRetry(messages, maxRetries = 3) {
let attempt = 0;
while (attempt <= maxRetries) {
try {
return await callLLM(messages);
} catch (err) {
if (attempt === maxRetries) throw err;
const delayMs = Math.pow(2, attempt) * 1000;
console.log(`Retry ${attempt + 1} in ${delayMs}ms`);
await new Promise(resolve => setTimeout(resolve, delayMs));
attempt++;
}
}
}- Do not retry on 4xx errors like 400 or 401; only retry on 429 and 5xx.
- Check the Retry-After header and use that delay if present.
- Log each retry attempt for observability.
Step 4: Use a cheaper model for sub-tasks
Not every agent step needs a top-tier model. Use a small, cheap model for classification, extraction, or formatting, and reserve the expensive model for complex reasoning.
Here is a simple router that picks a model based on the task type.
function selectModel(taskType) {
switch (taskType) {
case 'extract':
case 'format':
return 'gpt-4o-mini';
case 'reason':
case 'plan':
return 'gpt-4o';
default:
return 'gpt-4o-mini';
}
}
async function agentStep(taskType, messages) {
const model = selectModel(taskType);
return callLLM(messages, model);
}- Use gpt-4o-mini for summarization, extraction, and classification.
- Use gpt-4o only when the task requires deep reasoning or complex tool use.
- Measure quality on your own dataset before switching.
Step 5: Set a daily and monthly spend cap
Even with per-run limits, an agent can run many times. Enforce a global budget across all runs using a simple counter stored in a file or database.
This script checks the accumulated cost against a daily limit before each call.
const fs = require('fs');
const DAILY_LIMIT = parseFloat(process.env.AGENT_BUDGET_DAILY || '5');
const COST_FILE = '/tmp/agent_cost.json';
function getCosts() {
try {
return JSON.parse(fs.readFileSync(COST_FILE, 'utf8'));
} catch {
return { date: new Date().toISOString().slice(0,10), total: 0 };
}
}
function saveCosts(costs) {
fs.writeFileSync(COST_FILE, JSON.stringify(costs));
}
function canAfford(cost) {
const costs = getCosts();
const today = new Date().toISOString().slice(0,10);
if (costs.date !== today) {
costs.date = today;
costs.total = 0;
}
return costs.total + cost <= DAILY_LIMIT;
}
function addCost(cost) {
const costs = getCosts();
costs.total += cost;
saveCosts(costs);
}- Write the cost tracker to a persistent store if you have multiple instances.
- Use a cron job to reset the counter at midnight.
- Alert when you approach 80% of the limit.
Step 6: Add observability with structured logging
You cannot fix what you cannot see. Log every API call with model, tokens, cost, and latency. This helps you identify which agent runs are expensive.
Here is a logging wrapper that records the essential metrics.
async function callLLMLogged(messages, model = 'gpt-4o-mini') {
const start = Date.now();
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`
},
body: JSON.stringify({ model, messages })
});
const data = await response.json();
const latencyMs = Date.now() - start;
const cost = estimateCost(model, data.usage);
console.log(JSON.stringify({
event: 'llm_call',
model,
prompt_tokens: data.usage.prompt_tokens,
completion_tokens: data.usage.completion_tokens,
total_tokens: data.usage.total_tokens,
cost_usd: cost,
latency_ms: latencyMs,
timestamp: new Date().toISOString()
}));
return data.choices[0].message.content;
}
function estimateCost(model, usage) {
const rates = {
'gpt-4o-mini': { input: 0.00015/1000, output: 0.0006/1000 },
'gpt-4o': { input: 0.0025/1000, output: 0.01/1000 }
};
const r = rates[model] || rates['gpt-4o-mini'];
return (usage.prompt_tokens * r.input) + (usage.completion_tokens * r.output);
}- Send logs to a central aggregator like Datadog or ELK.
- Create a dashboard to monitor cost per agent and per user.
- Set alerts for unusual spikes.
Step 7: Test your guardrails with a mock API
Before deploying, verify that your budget and retry logic work. Use a mock server that returns fake usage data and simulates failures.
This Node.js script spins up a local server that mimics the OpenAI API, allowing you to test without spending real money.
const http = require('http');
const server = http.createServer((req, res) => {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
const parsed = JSON.parse(body);
const promptTokens = parsed.messages.reduce((acc, m) => acc + m.content.length, 0);
const usage = {
prompt_tokens: promptTokens,
completion_tokens: 20,
total_tokens: promptTokens + 20
};
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
choices: [{ message: { role: 'assistant', content: 'Mock response' } }],
usage
}));
});
});
server.listen(4000, () => console.log('Mock API on http://localhost:4000'));- Redirect your agent to the mock by setting OPENAI_API_BASE=http://localhost:4000.
- Simulate a 429 status to test retries.
- Verify that your budget limit stops the agent after N calls.
What I would do: a recommended setup
Combine all the techniques into a single robust pattern. Here is a copy-paste starter that includes token budget, caching, retry, model routing, and logging. Save it as agent.js and run it with Node.
const fs = require('fs');
const MAX_TOKENS_PER_RUN = 4000;
const DAILY_LIMIT = parseFloat(process.env.AGENT_BUDGET_DAILY || '5');
const COST_FILE = '/tmp/agent_cost.json';
const cache = new Map();
let totalTokensUsed = 0;
function getCosts() {
try { return JSON.parse(fs.readFileSync(COST_FILE, 'utf8')); }
catch { return { date: new Date().toISOString().slice(0,10), total: 0 }; }
}
function saveCosts(c) { fs.writeFileSync(COST_FILE, JSON.stringify(c)); }
function canAfford(cost) {
const c = getCosts();
const today = new Date().toISOString().slice(0,10);
if (c.date !== today) { c.date = today; c.total = 0; }
return c.total + cost <= DAILY_LIMIT;
}
function addCost(cost) {
const c = getCosts();
c.total += cost;
saveCosts(c);
}
function estimateCost(model, usage) {
const rates = {
'gpt-4o-mini': { input: 0.00015/1000, output: 0.0006/1000 },
'gpt-4o': { input: 0.0025/1000, output: 0.01/1000 }
};
const r = rates[model] || rates['gpt-4o-mini'];
return usage.prompt_tokens * r.input + usage.completion_tokens * r.output;
}
async function callLLM(messages, model = 'gpt-4o-mini') {
const key = `${model}:${JSON.stringify(messages)}`;
if (cache.has(key)) return cache.get(key);
const cost = estimateCost(model, { prompt_tokens: 100, completion_tokens: 50 });
if (!canAfford(cost)) throw new Error('Daily budget exceeded');
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${process.env.OPENAI_API_KEY}` },
body: JSON.stringify({ model, messages })
});
const data = await response.json();
if (!response.ok) throw new Error(`API error: ${data.error?.message}`);
const usage = data.usage;
totalTokensUsed += usage.total_tokens;
if (totalTokensUsed > MAX_TOKENS_PER_RUN) throw new Error('Token budget exceeded');
const realCost = estimateCost(model, usage);
addCost(realCost);
console.log(JSON.stringify({ event: 'llm_call', model, tokens: usage.total_tokens, cost: realCost }));
const content = data.choices[0].message.content;
cache.set(key, content);
return content;
}
// Example usage
(async () => {
try {
const result = await callLLM([{ role: 'user', content: 'Hello' }]);
console.log(result);
} catch (err) {
console.error(err.message);
}
})();Troubleshooting
If your agent still burns through credits, check the following:
First, verify that your budget checks are actually being called. A common mistake is to skip the canAfford check before the API call.
Second, inspect your logs to see which model is being used and how many tokens each call consumes. You might be calling the expensive model more often than you think.
Third, review your retry logic. If you retry on 4xx errors, you will multiply failures. Only retry on 429 and 5xx.
- Add a log line at the start of every API call to confirm the guardrails run.
- Check the usage field in the API response; some SDKs hide it.
- Use the mock server to test edge cases like hitting the token limit exactly.
- Monitor your daily cost file to see if the cap is working.
FAQ
These are common questions developers ask when implementing cost controls.
Q: Can I rely on the usage field from the API to track costs?
A: Yes, the usage field is accurate for token counts, but you still need to estimate cost per model because pricing varies.
Q: Should I cache every response?
A: Only cache responses that are safe to reuse, like static answers or extraction results. Do not cache personalized or time-sensitive responses.
Q: What is a good token budget for a typical agent run?
A: It depends on the task. A simple Q&A might use 500 tokens, while a multi-step reasoning task could use 5000. Start with a limit that covers your use case and adjust based on logs.
Next step
Implement one guardrail today. Start with the token budget in Step 1, then add logging. Run your agent for a day and review the logs to see where costs go. Then add caching and retry limits.
Create the agent.js file from the recommended setup and run it with a mock API to verify it works before using real credits.
Key takeaways
- Apply one concrete change from this post before collecting more reading.
- Prefer browser-side tools when the work involves secrets, tokens, or PII.
- Document the why next to the how so the next reviewer inherits context.
FAQ
- Who is this guide on ai-agents for?
- Working developers who need a practical take on how to prevent ai agents from burning through api credits — not a marketing overview. Skim the sections, apply one tip, then come back when you hit an edge case.
- Do I need an account to use the related tools?
- No. code.live tools run in your browser with no signup. Nothing you paste is uploaded to a server for the client-side utilities linked from this post.
- How often is this article updated?
- This post was published November 28, 2026. Fundamentals stay stable; check linked tool pages and official docs when version-specific behavior matters.