方寸 Portal

AI Engineer Portal

Your personal operating system for career transition.

Private mode

Exercise

Build a token cost tracker

Build a Token Cost Tracker

Without explicit cost tracking, AI features develop cost problems silently. Token counts accumulate, model choices drift toward expensive options, and the first signal of a problem is a billing invoice. A cost tracker built into the application layer gives you visibility before the bill arrives.

What you are building

Build a TokenCostTracker class that:

  1. Records UsageRecord events (model, input tokens, output tokens, feature name, timestamp)
  2. Computes cost in USD using a configurable pricing table
  3. Provides a daily_report() that returns per-model and per-feature breakdowns for the last 24 hours
  4. Enforces a daily_budget_usd limit: raises BudgetExceededError when a new record would push the daily total over budget
  5. Provides a budget_remaining() method that returns how much budget is left today
  6. Is thread-safe (use threading.Lock)

Pricing table to support

# USD per 1M tokens
PRICING = {
    "claude-haiku-4-5":  {"input": 0.80,  "output": 4.00},
    "claude-sonnet-4-5": {"input": 3.00,  "output": 15.00},
    "gpt-4o-mini":       {"input": 0.15,  "output": 0.60},
    "gpt-4o":            {"input": 2.50,  "output": 10.00},
}

Why this matters

Cost tracking is operational hygiene, not optional infrastructure. Teams that do not track cost per feature cannot make informed model routing decisions, cannot detect when a prompt change makes output tokens grow, and cannot answer "why did costs jump 30% this week?" with data instead of guesses.

Llm Foundations / medium / Step 4 of 6

Practice stage

General drill

Hint

Keep the solution explicit and reviewable.

Success criteria

Make the solution explicit, debuggable, and easy to explain.

Review checklist

Review where the boundary is, what gets validated, and what would be hard to debug later.

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.