Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Worked example · 20 min · revision 2

A Cost Report from Usage Logs

Turn a week of per-call usage records into a cost report with pandas: price every call from a price table you pass in, then break cost and latency down by billing category, feature, user action, user, tenant and day, and trace a jump in the bill to the feature and the user that caused it.

Contentsand lesson path

What you will learn

  • Attribute token usage, cost and latency per request, user and feature from logged usage data.

01. The problem

Lumen's daily model spend more than doubled in the second week of October. The provider's dashboard shows that the large model's usage went up, which everyone knew already. The questions that need an answer are different: which feature, which users, since when, and is it worth what it costs?

Lumen writes one usage record per model call, as described in the previous lesson. In this worked example you turn one week of those records into a report that answers those questions. The steps are the same for any log of this shape: load and validate, price every call, then group by every dimension you logged.

You need: Python 3.12 or later and pandas (tested with pandas 3.1). Install it in a virtual environment with python -m pip install pandas. Every number below comes from the scripts as shown. The log is synthetic, generated by a script, so that you can reproduce the report exactly; the prices are example figures, not quotes.

02. Step 1: A week of usage records and a price table

The generator stands in for a week of real logging. Lumen has three features: answer (the RAG assistant, one call per question on the large model, about 3% retried after failed validation), ticket_summary (one call on the small model) and triage_agent, launched on Thursday 8 October, which makes three to seven calls per click. From Friday, one user's integration script runs the agent 90 times a day, every ten minutes from 01:00.

Python · make_log.py
"""Write one synthetic week of Lumen usage records to usage.jsonl (a stand-in log)."""
import json
import random
from datetime import datetime, timedelta

rng = random.Random(7)
records = []


def record(ts, action, user, feature, model, attempt, inp, cw, cr, out, reasoning):
    speed = 14 if model == "large" else 6  # simulated ms per output token
    ttft = 300 + 0.05 * (inp + cw) + 0.01 * cr + rng.random() * 120
    records.append({
        "ts": ts.isoformat(),
        "action_id": action, "tenant": ["acme", "birch", "cobalt"][user % 3],
        "user_id": f"u-{user:04d}", "feature": feature, "model": model,
        "attempt": attempt, "input_tokens": inp, "cache_write_tokens": cw,
        "cache_read_tokens": cr, "output_tokens": out,
        "reasoning_tokens": reasoning, "ttft_ms": round(ttft),
        "latency_ms": round(ttft + out * speed),
    })


def answer(ts, action, user):
    for attempt in (1, 2) if rng.random() < 0.03 else (1,):  # 3% retried
        cached = rng.random() < 0.9
        reasoning = rng.randint(300, 900)
        record(ts, action, user, "answer", "large", attempt,
               rng.randint(1_800, 4_500), 0 if cached else 1_770,
               1_770 if cached else 0, rng.randint(120, 320) + reasoning, reasoning)


def summary(ts, action, user):
    record(ts, action, user, "ticket_summary", "small", 1,
           rng.randint(800, 2_500), 0, 0, rng.randint(80, 200), 0)


def triage(ts, action, user):
    for step in range(rng.randint(3, 7)):  # one model call per agent step
        reasoning = rng.randint(200, 600)
        record(ts + timedelta(seconds=8 * step), action, user, "triage_agent",
               "large", 1, 50, 650, 2_300 + 650 * step,
               rng.randint(150, 400) + reasoning, reasoning)


start = datetime(2026, 10, 5)
for day in range(7):
    weekend = day >= 5
    plan = [(answer, 120 if weekend else 250), (summary, 40 if weekend else 150)]
    if day >= 3:  # the triage agent launched on Thursday 8 October
        plan.append((triage, 60))
    for make, count in plan:
        for _ in range(count):
            ts = start + timedelta(days=day, seconds=rng.randint(0, 86_399))
            make(ts, f"act-{rng.getrandbits(32):08x}", rng.randint(1, 300))
    if day >= 4:  # from Friday, one user's script calls the agent in a loop
        for n in range(90):
            ts = start + timedelta(days=day, hours=1, minutes=10 * n)
            triage(ts, f"act-{rng.getrandbits(32):08x}", 42)

records.sort(key=lambda r: r["ts"])
with open("usage.jsonl", "w", encoding="utf-8") as f:
    for n, r in enumerate(records, start=1):
        f.write(json.dumps({"request_id": f"req-{n:05d}", **r}) + "\n")
print(f"wrote {len(records):,} records; the first one:")
print(json.dumps({"request_id": "req-00001", **records[0]}, indent=2))
Terminal
python make_log.py
Expected output
wrote 4,897 records; the first one:
{
  "request_id": "req-00001",
  "ts": "2026-10-05T00:06:04",
  "action_id": "act-4e868ac3",
  "tenant": "cobalt",
  "user_id": "u-0284",
  "feature": "ticket_summary",
  "model": "small",
  "attempt": 1,
  "input_tokens": 808,
  "cache_write_tokens": 0,
  "cache_read_tokens": 0,
  "output_tokens": 197,
  "reasoning_tokens": 0,
  "ttft_ms": 377,
  "latency_ms": 1559
}

Prices live in their own file, in US dollars per million tokens, one row per model and one column per billing category. In a real project you copy them from the provider's pricing page and record the date; here they are example figures.

CSV · prices.csv
model,input,cache_write,cache_read,output
large,2.00,2.50,0.20,10.00
small,0.20,0.25,0.02,1.00

03. Step 2: Price every call

load_usage() reads the JSON Lines file and joins the price table on the model. Two checks come first, because both errors would otherwise produce a plausible but wrong report: a model with no price would be costed at zero, and reasoning tokens larger than output tokens mean a record was logged in another provider's convention. The merge uses validate="many_to_one", so a duplicated row in the price table raises an error instead of doubling every cost.

Python · costlog.py
"""Load usage records and price every request with a price table you pass in."""
import pandas as pd

TOKEN_COLUMNS = {  # usage column -> price column (US dollars per million tokens)
    "input_tokens": "input",
    "cache_write_tokens": "cache_write",
    "cache_read_tokens": "cache_read",
    "output_tokens": "output",
}


def load_usage(log_path: str, prices: pd.DataFrame) -> pd.DataFrame:
    df = pd.read_json(log_path, lines=True, convert_dates=["ts"])
    unknown = set(df["model"]) - set(prices["model"])
    if unknown:  # an unpriced model would silently cost $0
        raise ValueError(f"no price for models: {sorted(unknown)}")
    if (df["reasoning_tokens"] > df["output_tokens"]).any():
        raise ValueError("reasoning tokens are part of output tokens")
    df = df.merge(prices, on="model", how="left", validate="many_to_one")
    for tokens, price in TOKEN_COLUMNS.items():
        df[f"cost_{price}"] = df[tokens] * df[price] / 1_000_000
    df["cost"] = df[[f"cost_{p}" for p in TOKEN_COLUMNS.values()]].sum(axis=1)
    df["cost_reasoning"] = df["reasoning_tokens"] * df["output"] / 1_000_000
    df["prompt_tokens"] = df[list(TOKEN_COLUMNS)[:3]].sum(axis=1)
    return df.drop(columns=list(TOKEN_COLUMNS.values()))

The first report is the headline: what the week cost, per 1,000 requests and per 1,000 user actions, and how the cost splits across billing categories.

Python · totals.py
import pandas as pd

from costlog import load_usage

prices = pd.read_csv("prices.csv")  # example figures, not a quote
df = load_usage("usage.jsonl", prices)

total = df["cost"].sum()
actions = df["action_id"].nunique()
print(f"requests {len(df):,}  user actions {actions:,}  cost ${total:,.2f}")
print(f"per 1,000 requests ${1000 * total / len(df):.2f}"
      f"  per 1,000 actions ${1000 * total / actions:.2f}")
print("\nshare of cost by billing category:")
shares = df[["cost_input", "cost_cache_write", "cost_cache_read", "cost_output"]].sum()
print((shares / total).map("{:.1%}".format).to_string())
print(f"reasoning tokens alone: {df['cost_reasoning'].sum() / total:.1%}")
Terminal
python totals.py
Expected output
requests 4,897  user actions 2,830  cost $47.21
per 1,000 requests $9.64  per 1,000 actions $16.68

share of cost by billing category:
cost_input          21.6%
cost_cache_write    10.1%
cost_cache_read      5.0%
cost_output         63.3%
reasoning tokens alone: 41.1%

Output is 63% of the bill, and reasoning tokens alone are 41%: the biggest lever in this product is how much the large model thinks and writes, not the prompts. Cost per 1,000 actions is higher than per 1,000 requests because agent clicks make several calls. Choose the unit that matches what you sell or what a user does, and say which one you report.

04. Step 3: Cost and latency per feature

Group in two stages. First add up the calls of each user action, so that cost and time are measured per click. Then summarise the actions per feature: count, calls per action, total cost, cost per 1,000 actions and latency percentiles. Time to first token is a per-call measure, so it gets its own small table.

Python · by_feature.py
import pandas as pd

from costlog import load_usage

df = load_usage("usage.jsonl", pd.read_csv("prices.csv"))

per_action = df.groupby(["feature", "action_id"]).agg(
    calls=("request_id", "size"), cost=("cost", "sum"),
    seconds=("latency_ms", lambda ms: ms.sum() / 1000),
)
features = per_action.groupby("feature").agg(
    actions=("calls", "size"), calls_avg=("calls", "mean"),
    cost=("cost", "sum"), per_1k_actions=("cost", lambda c: 1000 * c.mean()),
    p50_s=("seconds", "median"), p95_s=("seconds", lambda s: s.quantile(0.95)),
)
share = features["cost"] / features["cost"].sum()
features = features.round(2).assign(share=share.map("{:.0%}".format))
print(features.sort_values("cost", ascending=False).to_string())

ttft = df.groupby("feature")["ttft_ms"].quantile([0.5, 0.95]).unstack()
print("\ntime to first token per call (ms):")
print(ttft.rename(columns={0.5: "p50", 0.95: "p95"}).round().to_string())
Terminal
python by_feature.py
Expected output
                actions  calls_avg   cost  per_1k_actions  p50_s  p95_s share
feature                                                                      
triage_agent        510       4.98  23.49           46.06  50.67  73.18   50%
answer             1490       1.03  23.33           15.66  12.09  16.66   49%
ticket_summary      830       1.00   0.38            0.46   1.27   1.61    1%

time to first token per call (ms):
                  p50    p95
feature                     
answer          540.0  633.0
ticket_summary  443.0  511.0
triage_agent    432.0  490.0

The agent, live for only four of the seven days, already costs as much as the answer feature, and each click costs about three times as much as an answer. It is also the slowest: the median click takes about 50 seconds of model time. Its time to first token is the lowest, though, because most of every agent prompt is read from the cache. Ticket summaries on the small model are 1% of the cost, so there is nothing to gain by optimising them.

05. Step 4: Cost per user and tenant

Python · by_user.py
import pandas as pd

from costlog import load_usage

df = load_usage("usage.jsonl", pd.read_csv("prices.csv"))
total = df["cost"].sum()

users = df.groupby(["user_id", "tenant"]).agg(
    actions=("action_id", "nunique"), requests=("request_id", "size"),
    cost=("cost", "sum"),
).sort_values("cost", ascending=False)
users["share"] = (users["cost"] / total).map("{:.1%}".format)
print(users.head(5).round(2).to_string())

top = users.head(max(1, len(users) // 100))  # the top 1% of users
print(f"\n{len(users)} users; the top {len(top)} account for "
      f"{top['cost'].sum() / total:.0%} of cost")
print(f"median user: ${users['cost'].median():.3f} for the week")

by_tenant = df.pivot_table(index="tenant", columns="feature", values="cost",
                           aggfunc="sum", margins=True, margins_name="total")
print("\ncost by tenant and feature ($):")
print(by_tenant.round(2).to_string())
Terminal
python by_user.py
Expected output
                actions  requests   cost  share
user_id tenant                                 
u-0042  acme        272      1360  12.56  26.6%
u-0215  cobalt       13        29   0.27   0.6%
u-0241  birch        20        24   0.26   0.5%
u-0120  acme         15        31   0.25   0.5%
u-0136  birch        13        21   0.25   0.5%

300 users; the top 3 account for 28% of cost
median user: $0.107 for the week

cost by tenant and feature ($):
feature  answer  ticket_summary  triage_agent  total
tenant                                              
acme       7.49            0.12         16.17  23.78
birch      7.98            0.13          3.95  12.06
cobalt     7.87            0.13          3.37  11.37
total     23.33            0.38         23.49  47.21

One user, u-0042 of tenant acme, accounts for 27% of the week's cost, more than a hundred times as much as the median user. The next users in the list are ordinary. This is the long tail from the previous lesson in real numbers, and it is invisible in any per-model total. The tenant pivot (margins=True adds the totals) shows the same thing from the billing side: acme's agent spend is four times that of the other tenants. If you charge customers by usage or by seat, this is the table that tells you whether a plan is still profitable.

06. Step 5: When did it change?

Python · daily.py
import pandas as pd

from costlog import load_usage

df = load_usage("usage.jsonl", pd.read_csv("prices.csv"))
df["day"] = df["ts"].dt.strftime("%m-%d %a")

daily = df.pivot_table(index="day", columns="feature", values="cost",
                       aggfunc="sum", fill_value=0)
daily["total"] = daily.sum(axis=1)
print(daily.round(2).to_string())

agent = df[df["feature"] == "triage_agent"]
heavy = agent["user_id"].eq("u-0042")
print(f"\ntriage_agent cost from u-0042: {agent.loc[heavy, 'cost'].sum():.2f}"
      f" of {agent['cost'].sum():.2f}")
per_call = agent.groupby(agent.groupby("action_id").cumcount() + 1)["cost"].mean()
print("mean cost of the n-th call in an agent run ($):")
print(per_call.round(4).to_string())
Terminal
python daily.py
Expected output
feature    answer  ticket_summary  triage_agent  total
day                                                   
10-05 Mon    3.91            0.07          0.00   3.97
10-06 Tue    3.79            0.07          0.00   3.86
10-07 Wed    3.98            0.07          0.00   4.05
10-08 Thu    4.02            0.07          2.84   6.93
10-09 Fri    3.87            0.07          6.95  10.89
10-10 Sat    1.88            0.02          6.89   8.79
10-11 Sun    1.88            0.02          6.80   8.71

triage_agent cost from u-0042: 12.56 of 23.49
mean cost of the n-th call in an agent run ($):
1    0.0089
2    0.0092
3    0.0091
4    0.0094
5    0.0094
6    0.0099
7    0.0100

The story is now complete. Spend was flat at about $4 a day, rose on Thursday when the agent launched, and jumped again on Friday when one script started running it every ten minutes; over the weekend the agent stays expensive while ordinary traffic halves. More than half of the agent's cost comes from that one user. The last table shows why the agent's calls barely get dearer as its conversation grows: the earlier turns are read from the cache at a tenth of the input price. Without caching, each later call would cost noticeably more than the first.

The report suggests three actions, each for a later lesson: talk to acme and put a per-user limit on the agent (lesson 5), check whether a smaller model or a router can serve the answer feature's easy questions with less reasoning (lesson 4), and keep the prompt cache working as the prompts change (lesson 3).

07. Common mistakes

08. Check your understanding

Practice check · 3 questions

Reading the report

Use the scripts and outputs of this lesson to answer. Each question has one best answer.

Q1. In by_feature.py, triage_agent costs $46.06 per 1,000 actions and makes 4.98 calls per action on average. About how much do 1,000 of its calls cost?
Q2. Your prices.csv has one row per model and no dates. On 1 November the provider halves the price of the small model, and you update the row. In December you rerun the October report. What happens to the October cost of the small model?
Q3. For triage_agent, the p95 time to first token is under half a second per call, but the p95 latency per action is about 73 seconds. What explains most of the gap?
Practice only: not graded, not saved, not evidence.

09. Apply it

Point these scripts at the baseline usage.jsonl of your own RAG API from the previous lesson.

  1. Adapt load_usage() to your field names and add an effective_from column to your price table, joined with pandas.merge_asof on the timestamp and grouped by model.
  2. Produce the before numbers you will compare against for the rest of this skill: cost per 1,000 queries, the split by billing category, and p50 and p95 latency per feature.
  3. Add one breakdown that your product needs and these scripts lack, such as cost per prompt version or per customer plan, and write down which lever its result points to.

10. Review prompt

Without looking back:

  1. Which two checks does load_usage() make before pricing anything, and what wrong report would each one prevent?
  2. Why does the per-feature report group by action first, and what would per-call numbers hide for the agent?
  3. How did the report separate the effect of a new feature from the effect of a single user?
  4. Why do later agent calls cost barely more than the first one in this log?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check