AI Engineer Portal
Your personal operating system for career transition.
Exercise
Cost-tracking middleware for agent tool calls
Cost-Tracking Middleware for Agent Tool Calls
Agent systems can burn through API budgets fast. Every LLM call, every tool invocation, every retry costs tokens and time. Without cost tracking, you discover overspending after the invoice arrives. Cost-tracking middleware wraps every tool call to record token usage, latency, and estimated cost in real time, with optional budget enforcement that stops the agent before it exceeds a limit.
What you are building
Create a CostTracker middleware class that:
- Wraps tool calls — intercepts every tool invocation to measure and record metrics before and after execution.
- Tracks per-call metrics — token usage (input + output), latency in milliseconds, estimated cost in USD.
- Maintains running totals — cumulative tokens, cost, and call count, grouped by tool name.
- Enforces budgets — if a configurable budget (in USD or tokens) would be exceeded by the next call, raise a
BudgetExceededErrorinstead of executing. - Provides a summary — return a structured cost report with per-tool and aggregate breakdowns.
Why this matters
In production, cost visibility is not optional. A runaway agent loop that calls GPT-4 in a retry spiral can burn hundreds of dollars in minutes. Cost tracking middleware is the standard pattern for: (1) real-time budget enforcement, (2) per-request cost attribution for billing, (3) identifying expensive tool calls for optimization, and (4) comparing agent configurations by cost efficiency.
This is the kind of infrastructure every AI team builds early and never removes.
Constraints
- The middleware must work with both sync and async tool functions.
- Token counts come from the tool's return value (assume tools return a dict with an optional
usagefield). - The pricing table maps model/tool names to per-1K-token rates.
- Budget enforcement must check BEFORE executing, not after (to prevent overspend).
- All tracking data must be thread-safe for concurrent agent execution.
Agents / intermediate / Step 8 of 8
Agent architecture patterns
Focus on explicit control surfaces — function schemas, state machines, and structured outputs. Agents are most useful when the task requires dynamic tool selection or multi-step reasoning. Start with the simplest pattern (single tool call) before reaching for ReAct loops.
This is the end of the current mini-sequence.
- - Tools return structured, typed responses
- - Agent completes the task within a bounded number of steps
- - All tool calls include error handling and retries
- - Memory/state management prevents unbounded context growth
- - Tool schemas validate inputs and handle errors gracefully
- - Agent loop has explicit termination conditions
- - State is serializable and inspectable between steps
- - Cost and token usage are tracked per invocation
- - Fallback behavior exists for tool call failures
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.