方寸 Portal

AI Engineer Portal

Your personal operating system for career transition.

Private mode

Exercise

Compute per-model cost and usage summaries from request logs

Compute Per-Model Cost and Usage Summaries from Request Logs

Every AI service needs basic cost visibility: which models are being used, how many tokens are flowing through each one, and what that costs. These summaries come from request logs — JSONL files or database rows that record per-request token counts. The transformation from raw logs to an actionable cost summary is a standard data engineering task.

What to build

Implement summarize_usage(records: list[dict]) -> dict that takes a list of request log records and returns a nested summary:

{
  "gpt-4o-mini": {
    "request_count": 120,
    "input_tokens": 48000,
    "output_tokens": 24000,
    "total_tokens": 72000,
    "estimated_cost_usd": 0.0216,
    "avg_latency_ms": 340.5,
    "error_count": 3,
  },
  "claude-3-5-haiku": { ... },
  "_totals": {
    "request_count": ...,
    "total_tokens": ...,
    "estimated_cost_usd": ...,
  }
}

Each input record has the shape:

{
  "model": "gpt-4o-mini",
  "input_tokens": 400,
  "output_tokens": 200,
  "latency_ms": 320,
  "status": "ok",  # or "error"
}

Pricing table to use

ModelInput (per 1M tokens)Output (per 1M tokens)
gpt-4o-mini$0.15$0.60
gpt-4o$2.50$10.00
claude-3-5-haiku$0.80$4.00
claude-3-7-sonnet$3.00$15.00

For unknown models, use $1.00 / $5.00 as defaults.

Why this matters

Cost attribution is the first step toward cost optimization. Without per-model summaries, you cannot answer "why did our AI spend increase 40% this month?" or "is the expensive model being used for tasks a cheaper one could handle?" Build this once and run it weekly.

Constraints

  • Handle missing or None token fields gracefully (treat as 0).
  • Skip records where model is missing.
  • Include a _totals key that aggregates all models.

Data Transformation / medium / Step 14 of 16

Practice stage

Transform and summarize data safely

Hint

Think like an evaluation or trace pipeline: group clearly, preserve the data story, and make edge cases visible instead of clever.

Success criteria
  • - Handles missing or noisy records predictably
  • - Produces summary output that is easy to inspect
  • - Would be safe to rerun in a script workflow
Review checklist
  • - Do grouped metrics stay readable?
  • - Would malformed rows be debuggable?
  • - Did I choose names that explain the transformation?

Practice

Generate a variation

Generate a new exercise variation to deepen understanding or practice a related concept.

Attempt history

Recent submissions

Before you submit, decide what a strong answer should make obvious to the reviewer.

No attempts yet.