70 行
2.5 KiB
Python
70 行
2.5 KiB
Python
"""用量统计:从对话消息的 usage 元信息聚合(配额/缓存命中率)。
|
|
数据量小时实时聚合;量大后可改为定时物化聚合表(本轮先实时)。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
from sqlalchemy import select
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.models.message import Message
|
|
|
|
|
|
class UsageService:
|
|
def __init__(self, session: Session):
|
|
self.session = session
|
|
|
|
def summary(self, user_id: int, days: int = 7) -> dict:
|
|
since = datetime.now(timezone.utc) - timedelta(days=days)
|
|
rows = list(
|
|
self.session.execute(
|
|
select(Message).where(
|
|
Message.user_id == user_id,
|
|
Message.role == "assistant",
|
|
Message.created_at >= since,
|
|
)
|
|
).scalars()
|
|
)
|
|
total_prompt = total_completion = total_cache = 0
|
|
calls = 0
|
|
per_day: dict[str, dict] = {}
|
|
for m in rows:
|
|
if not m.meta:
|
|
continue
|
|
try:
|
|
meta = json.loads(m.meta)
|
|
except Exception:
|
|
continue
|
|
usage = meta.get("usage")
|
|
if not usage:
|
|
continue
|
|
calls += 1
|
|
p = int(usage.get("prompt_tokens", 0) or 0)
|
|
c = int(usage.get("completion_tokens", 0) or 0)
|
|
cache = 0
|
|
# DeepSeek: prompt_cache_hit_tokens(命中);部分厂商无此字段
|
|
cache = int(usage.get("prompt_cache_hit_tokens", 0) or 0)
|
|
total_prompt += p
|
|
total_completion += c
|
|
total_cache += cache
|
|
day = m.created_at.strftime("%Y-%m-%d") if m.created_at else "unknown"
|
|
d = per_day.setdefault(day, {"prompt": 0, "completion": 0, "cache": 0, "calls": 0})
|
|
d["prompt"] += p
|
|
d["completion"] += c
|
|
d["cache"] += cache
|
|
d["calls"] += 1
|
|
cache_rate = round(total_cache / total_prompt * 100, 1) if total_prompt else 0.0
|
|
return {
|
|
"user_id": user_id,
|
|
"days": days,
|
|
"calls": calls,
|
|
"total_tokens": total_prompt + total_completion,
|
|
"prompt_tokens": total_prompt,
|
|
"completion_tokens": total_completion,
|
|
"cache_hit_tokens": total_cache,
|
|
"cache_rate_pct": cache_rate,
|
|
"per_day": [{"date": k, **v} for k, v in sorted(per_day.items())],
|
|
}
|