Overview
TheCostTracker is a thread-safe singleton that accumulates costs across your agent’s execution. It works alongside the ledger to provide real-time cost visibility at multiple scopes:
- Session - Entire application lifetime
- Run - Single agent execution (e.g., one task)
- Action - Individual operations (automatically tracked by
@guarded_action)
Basic Usage
Adding costs manually
Run-level tracking
Automatic Cost Tracking
With @guarded_action
Costs are automatically tracked when you use@guarded_action:
With LLM instrumentation
LLM calls are automatically tracked when instrumentation is enabled:Action Statistics
Track per-action metrics:Complete Snapshot
Get all cost data at once:Multi-Run Example
Typical pattern for agents that process multiple tasks:Budget Enforcement
Use with PolicyEngine for budget limits:Cost backends
CostTracker stores its counters in a pluggable backend. Pick one based on where
your budgets need to hold:
An unrecognised backend name, or a missing path or key, raises
ValueError
at startup instead of quietly falling back to per-process memory.
Platform budgets (RemoteCostBackend)
With the remote backend, every guarded action reserves its cost_usd against
the platform before it runs, via
POST /api/v1/budgets/reserve. The platform checks your
organization’s monthly budget and, if a group is set, that group’s budget, in one
atomic step. A refused reservation raises BudgetExceededError and the action
does not run.
- Holds last 15 minutes and are settled at ingest against the action’s real
cost_usd. - Local
session_budget/run_budget/action_budgetsare not evaluated with this backend; the platform is authoritative. CostTracker.get_session_total()and friends still work, reading a local mirror of the reservations this process made.- If the platform is unreachable, the action is blocked with
NetworkErroronly under strictfail_closed. Under the defaultfail_closed_writesand underfail_open, the SDK logs a warning and the action proceeds without a hold.
Thread Safety
CostTracker is thread-safe and can be used in multi-threaded applications:
Resetting
Reset run only
Reset everything
Integration with Remote Sync
When using remote sync, costs are automatically sent to the platform:Common Patterns
Cost-aware agent loop
Cost reporting
Cost comparison
Best Practices
Troubleshooting
Costs not accumulating
Make sure you’re callingadd_cost() or using instrumented operations:
Run total seems wrong
Check if you forgot to reset between runs:Thread safety issues
CostTracker is thread-safe by design, but ensure you’re using the class methods, not creating instances:
See Also
- Instrumentation - Using @guarded_action for automatic cost tracking
- LLM Integrations - Automatic LLM cost tracking
- Policies - Enforcing budget limits
- Analytics - Visualizing costs in the console
