AI Engineer Portal
Your personal operating system for career transition.
Private mode
Exercise
Build a cost monitoring middleware
Build a Cost Monitoring Middleware
Without per-request cost tracking, you discover cost problems on the monthly invoice. A cost monitoring middleware intercepts every LLM call, records token usage, computes the dollar cost, and raises an alert before a budget is exceeded.
What to build
CostMonitor(llm_fn, budget_usd: float, model_prices: dict):
model_pricesformat:{"gpt-4o": {"input": 0.0025, "output": 0.01}}(per 1K tokens)async call(model, input_tokens, output_tokens) -> dict— calls llm_fn, returns result with_cost_usd- Raise
BudgetExceededErrorBEFORE making the call if it would exceed the budget get_report() -> dict—total_usd,budget_usd,budget_remaining_usd,by_model
Constraints
llm_fnis async:(model, input_tokens, output_tokens) -> dict- Standard library only
- Unknown models raise
ValueError
Api Async / medium / Step 16 of 23
Practice stage
Async and provider control
Hint
Make waiting behavior explicit. Timeouts, retries, and concurrency limits matter more than squeezing everything into one helper.
Success criteria
- - Uses async boundaries coherently
- - Makes timeout and retry decisions legible
- - Would be maintainable under provider instability
Review checklist
- - Is timeout behavior explicit?
- - Is retryable failure separate from terminal failure?
- - Would logs reveal what actually timed out?
Related lessons
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.