cost_tracker¶
cost_tracker ¶
Cost tracking for LLM API calls.
Provides accurate cost tracking with thread safety and detailed breakdowns.
CostEntry
dataclass
¶
Single cost tracking entry.
CostTracker ¶
Detailed cost accounting with thread-safety and per-stage breakdowns.
Scope: Detailed financial tracking and reporting Pattern: Accumulator with thread-safe operations
Use CostTracker for: - Stage-by-stage cost breakdowns - Detailed entry logging (timestamp, model, tokens) - Thread-safe accumulation in concurrent execution - Cost reporting and analytics - Budget enforcement (via BudgetController)
NOT for: - Simple orchestration state (use ExecutionContext for that)
Why separate from ExecutionContext? - CostTracker = detailed accounting system (entries, breakdowns, thread-safety) - ExecutionContext = orchestration state (progress, session, timing) - Different concerns: accounting vs execution control
Thread Safety: - All methods protected by threading.Lock - Safe for concurrent LLM invocations
Example
tracker = CostTracker( input_cost_per_1k=Decimal("0.00015"), output_cost_per_1k=Decimal("0.0006") ) cost = tracker.add(tokens_in=1000, tokens_out=500, model="gpt-4o-mini") breakdown = tracker.get_stage_costs() # {"llm_invocation": Decimal("0.00045")}
See Also: - ExecutionContext: For orchestration-level state - BudgetController: For cost limit enforcement - docs/TECHNICAL_REFERENCE.md: Cost tracking architecture
Initialize cost tracker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_cost_per_1k
|
Decimal | None
|
Input token cost per 1K tokens |
None
|
output_cost_per_1k
|
Decimal | None
|
Output token cost per 1K tokens |
None
|
Source code in ondine/utils/cost_tracker.py
add ¶
add(tokens_in: int, tokens_out: int, model: str, timestamp: float, stage: str | None = None) -> Decimal
Add cost entry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens_in
|
int
|
Input tokens used |
required |
tokens_out
|
int
|
Output tokens used |
required |
model
|
str
|
Model identifier |
required |
timestamp
|
float
|
Timestamp of request |
required |
stage
|
str | None
|
Optional stage name |
None
|
Returns:
| Type | Description |
|---|---|
Decimal
|
Cost for this entry |
Source code in ondine/utils/cost_tracker.py
calculate_cost ¶
Calculate cost for given token counts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens_in
|
int
|
Input tokens |
required |
tokens_out
|
int
|
Output tokens |
required |
Returns:
| Type | Description |
|---|---|
Decimal
|
Total cost |
Source code in ondine/utils/cost_tracker.py
get_estimate ¶
Get cost estimate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rows
|
int
|
Number of rows processed |
0
|
Returns:
| Type | Description |
|---|---|
CostEstimate
|
CostEstimate object |
Source code in ondine/utils/cost_tracker.py
reset ¶
Reset all tracking.