Sub topic 9
Calculating metrics with code, not with the model
This chapter assumes you can read basic Python, know the marketing metrics impressions, clicks, spend and conversions, and understand how an agent calls tools. It shows why an agent should hand arithmetic to code and how to build a tool that does it safely.
Why the model should not do the math
A language model predicts likely text. It does not run a calculator. Given a table of campaign rows, it may produce a click-through rate that looks right but is off by a digit. The error is also hard to spot, because the surrounding sentence reads fluently.
Code gives the same answer every time for the same input. So the split of work is simple:
- The model decides which tool to call and explains the result.
- The code sums, divides and rounds.
The model never sees a division it has to perform. It only reads the numbers the tool returns.
The three core ratios
| Metric | Formula | Meaning |
|---|---|---|
| CTR (click-through rate) | clicks / impressions | Share of views that led to a click |
| CPC (cost per click) | spend / clicks | Average price of one click |
| CPA (cost per acquisition) | spend / conversions | Average price of one conversion |
Each one divides by a count that can be zero. A new campaign may have no clicks yet. If the code divides anyway, Python raises ZeroDivisionError and the agent loop stops. If the code returns 0, the report claims a cost of zero, which is false. The safer answer is None, which means "not defined".
A deterministic metrics tool
The function below totals the rows first, then computes the ratios from the totals. This matters: averaging each campaign's CTR would weight a campaign with 50 impressions the same as one with 10,000.
def campaign_metrics(rows):
"""Compute standard performance metrics from per-campaign rows."""
impressions = sum(r["impressions"] for r in rows)
clicks = sum(r["clicks"] for r in rows)
spend = sum(r["spend"] for r in rows)
conversions = sum(r["conversions"] for r in rows)
return {
"impressions": impressions,
"clicks": clicks,
"spend": round(spend, 2),
"conversions": conversions,
"ctr": round(clicks / impressions, 4) if impressions else None,
"cpc": round(spend / clicks, 2) if clicks else None,
"cpa": round(spend / conversions, 2) if conversions else None,
}
rows = [
{"impressions": 10000, "clicks": 200, "spend": 150.0, "conversions": 10},
{"impressions": 5000, "clicks": 50, "spend": 60.0, "conversions": 2},
]
print(campaign_metrics(rows))For these rows the totals are 15,000 impressions, 250 clicks, 210.00 spend and 12 conversions. That gives a CTR of 0.0167, a CPC of 0.84 and a CPA of 17.5.
How the agent uses it
The agent registers campaign_metrics as a tool. When asked "How did last month perform?", the model fetches rows with a data tool, then calls the metrics tool with those rows. The returned dictionary goes back into the conversation. The model then writes the summary from those values.
Common errors
- Letting the model compute "just a quick percentage". Put every calculation in a tool, including period-over-period change.
- Returning 0 for an undefined ratio. Use
Noneand tell the model in the tool description thatNonemeans "not computable". - Rounding too early. Round only the final output, as the function does, so totals stay exact.
- Mixed units. Check that spend is in one currency and the date range is the same across rows before summing.
- Silent bad input. A row missing a key raises
KeyError. Let the error surface or return a clear error message, so the agent does not guess.
Exercise
A campaign has 0 conversions and 40 clicks at 30.00 spend. What should campaign_metrics return for cpc and cpa, and why?
Show answer
cpc is 0.75 (30.00 / 40). cpa is None, because dividing by zero conversions is undefined. Returning None keeps the agent loop running and prevents the report from claiming a cost of zero.
Exercise
Two campaigns have CTRs of 2% (100 impressions) and 1% (10,000 impressions). Why is the combined CTR not 1.5%?
Show answer
The combined CTR is total clicks over total impressions: (2 + 100) / 10,100, about 1.01%. Averaging the two ratios ignores that the second campaign has 100 times more impressions.