IP-Safe / src /utils /cost_tracker.py
Yash
Claude Sonnet 4.6
Fix all 47 ruff lint errors to pass CI
74888a1
Raw History Blame Contribute Delete
5.18 kB
"""Cost tracking for LLM API calls."""
from typing import Dict, List
from loguru import logger
import json
from datetime import datetime
class CostTracker:
"""Track API costs across all providers."""
# Pricing (Mar 2026) - per million tokens
PRICING = {
"gpt-5.2": {"input": 10.0, "output": 40.0}, # GPT-5.2 thinking model
"gemini-3.1-pro-preview": {
"input": 2.50,
"output": 15.0,
}, # Gemini 3.1 Pro with thinking
"claude-opus-4-6": {
"input": 15.0,
"output": 75.0,
}, # Claude Opus 4.6 (includes thinking tokens)
}
def __init__(self):
"""Initialize cost tracker."""
self.total_cost = 0.0
self.cost_by_model = {}
self.request_count = 0
self.detailed_log = []
def add_analysis_cost(self, model_results: List[Dict]):
"""
Add costs from model analysis results.
Args:
model_results: List of results from multiple models
"""
for result in model_results:
if "error" not in result:
model = result.get("model", "unknown")
input_tokens = result.get("input_tokens", 0)
output_tokens = result.get("output_tokens", 0)
cost = self.calculate_cost(model, input_tokens, output_tokens)
self.total_cost += cost
self.cost_by_model[model] = self.cost_by_model.get(model, 0.0) + cost
self.request_count += 1
self.detailed_log.append(
{
"timestamp": datetime.now().isoformat(),
"model": model,
"input_tokens": input_tokens,
"output_tokens": output_tokens,
"cost": cost,
}
)
def calculate_cost(
self, model: str, input_tokens: int, output_tokens: int
) -> float:
"""
Calculate cost for a single API call.
Args:
model: Model name
input_tokens: Number of input tokens
output_tokens: Number of output tokens
Returns:
Cost in USD
"""
pricing = self.PRICING.get(model, {"input": 0, "output": 0})
# Convert to per-token pricing
input_cost = (input_tokens / 1_000_000) * pricing["input"]
output_cost = (output_tokens / 1_000_000) * pricing["output"]
return input_cost + output_cost
def estimate_total_cost(
self, num_images: int, models: List[str] = None
) -> Dict[str, float]:
"""
Estimate total cost for analyzing N images.
Args:
num_images: Number of images to analyze
models: List of model names (defaults to all configured models)
Returns:
Dictionary with cost breakdown by model
"""
if models is None:
models = list(self.PRICING.keys())
estimates = {}
# Assumptions:
# - Image ~= 800 tokens (vision tokens)
# - Prompt ~= 600 tokens
# - Response ~= 1000 tokens (JSON with reasoning)
input_tokens_per_image = 1400
output_tokens_per_image = 1000
for model in models:
cost_per_image = self.calculate_cost(
model, input_tokens_per_image, output_tokens_per_image
)
total = cost_per_image * num_images
estimates[model] = total
estimates["total"] = sum(estimates.values())
return estimates
def get_summary(self) -> Dict:
"""
Get cost summary.
Returns:
Dictionary with cost statistics
"""
return {
"total_cost": round(self.total_cost, 2),
"cost_by_model": {
model: round(cost, 2) for model, cost in self.cost_by_model.items()
},
"request_count": self.request_count,
"avg_cost_per_request": round(
self.total_cost / max(self.request_count, 1), 4
),
}
def save_report(self, output_path: str):
"""
Save detailed cost report to file.
Args:
output_path: Path to save JSON report
"""
report = {
"summary": self.get_summary(),
"detailed_log": self.detailed_log,
"pricing_table": self.PRICING,
}
with open(output_path, "w") as f:
json.dump(report, f, indent=2)
logger.info(f"Cost report saved to {output_path}")
def print_summary(self):
"""Print cost summary to console."""
summary = self.get_summary()
print("\n" + "=" * 50)
print("COST SUMMARY")
print("=" * 50)
print(f"Total Cost: ${summary['total_cost']:.2f}")
print(f"Requests: {summary['request_count']}")
print(f"Average per Request: ${summary['avg_cost_per_request']:.4f}")
print("\nCost by Model:")
for model, cost in summary["cost_by_model"].items():
print(f" {model}: ${cost:.2f}")
print("=" * 50 + "\n")