AI Engineer Portal
Your personal operating system for career transition.
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:
- Records
UsageRecordevents (model, input tokens, output tokens, feature name, timestamp) - Computes cost in USD using a configurable pricing table
- Provides a
daily_report()that returns per-model and per-feature breakdowns for the last 24 hours - Enforces a
daily_budget_usdlimit: raisesBudgetExceededErrorwhen a new record would push the daily total over budget - Provides a
budget_remaining()method that returns how much budget is left today - 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
General drill
Keep the solution explicit and reviewable.
Make the solution explicit, debuggable, and easy to explain.
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.