Add API cost tracking to admin dashboard
Track estimated Anthropic API costs per request across all Claude API call sites (recommender, analyze, artist-dive, generate-playlist, crate, rabbit-hole, playlist-fix, timeline, compatibility). Log token usage and estimated cost to the app logger. Aggregate costs in admin stats endpoint and display total/today costs and token usage in the admin dashboard.
This commit is contained in:
@@ -1,6 +1,9 @@
|
||||
import json
|
||||
import logging
|
||||
|
||||
import anthropic
|
||||
|
||||
api_logger = logging.getLogger("app")
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import select
|
||||
@@ -144,6 +147,12 @@ Return ONLY the JSON. Include exactly 5 recommendations."""
|
||||
messages=[{"role": "user", "content": prompt}],
|
||||
)
|
||||
|
||||
# Track API cost (Haiku: $0.80/M input, $4/M output)
|
||||
input_tokens = message.usage.input_tokens
|
||||
output_tokens = message.usage.output_tokens
|
||||
cost = (input_tokens * 0.80 / 1_000_000) + (output_tokens * 4 / 1_000_000)
|
||||
api_logger.info(f"API_COST|model=claude-haiku|input={input_tokens}|output={output_tokens}|cost=${cost:.4f}|user=system|endpoint=compatibility")
|
||||
|
||||
try:
|
||||
text = message.content[0].text.strip()
|
||||
if text.startswith("```"):
|
||||
|
||||
Reference in New Issue
Block a user