How Much Does It Actually Cost to Run an AI Agent?
Measure real monthly costs for an AI agent with a reproducible script, comparing OpenAI, Anthropic, and local models.
Before you start
You have built a prototype agent that calls a language model in a loop, decides which tool to call, and parses the result. It works in your dev environment. Now your manager asks the question you cannot answer yet: what will this cost in production?
Most cost estimates fail because they assume a fixed number of tokens per request. Real agents are dynamic. They retry, loop, and sometimes spiral. This article gives you a reproducible way to measure the actual cost of your agent, not a guess.
- You need a working agent that makes at least one LLM call per task.
- You need API keys for at least one provider (OpenAI or Anthropic).
- You need Python 3.9+ and the requests library installed.
- You will run a script that logs token usage per step and computes cost.
- You will compare costs across providers and a local model.
Step 1: Instrument your agent to log token usage
The first step is to capture the token usage from every LLM call. Most SDKs return usage metadata. If you are using the OpenAI Python SDK, the response object has a usage field. If you are using raw HTTP, parse the usage from the JSON response.
Create a file called agent_cost_logger.py. This script defines a function that wraps your LLM call and appends usage to a log file. It uses the OpenAI API but the pattern works for any provider.
import json
import time
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY from env
def call_llm(messages, model="gpt-4o-mini", log_file="agent_usage.jsonl"):
resp = client.chat.completions.create(model=model, messages=messages)
usage = resp.usage
entry = {
"timestamp": time.time(),
"model": model,
"prompt_tokens": usage.prompt_tokens,
"completion_tokens": usage.completion_tokens,
"total_tokens": usage.total_tokens,
}
with open(log_file, "a") as f:
f.write(json.dumps(entry) + "\n")
return resp.choices[0].message.content
- Run this logger in your agent loop for every LLM call.
- If you use Anthropic, the response has usage.input_tokens and usage.output_tokens.
- Log the model name because you may switch models later.
- Store the log as JSONL for easy aggregation.
Step 2: Run a realistic workload
You need to run your agent on a set of tasks that represent real usage. Use at least 10 tasks to get a meaningful average. The tasks should vary in complexity. For this example, we will simulate a customer support agent that answers questions and sometimes looks up a database.
Create a test script that calls your agent loop 20 times with different prompts. Record the total tokens used per run.
import json
from agent_cost_logger import call_llm
# Simulate an agent loop: each task may require 1-3 LLM calls
tasks = [
"What is your return policy?",
"I need a refund for order #1234.",
"Do you ship to Canada?",
"My account is locked, help.",
"What is the status of my order?",
"Can I change my shipping address?",
"How do I cancel my subscription?",
"I got the wrong item, what do I do?",
"Do you have a student discount?",
"My payment failed, why?",
]
for task in tasks:
# First call: classify intent
messages = [
{"role": "system", "content": "You are a support agent. Classify the intent."},
{"role": "user", "content": task}
]
intent = call_llm(messages)
# Second call: generate response (simplified)
messages.append({"role": "assistant", "content": intent})
messages.append({"role": "user", "content": "Now respond to the customer."})
call_llm(messages)
print("Log written. Run the cost calculator next.")
Step 3: Calculate the cost from the log
Now that you have a log file with token counts, you can compute the cost. The pricing differs by model and provider. As of May 2025, the relevant prices are: GPT-4o-mini costs 0.15 USD per 1M input tokens and 0.60 USD per 1M output tokens. Claude 3.5 Haiku costs 0.80 USD per 1M input and 4.00 USD per 1M output. These prices change, so verify before relying on them.
Write a script that reads the JSONL log, applies the price per model, and prints the total cost per task and the average cost per task.
import json
from collections import defaultdict
PRICING = {
"gpt-4o-mini": {"input": 0.15e-6, "output": 0.60e-6}, # per token
"claude-3-5-haiku": {"input": 0.80e-6, "output": 4.00e-6},
}
def compute_cost(log_file="agent_usage.jsonl"):
totals = defaultdict(lambda: {"prompt": 0, "completion": 0, "calls": 0})
with open(log_file) as f:
for line in f:
entry = json.loads(line)
m = entry["model"]
totals[m]["prompt"] += entry["prompt_tokens"]
totals[m]["completion"] += entry["completion_tokens"]
totals[m]["calls"] += 1
for model, usage in totals.items():
cost = (usage["prompt"] * PRICING[model]["input"] +
usage["completion"] * PRICING[model]["output"])
print(f"{model}: {usage['calls']} calls, {cost:.4f} USD")
print(f" avg cost per call: {cost / usage['calls']:.6f} USD")
if __name__ == "__main__":
compute_cost()
- Run python agent_cost_logger.py to generate the log.
- Run python cost_calculator.py to see the output.
- The average cost per call is the number you need for scaling estimates.
Step 4: Compare providers with a side-by-side test
You want to know if switching from OpenAI to Anthropic changes the cost. The best way is to run the same workload against both. Modify the logger to accept a provider parameter, or write a separate script that calls each provider directly.
The script below runs the same 10 tasks against both GPT-4o-mini and Claude 3.5 Haiku, logs usage, and prints the total cost.
import json
import time
from openai import OpenAI
from anthropic import Anthropic
openai_client = OpenAI()
anthropic_client = Anthropic()
def call_openai(messages, model="gpt-4o-mini"):
resp = openai_client.chat.completions.create(model=model, messages=messages)
return resp.usage.prompt_tokens, resp.usage.completion_tokens
def call_anthropic(messages, model="claude-3-5-haiku"):
# Convert OpenAI format to Anthropic format
system = messages[0]["content"]
msgs = [{"role": m["role"], "content": m["content"]} for m in messages[1:]]
resp = anthropic_client.messages.create(model=model, system=system, messages=msgs, max_tokens=1024)
return resp.usage.input_tokens, resp.usage.output_tokens
providers = {"openai": call_openai, "anthropic": call_anthropic}
for name, func in providers.items():
total_prompt = total_completion = 0
for task in tasks:
# Simplified: one call per task for comparison
p, c = func([{"role": "system", "content": "You are a support agent."},
{"role": "user", "content": task}])
total_prompt += p
total_completion += c
cost = (total_prompt * 0.15e-6 + total_completion * 0.60e-6) if name == "openai" else \
(total_prompt * 0.80e-6 + total_completion * 4.00e-6)
print(f"{name}: {total_prompt} prompt, {total_completion} completion, cost ${cost:.4f}")
- Run this script with both API keys set in your environment.
- The output shows the raw token counts and cost for each provider.
- Remember that model quality differs; cost is not the only factor.
Step 5: Factor in the agent loop overhead
The cost per call is only part of the story. Agents often make multiple calls per task, including retries and tool calls. You need to know the average number of LLM calls per completed task.
Add a counter to your agent loop that increments every time you call the LLM. Run your workload and divide the total calls by the number of tasks. This gives you the calls per task multiplier.
import json
from collections import Counter
# After running your workload, count calls per task from the log
def count_calls_per_task(log_file="agent_usage.jsonl"):
# Assuming each task logs a unique task_id, add that to your logger
counts = Counter()
with open(log_file) as f:
for line in f:
entry = json.loads(line)
counts[entry.get("task_id", "unknown")] += 1
total_calls = sum(counts.values())
num_tasks = len(counts)
print(f"Total calls: {total_calls}, Tasks: {num_tasks}")
print(f"Average calls per task: {total_calls / num_tasks:.2f}")
if __name__ == "__main__":
count_calls_per_task()
- Add a task_id field to your logger entries to make this work.
- If your agent retries on failure, the multiplier will be higher.
- A typical agent might average 3 to 5 calls per task, not 1.
Step 6: Estimate monthly cost for production
Now you can calculate the monthly cost. You need three numbers: average cost per LLM call, average calls per task, and expected tasks per month.
Use this formula: monthly cost = cost per call x calls per task x tasks per month. The script below does this for you given your measured numbers.
#!/bin/bash
# Estimate monthly cost
echo "Enter average cost per call (USD):"
read COST_PER_CALL
echo "Enter average calls per task:"
read CALLS_PER_TASK
echo "Enter expected tasks per month:"
read TASKS_PER_MONTH
MONTHLY=$(echo "$COST_PER_CALL * $CALLS_PER_TASK * $TASKS_PER_MONTH" | bc)
echo "Estimated monthly cost: $MONTHLY USD"
- Run chmod +x estimate_monthly.sh and then ./estimate_monthly.sh.
- Use your measured values from Steps 3 and 5.
- This is a baseline; add 20% for variance and retries.
Step 7: Compare with a local model
If you are considering running a local model, the cost model changes. You pay for hardware and electricity, not per token. A simple way to estimate is to run a small model like Llama 3.2 3B on your machine and measure tokens per second and power draw.
The command below runs a local model using Ollama and measures tokens per second. You can then estimate the cost of electricity per token.
# Install Ollama if not present
curl -fsSL https://ollama.com/install.sh | sh
# Pull a small model
ollama pull llama3.2:3b
# Run a test prompt and measure time
start=$(date +%s%N)
output=$(ollama run llama3.2:3b "What is the capital of France?")
end=$(date +%s%N)
elapsed_ms=$(( (end - start) / 1000000 ))
echo "Response: $output"
echo "Elapsed time: ${elapsed_ms} ms"
- Use a power meter or estimate your GPU wattage to get cost per hour.
- For a rough estimate, assume 300W for a mid-range GPU.
- At 0.15 USD per kWh, running 24/7 costs about 32 USD per month in electricity.
Recommended setup for cost monitoring
After measuring, you should set up continuous cost monitoring. Use a simple script that runs weekly and aggregates your logs. You can also use a tool like LangSmith or Helicone, but a custom script is fine for small projects.
Here is a cron-ready script that emails you a cost report. It assumes you have the cost_calculator.py from Step 3.
#!/bin/bash
# Run weekly cost report
cd /path/to/your/agent
python cost_calculator.py > cost_report.txt
# Send email (requires mailx or similar)
mail -s "Agent Cost Report" you@example.com < cost_report.txt
- Add this script to crontab: 0 9 * * 1 /path/to/cost_report.sh
- Keep your logs in a separate directory to avoid clutter.
- Set a budget alert if you use a provider dashboard.
Troubleshooting
If your cost estimates seem too high or too low, check these common issues.
Token counts from the API include system prompts and tool definitions, which can be large.
If you are using a model with caching, the cached tokens are billed at a lower rate.
- Make sure you are logging every LLM call, including retries.
- Check that your pricing table is up to date.
- For local models, include hardware depreciation in your cost if you are comparing to cloud APIs.
- If you use a multi-step agent, the calls per task can be much higher than expected.
FAQ
How do I account for tool call tokens?
Tool definitions are part of the prompt, so they are counted as input tokens. The output of the tool is also input for the next call.
What if my agent uses multiple models?
Log the model name for each call and apply the corresponding price. The script in Step 3 already handles that.
Is a local model always cheaper?
Not always. For low volume, cloud is cheaper because you avoid hardware costs. For high volume, local can be cheaper but requires upfront investment.
How often should I recalculate?
At least monthly, because pricing changes and your agent behavior changes.
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 much does it actually cost to run an ai agent? — 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 27, 2026. Fundamentals stay stable; check linked tool pages and official docs when version-specific behavior matters.