Summarise API calls per model with named groupby aggregations
A usage logger records every LLM call. Failed calls have no latency (NaN) but still count as calls, so the summary must treat them carefully.
Write model_stats(df) where df has columns model (str), latency_ms (float, NaN for failed calls) and tokens (int).
Return a DataFrame with columns exactly [model, n_calls, mean_latency, total_tokens], one row per model, sorted by model ascending, with a plain 0..n-1 index.
- n_calls: number of rows for that model, failed calls included.
- mean_latency: mean of latency_ms ignoring NaN (NaN if the model has no successful call).
- total_tokens: sum of tokens.
def model_stats(df)Example
model 'a' with latencies [100, NaN] and tokens [10, 0] gives n_calls 2, mean_latency 100.0, total_tokens 10.
Understand the idea
A call log for an LLM gateway has one row per request. Failed calls have no latency (NaN) but are still calls, so the count must include them while the mean latency must skip them. In pandas, the 'size' aggregation counts every row, while 'count' skips NaN, which would quietly drop failures. Named aggregation lets you build several well-named output columns in one groupby. Worked example: model a has latencies [100, NaN] and tokens [10, 0]; model b has [50, 70] and [5, 5]. a: n_calls 2, mean_latency 100.0 (NaN ignored), total_tokens 10. b: n_calls 2, mean_latency 60.0, total_tokens 10. A model with only failed calls gets mean_latency NaN. Rule: group by model; n_calls = number of rows; mean_latency = mean of latency_ms skipping NaN; total_tokens = sum of tokens; output columns exactly [model, n_calls, mean_latency, total_tokens], sorted by model, with a fresh 0 to n-1 index (reset the group index into a column). This is a typical first summary in LLM observability notebooks.