AI LLM Cost Tracking Template
Track token usage and costs per feature, model, and user. Includes cost categories, pricing tables, budget alerts, optimization strategies, and reporting templates for LLM API spending.
Overview
LLM bills arrive as one number; the interesting question is which items drove it. This template tracks API costs per feature, model, and user — meter the spend, attribute it, and suddenly “the bill went up” becomes “the new summarizer feature costs $40/day and nobody’s using it.”
Use it to watch spend, set budgets with real thresholds, find the cost drivers, and tune token usage where it actually helps. Adapt the categories and thresholds to your org — the structure is the template, the numbers are yours.
How the Tracking Actually Works
The only non-negotiable piece is a log per call — model, feature, user, token counts — because without that schema there’s nothing to attribute. On top of it sit the budget config, with thresholds that alert before the invoice arrives, and the monthly report someone actually reads: cost per feature, per user, and the delta vs last month, so an anomaly jumps off the page.
Companion files: the ai-llm-cost-tracking-template companion repo has everything on this page as standalone files — the budget_config.yaml, a runnable llm_cost_monitor.py, the schema.sql for Postgres, and the monthly report template.
The pipeline itself is dumb on purpose: every LLM call gets wrapped once, the wrapper stamps on a feature and user_id, and the record lands in a store you can aggregate. The sophistication is in the tagging — feature names need to be the thing a PM would recognize, not the internal function name, or the monthly report turns into a translation exercise nobody reads.
1. Pricing Reference Table
Refresh this table against your providers’ current pricing — it goes stale fast (figures checked Oct 2026).
Model | Input ($/1K tok) | Output ($/1K tok) | Context window
───────────────────┼──────────────────┼───────────────────┼───────────────
GPT-4o | $0.00250 | $0.01000 | 128K
GPT-4o-mini | $0.00015 | $0.00060 | 128K
Claude 3.5 Sonnet | $0.00300 | $0.01500 | 200K
Claude 3 Haiku | $0.00025 | $0.00125 | 200K
Llama 3.1 70B | $0.00059 | $0.00079 | 128K
Gemini 1.5 Pro | $0.00125 | $0.00500 | 2M
Gemini 1.5 Flash | $0.000075 | $0.00030 | 1M
Embedding models:
text-embedding-3-small | $0.00002 / 1K tokens
text-embedding-3-large | $0.00013 / 1K tokens
2. Cost Tracking Schema
Per-Request Log
{
"request_id": "req_abc123",
"timestamp": "2026-07-04T10:30:00Z",
"feature": "chat-completion",
"user_id": "user_456",
"model": "gpt-4o",
"prompt_tokens": 1250,
"completion_tokens": 450,
"total_tokens": 1700,
"input_cost": 0.003125,
"output_cost": 0.0045,
"total_cost": 0.007625,
"latency_ms": 1200,
"status": "success"
}
Daily Aggregation
{
"date": "2026-07-04",
"feature": "chat-completion",
"model": "gpt-4o",
"total_requests": 1500,
"total_prompt_tokens": 1875000,
"total_completion_tokens": 675000,
"total_tokens": 2550000,
"total_cost": 11.34,
"avg_cost_per_request": 0.00756,
"avg_latency_ms": 1150,
"error_count": 12,
"unique_users": 340
}
3. Cost by Feature
Sort this table once and it basically tells you where to work: the top rows hold nearly every optimization decision you’ll make this quarter. If one feature is half your spend, that’s where a caching layer or a model downgrade earns its keep; the 2% rows at the bottom aren’t worth an hour of engineering.
Feature | Model | Daily cost | Monthly est | % of budget
─────────────────────┼───────────────┼────────────┼─────────────┼────────────
Chat completion | GPT-4o | $11.34 | $340.20 | 45%
Document Q&A (RAG) | GPT-4o | $7.82 | $234.60 | 31%
Code review | Claude 3.5 | $3.45 | $103.50 | 14%
Text classification | GPT-4o-mini | $0.89 | $26.70 | 4%
Embedding generation | text-emb-3-sm | $0.42 | $12.60 | 2%
Sentiment analysis | GPT-4o-mini | $0.31 | $9.30 | 2%
Image description | GPT-4o | $1.23 | $36.90 | 2%
─────────────────────┴───────────────┴────────────┴─────────────┴────────────
Total | $25.46 | $763.80 | 100%
4. Cost by User
Spot power users — and the ones abusing the API. The shape of the distribution matters more than the totals: a healthy curve is a long tail of many cheap users and few expensive ones. When the curve flattens — one user costing more than the next hundred combined — you’ve got either a champion or a leak, and the per-user daily cap decides which.
User tier | Users | Daily cost | Cost/user | % of cost
─────────────┼───────┼────────────┼───────────┼──────────
Free tier | 2800 | $4.20 | $0.0015 | 16%
Pro tier | 340 | $14.85 | $0.0437 | 58%
Enterprise | 12 | $5.80 | $0.4833 | 23%
Internal | 8 | $0.61 | $0.0763 | 3%
─────────────┴───────┴────────────┴───────────┴──────────
Total | 3160 | $25.46 | | 100%
5. Budget Configuration
# budget_config.yaml
monthly_budget: 1000.00 # USD
alert_thresholds:
- percentage: 50
action: "notify"
recipients: ["ai-team@company.com"]
- percentage: 75
action: "notify"
recipients: ["ai-team@company.com", "finance@company.com"]
- percentage: 90
action: "notify"
recipients: ["ai-team@company.com", "finance@company.com", "cto@company.com"]
- percentage: 100
action: "throttle"
message: "Monthly LLM budget exceeded. Non-critical features disabled."
disabled_features:
- sentiment-analysis
- image-description
per_feature_budgets:
chat-completion: 400.00
document-qa: 300.00
code-review: 150.00
text-classification: 50.00
embedding-generation: 50.00
sentiment-analysis: 30.00
image-description: 20.00
per_user_limits:
free-tier:
daily_cost: 0.05
daily_requests: 50
pro-tier:
daily_cost: 1.00
daily_requests: 500
enterprise:
daily_cost: 10.00
daily_requests: 5000
6. Cost Optimization Strategies
6.1 Model Downgrading
When to downgrade:
- Classification tasks → GPT-4o-mini (15x cheaper than GPT-4o)
- Simple extraction → GPT-4o-mini or Claude 3 Haiku
- Embedding generation → text-embedding-3-small (6x cheaper than large)
- Short responses → smaller model with lower latency
Before downgrading:
1. Run an A/B test of 1000 requests against each model
2. Compare output quality (accuracy, faithfulness, relevance)
3. Work out the savings
4. If quality drop < 3% and savings > 50%, downgrade
6.2 Prompt Compression
Techniques:
- Remove redundant instructions
- Use concise system prompts
- Compress few-shot examples (shorter examples)
- Remove unnecessary context from RAG (fewer chunks)
- Use structured prompts (JSON instead of natural language)
Impact:
- 20-40% token reduction is common
- Direct cost savings on input tokens
- Faster response times
6.3 Caching
import hashlib
import redis
import json
import openai
r = redis.Redis(host="localhost", port=6379)
client = openai.OpenAI()
def cached_llm_call(prompt: str, model: str = "gpt-4o", ttl: int = 3600):
cache_key = f"llm:{model}:{hashlib.sha256(prompt.encode()).hexdigest()}"
cached = r.get(cache_key)
if cached:
return json.loads(cached), 0.0 # Cache hit — no cost
response = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": prompt}],
)
result = response.choices[0].message.content
cost = calculate_cost(model, response.usage) # $ lookup — see §1 pricing table
r.setex(cache_key, ttl, json.dumps(result))
return result, cost
# Cache hit rate tracking
cache_hits = 0
cache_misses = 0
def track_cache(hit: bool):
global cache_hits, cache_misses
if hit:
cache_hits += 1
else:
cache_misses += 1
# Monthly savings = cache_hits * avg_cost_per_request
6.4 Batch Processing
# Batch API (50% discount on most providers)
def batch_process(prompts: list[str], model: str = "gpt-4o"):
# OpenAI Batch API
import openai
client = openai.OpenAI()
# Create batch file
requests = [
{
"custom_id": f"req-{i}",
"method": "post",
"url": "/v1/chat/completions",
"body": {
"model": model,
"messages": [{"role": "user", "content": prompt}],
}
}
for i, prompt in enumerate(prompts)
]
# Upload and submit batch
# 50% discount, 24-hour turnaround
# Good for non-real-time workloads
6.5 Prompt Caching
Providers bill repeated input prefixes at a fraction of the input rate — OpenAI and Anthropic both discount cached tokens aggressively. The wins are structural: put stable system prompts, tool schemas, and few-shot examples at the front of the message where they can be cached, and put per-request content at the end. Say your system prefix is 8K tokens and it runs 10,000 times a day: that’s 80M input tokens billed, or only the few that actually change if they hit the cache.
7. Monthly Report Template
# LLM Cost Report — [Month Year]
## Summary
- Total spend: $[amount]
- Budget: $[budget]
- Budget utilization: [X]%
- Cost per active user: $[amount]
- Total requests: [count]
- Average cost per request: $[amount]
## Cost by Feature
| Feature | Spend | % | MoM change |
|---------|-------|---|------------|
| [feature] | $[x] | [x]% | [+/-X%] |
## Cost by Model
| Model | Spend | % | Requests |
|-------|-------|---|----------|
| [model] | $[x] | [x]% | [count] |
## Top 10 Users by Cost
| User | Spend | Requests | Avg cost/req |
|------|-------|----------|-------------|
| [user] | $[x] | [count] | $[x] |
## Optimization Actions Taken
- [action 1]: saved $[x]/month
- [action 2]: saved $[x]/month
## Recommendations
- [recommendation 1]
- [recommendation 2]
## Alerts Triggered
- [alert]: [date] — [description]
8. Monitoring Script
The monitor below is the reference implementation for the whole setup: feed it the per-request log from section 2 and the budget config from section 5, and it returns the alerts to fire. Wire it into whatever scheduler runs your other ops jobs — cron, a CI pipeline, a container on a timer. In production it runs as a scheduled job — hourly is the right cadence for most workloads, since a bad hour is recoverable but a bad month isn’t.
import datetime
import json
from collections import defaultdict
class LLMCostMonitor:
def __init__(self, budget_config: dict):
self.config = budget_config
self.daily_spend = defaultdict(float)
self.feature_spend = defaultdict(lambda: defaultdict(float))
def record(self, request: dict):
date = request["timestamp"][:10]
cost = request["total_cost"]
feature = request["feature"]
self.daily_spend[date] += cost
self.feature_spend[date][feature] += cost
def check_budget(self, date: str) -> dict:
monthly_spend = sum(
spend for d, spend in self.daily_spend.items()
if d.startswith(date[:7])
)
budget = self.config["monthly_budget"]
utilization = monthly_spend / budget
alerts = []
for threshold in self.config["alert_thresholds"]:
if utilization >= threshold["percentage"] / 100:
alerts.append({
"threshold": threshold["percentage"],
"action": threshold["action"],
"spend": monthly_spend,
"budget": budget,
})
return {
"monthly_spend": monthly_spend,
"budget": budget,
"utilization": utilization,
"alerts": alerts,
}
def daily_report(self, date: str) -> dict:
return {
"date": date,
"total_spend": self.daily_spend[date],
"by_feature": dict(self.feature_spend[date]),
}
9. Storage Schema (SQL)
Once you log more than a few thousand requests a day, files stop cutting it — put the records in a table you can actually query:
CREATE TABLE llm_usage (
id BIGSERIAL PRIMARY KEY,
request_id TEXT NOT NULL,
ts TIMESTAMPTZ NOT NULL DEFAULT now(),
feature TEXT NOT NULL,
user_id TEXT,
model TEXT NOT NULL,
prompt_tokens INTEGER NOT NULL,
completion_tokens INTEGER NOT NULL,
total_cost NUMERIC(12,6) NOT NULL,
latency_ms INTEGER,
status TEXT NOT NULL DEFAULT 'success'
);
CREATE INDEX idx_llm_usage_ts_feature ON llm_usage (ts, feature);
CREATE INDEX idx_llm_usage_user ON llm_usage (user_id, ts);
The (ts, feature) index is the one that matters — every report you generate slices by time and feature. Once the raw table gets heavy, add a daily rollup and have a nightly job aggregate into it:
CREATE TABLE llm_usage_daily (
date DATE NOT NULL,
feature TEXT NOT NULL,
model TEXT NOT NULL,
requests INTEGER NOT NULL,
total_tokens BIGINT NOT NULL,
total_cost NUMERIC(12,4) NOT NULL,
unique_users INTEGER,
PRIMARY KEY (date, feature, model)
);
Dashboards read the rollup; the raw table is for debugging and drilling into anomalies. Postgres carries this comfortably into the millions of rows; past ~50M rows a month, move the rollup to whatever warehouse you already have (BigQuery, Snowflake) and keep the database for the last 90 days of raw detail.
10. Alerting Integrations
A threshold in a YAML file is only as good as the channel it screams through. Wire the monitor to wherever the team actually looks:
def send_slack_alert(webhook_url: str, alert: dict):
import requests
requests.post(webhook_url, json={
"text": f":warning: LLM spend at {alert['threshold']}% of budget: "
f"${alert['spend']:.2f} of ${alert['budget']:.2f} this month."
})
def send_email_alert(smtp_client, recipients: list, alert: dict):
subject = f"[LLM Budget] {alert['threshold']}% threshold hit"
body = (f"Spend is ${alert['spend']:.2f} of ${alert['budget']:.2f}.\n"
f"Review feature-level costs before the month ends.")
smtp_client.send(recipients, subject, body)
Rule of thumb: 50% goes to the team channel, 75% goes to whoever signs the checks, and 100% goes to whoever owns the kill switch. Alerts nobody reads are monitoring theatre.
For dashboards, pipe the daily rollup into whatever the team already uses — a Grafana panel with cost-per-feature over time catches drift faster than any monthly report. Budget pace (actual spend vs straight-line projection to month end) is the single most useful chart to put on it.
11. Edge Cases and Gotchas
- Retries bill you twice. A call that times out and retries three times is three billable requests. Log retries with a
retry_offield pointing at the originalrequest_id, or your attribution quietly overstates spend. - Streaming counts late. With
stream=True, usage data only arrives if you setstream_options={"include_usage": True}— miss that flag and you’re back to guessing tokens from text length, and guesses drift. - Cached input has its own price. Prompt caching bills cached tokens at a discount, so log
cached_tokenson its own field or your totals quietly overstate spend. - Vision isn’t tokens. Image inputs price per image or per patch, not per token. Track them under a separate
unitfield instead of pretending they’re tokens. - Fine-tuned models have their own rates. Treat model prices as data, not code: keep the pricing table in config so a price change is a YAML edit, not a deploy.
- Multi-currency reporting. If engineering reports in USD and finance thinks in EUR, store raw cents and convert at report time — never inside the logger.
12. Implementation Checklist
- Meter first. Wrap the API client once; every call logs
feature,user_id, model, and token counts. If the wrapper is optional it will be skipped — make it the only path. - Attribute on write, not on read. Tag the call where the business context exists; recovering “which feature was this” later is archaeology.
- Aggregate nightly. Raw table for detail, daily rollup for reports. Dashboards should read the rollup, not scan millions of rows.
- Alert before the limit. 50/75/90% notify, 100% throttle. Pick the items to disable in advance — deciding under pressure means disabling the wrong thing.
- Report monthly. One page: spend, utilization, top feature rows, top users, actions taken, next actions. Nobody reads page two — cut until they do.
- Review quarterly. Re-baseline the pricing table, re-run downgrade A/B tests, and delete the functionality nobody uses.
13. Data Retention
Decide up front how long raw request logs live — they contain user_id and, depending on what you log, prompt content. Keep raw rows for 30–90 days for debugging, then archive or delete them; keep daily aggregates as long as finance needs them, typically a fiscal year or more. Whatever you keep, write it down: “we store cost telemetry, not prompts” is a sentence your security review will ask for verbatim.
14. Cost Allocation and Showback
If several teams share one AI budget, someone has to own the number. Showback reports what each team spent without charging them; chargeback actually moves money between cost centers. Start with showback — the report alone changes behavior — and graduate to chargeback once people trust the numbers.
Team | Feature | Monthly cost | % of total
──────────────┼───────────────────────┼──────────────┼───────────
Platform | internal-tools | $180.50 | 24%
Growth | onboarding-assistant | $215.30 | 28%
Support | ticket-triage | $190.20 | 25%
Data | analytics-assistant | $98.40 | 13%
Sales | email-drafter | $79.40 | 10%
──────────────┴───────────────────────┼──────────────┼───────────
Total | $763.80 | 100%
The mechanics are the same as everything else here: tag usage with team at the same boundary where you tag feature, roll it up monthly, and send each team a report that looks just like section 3 scoped to their spend. Put their number next to everyone else’s and teams optimize on their own — nobody likes being the biggest line item.
See Also
To keep going on this topic:
-
Complete Guide to LLM Cost Optimization — the long read on getting the bill down
-
Complete Guide to LLM Prompt Engineering — cheaper prompts start here
-
AI Agent Design Document Template — where to budget an agent before building it
-
AI LLM Prompt Template Library — versioned prompts this template can meter
-
AI Prompt Version Control Template — for telling what changed when cost climbs
-
OpenAI Pricing — check here first when the table numbers look off
-
Anthropic Pricing — the Claude side of the same check
Frequently Asked Questions
How do I estimate LLM costs before launching a feature?
Cost per request first: (avg input tokens × input price) + (avg output tokens × output price), times expected daily requests, plus ~20% headroom for variance. Say a chat feature sends 1500 input + 500 output tokens to GPT-4o: (1500/1000 × $0.0025) + (500/1000 × $0.01) ≈ $0.0088/request — 1,000 requests a day lands at ~$8.75/day, ~$262/month.
What is a reasonable cost per user for an AI feature?
On the free tier you want under a cent per user per day, which means cheap models (GPT-4o-mini, Haiku) and aggressive caching. Pro lands around $0.05-0.50/day; enterprise goes $1-5/day depending on how hard they hammer it. Whatever the tier, watch cost per user weekly — once it drifts over target, tighten model selection or rate limits.
Should I pass LLM API costs to my customers?
If LLM spend is a big slice of your per-user cost, usage-based pricing is the honest model — free tier with daily caps, pro with higher limits, enterprise custom. Track cost per user per tier so the price covers the LLM bill plus margin. Shortcut version: free users get the small model, paid users get the flagship.
How do I reduce costs without sacrificing quality?
Start with cache: an identical query should never cost you twice. Next, run simple work (classification, extraction) on the cheap model, push anything non-real-time through the batch API (50% off), and keep prompts and RAG context tight. Per-user rate limits catch abuse; cost-per-request alerts pick up the rest.
What causes unexpected cost spikes?
Check the usual suspects first: a user pasting enormous prompts, a retry loop gone wild, RAG pulling too many chunks, a price change that never made it into the code, one bot hammering the endpoint, or a test script someone forgot in production. Per-request cost alerts (> $0.50), per-user daily caps, and per-feature budgets surface most of these within a day.
How do I attribute costs when one feature spans several LLM calls?
Stamp a feature ID at the outer boundary — every LLM call inside that request carries it. A "summarize document" flow fanning out into a map/reduce of calls keeps feature: "doc-summary" on all of them. Async chains pass the tag through the queue message, same as a trace ID. Attribution lives and dies on that field; the rest is arithmetic.
What belongs on the LLM cost dashboard?
You need five panels, not fifty: daily spend against budget pace, cost per feature over time, cost per user tier, average cost per request by model, and the error/retry rate — retries burn budget without producing anything. More than that's usually noise; a dashboard earns its keep when someone can answer "what changed?" in thirty seconds.
Related Resources
Complete Guide to LLM Cost Optimization
Cut LLM costs in production: model routing, prompt compression, caching, Batch API, token budgets and cost monitoring with real numbers.
DocAI Model Selection Matrix
Compare LLM models by cost, latency, context window, accuracy, and use case. Includes decision criteria, benchmark results, pricing comparison, and recommendations for classification, extraction, summarization, code, and agent tasks.
DocAI LLM Prompt Template Library
A reusable prompt template library for common LLM tasks: summarization, extraction, classification, code review, translation, and structured output with variables, examples, and evaluation criteria.
DocCloud Cost Allocation Template: Tagging & Chargeback
A template for assigning cloud infrastructure costs to teams, products, or environments with enforced tagging, chargeback rules, and shared cost splitting.