Sub topic 9
Calculating metrics with code, not with the model
This chapter assumes you can read basic Python, know the marketing metrics click-through rate (CTR), cost per click (CPC) and cost per acquisition (CPA), and have seen the agent loop from earlier chapters. You will build a deterministic metrics tool, learn the errors that most often corrupt marketing numbers, and wire the tool into an agent.
Why the model should not do the arithmetic
A language model predicts likely text. It does not run a calculator. Given 250 clicks and 15,000 impressions, it will often produce a plausible CTR, but it can be wrong by a digit, round inconsistently, or add up a long column incorrectly. These errors look just like correct answers, so nobody notices them.
Code has none of these problems. The same input always gives the same output, you can test it, and you can read it. The division of labor is:
- The tool computes every number.
- The model decides which tool to call, passes the arguments, and writes prose around the returned values.
This is the main defense against the hallucination problems covered earlier in the tutorial. It removes one whole class of unsupported claims before the verification stage has to look for them.
A deterministic metrics tool
The function below takes per-campaign rows and returns totals and ratios.
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))Running it prints:
{'impressions': 15000, 'clicks': 250, 'spend': 210.0, 'conversions': 12, 'ctr': 0.0167, 'cpc': 0.84, 'cpa': 17.5}Four design choices in this function matter for agents.
Sum first, then divide
The function adds the raw counts across campaigns and divides once. The tempting alternative is to compute a CTR per campaign and average them. Here campaign one has a CTR of 0.02 and campaign two has 0.01. Their mean is 0.015, but the true blended CTR is 250 / 15,000 = 0.0167. The average of ratios gives a small campaign the same weight as a large one, so it misstates the portfolio. The same applies to CPC and CPA. Ratios are never summed or averaged; they are always recomputed from totals.
Zero denominators return None
A campaign that has spent money but made no conversions has no CPA. Raising ZeroDivisionError would crash the agent loop. Returning 0 would be worse, because a CPA of zero reads as "free conversions." None becomes null in JSON and says "undefined." Your prompt should then tell the model to write "no conversions yet" rather than invent a number.
Rounding happens once, at the end
Rounding each row before summing accumulates error. Round only in the returned values, and keep the raw totals available for later calculations.
Rates are fractions
CTR is returned as 0.0167, not 1.67. Pick one convention, document it in the tool description, and keep it everywhere. If the model sees 0.0167 in one tool and 1.67 in another, it may mix them up when writing prose.
Period-over-period change
Reports compare periods constantly. Give the agent a tool for that too, so it never subtracts numbers in its head.
def pct_change(current, previous):
"""Percent change from previous to current, or None if undefined."""
if current is None or previous is None or previous == 0:
return None
return round((current - previous) / previous * 100, 1)
print(pct_change(0.84, 0.70)) # 20.0
print(pct_change(17.5, 0)) # None
print(pct_change(None, 12.0)) # NoneThe function accepts None as input because upstream metrics can be undefined. Propagating None keeps an undefined value from turning into a misleading number further along.
Validate inputs at the tool boundary
The model builds the arguments, and sometimes it builds them badly: a missing key, a string where a number belongs, or rows copied from the wrong source. Real exports also contain surprises, such as clicks that exceed impressions because of different attribution windows. A validator catches these problems and returns them in a form the model can act on.
This snippet reuses campaign_metrics from above.
REQUIRED = ("impressions", "clicks", "spend", "conversions")
def validate_rows(rows):
"""Return a list of human-readable problems; empty means the rows are usable."""
if not isinstance(rows, list) or not rows:
return ["rows must be a non-empty list"]
problems = []
for i, row in enumerate(rows):
bad = False
for key in REQUIRED:
value = row.get(key) if isinstance(row, dict) else None
if isinstance(value, bool) or not isinstance(value, (int, float)) or value < 0:
problems.append(f"row {i}: {key} is missing, non-numeric or negative")
bad = True
if not bad and row["clicks"] > row["impressions"]:
problems.append(f"row {i}: clicks exceed impressions")
return problems
def metrics_tool(rows):
"""Tool entry point: validate, then compute. Always returns a dict."""
problems = validate_rows(rows)
if problems:
return {"error": "invalid input", "details": problems}
return campaign_metrics(rows)
print(metrics_tool([{"impressions": 100, "clicks": 500, "spend": 10, "conversions": 1}]))
print(metrics_tool([{"impressions": 100, "clicks": 5, "spend": 10, "conversions": 1}]))The first call returns an error object listing the problem. The second returns the metrics. An error returned as data goes back to the model in the loop, which can fix its arguments and retry. An uncaught exception ends the run instead.
To register the tool, add it to the dictionary the loop uses:
tools = {"campaign_metrics": metrics_tool, "pct_change": pct_change}The key is the name the model uses in its tool request, so choose names that say what the tool does.
Describe the tool so the model uses it correctly
The model only knows a tool through its description. A good description states:
- what the tool computes, and the exact formula for each ratio;
- the input shape, with field names and units (currency, fraction versus percent);
- what
nullmeans in the output; - when not to use it, for example "do not use for per-campaign comparisons; call once per campaign."
Vague descriptions produce wrong calls, such as passing percentages where fractions are expected.
Common errors
| Error | Symptom | Fix |
|---|---|---|
| Averaging per-campaign ratios | Blended CTR or CPA does not match the platform's total | Sum numerators and denominators, then divide once |
| Returning 0 for undefined ratios | CPA of 0.00 in the report | Return `None` and instruct the model on wording |
| Mixing percent and fraction | CTR reads 1.67 in one place and 0.0167 in another | One convention, stated in the tool description |
| Rounding early | Totals drift by a few cents | Round only the returned values |
| Mixed currencies or time zones | Spend does not reconcile with the ad platform | Normalize in the data-loading step, before the tool |
| Trusting unvalidated rows | Impossible values such as clicks above impressions pass silently | Validate and return an error object |
For money, floating-point sums can drift by tiny amounts. Rounding to two decimals at the end is enough for reporting. If you do bookkeeping or reconciliation, use decimal.Decimal instead.
Test the tool like any other code
Because the tool is plain Python, you can test it without a model. Check at least these cases:
- A known input with a hand-calculated answer, such as the two-row example above.
- A zero denominator for each ratio.
- A single-row input, which should equal that row's own ratios.
- Splitting the rows into two groups, computing each, and confirming the totals add up.
These tests run in milliseconds and never change. That is the benefit of moving arithmetic out of the model.
Exercise
A report has two campaigns. Campaign A: 4,000 impressions, 80 clicks. Campaign B: 1,000 impressions, 5 clicks. A teammate computes each CTR and averages them to report a blended CTR. What blended CTR should the tool return, and why does the teammate's number differ? What should the tool return for CPA if both campaigns have zero conversions?
Show answer
Campaign A's CTR is 0.02 and Campaign B's is 0.005, so the teammate's average is 0.0125. The correct blended CTR sums first: 85 clicks / 5,000 impressions = 0.017. The average gives the small campaign the same weight as the large one. With zero total conversions, CPA is undefined, so the tool returns None (null in JSON), not 0.