Files
AgentScript/agent/backend/app/services/metrics_service.py
T
HenryandClaude Code 26e13ff032 feat: Agent 工作区初始提交(源码+文档+Skills)
包含 CodeAgent 前后端源码、SKILLS、MCP、demo 代码与工作区文档。
排除依赖缓存、运行数据、备份与二进制附件,规则见 .gitignore。

Co-Authored-By: Claude Code <[email protected]>
2026-11-13 13:48:41 +08:00

398 lines
13 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
指标采集与统计服务
==================
【功能说明】
采集模型调用指标(token 消耗、延迟、成本)、任务执行指标、系统指标,
供监控仪表盘、成本统计、性能分析使用。
【技术选型理由】
1. 轻量 JSON 文件存储(单机场景够用,免额外基础设施);
2. 调用方只需一行 record_model_call(),无侵入;
3. 统计接口支持按日期/模型/维度聚合。
【实现思路】
- record_model_call():记录每次模型调用(token、延迟、模型名);
- record_task():记录任务执行(耗时、状态、步骤数);
- get_dashboard():聚合统计供仪表盘展示;
- 指标存 D:\\Agent\\agent\\data\\metrics.jsonl(追加式 JSONL)。
"""
from __future__ import annotations
import json
import logging
import threading
import time
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any
logger = logging.getLogger("agent.metrics")
# 指标文件
METRICS_FILE = Path(r"D:\Agent\agent\data\metrics.jsonl")
_lock = threading.Lock()
# 模型定价(每千 token,单位:元)—— 行业均价估算
MODEL_PRICING = {
"mimo-v2.6-pro": {"input": 0.002, "output": 0.008},
"mimo-v2.6-flash": {"input": 0.0005, "output": 0.002},
"glm-5.3": {"input": 0.002, "output": 0.008},
"glm-5.3-flash": {"input": 0.0005, "output": 0.002},
"default": {"input": 0.002, "output": 0.008},
}
def _get_price(model_name: str) -> dict:
"""获取模型定价(未匹配则用默认价)。"""
for key, price in MODEL_PRICING.items():
if key != "default" and key.lower() in model_name.lower():
return price
return MODEL_PRICING["default"]
def record_model_call(
model_name: str,
provider: str = "",
input_tokens: int = 0,
output_tokens: int = 0,
latency_ms: float = 0,
success: bool = True,
task_id: str = "",
) -> None:
"""
记录一次模型调用(异步追加,不阻塞主流程)。
【参数】provider:所属 Provider(如 ccswitch / zhipu),供按平台聚合用量。
【安全】写入失败只记日志,不影响业务。
"""
try:
price = _get_price(model_name)
cost = (input_tokens / 1000 * price["input"]) + (output_tokens / 1000 * price["output"])
entry = {
"type": "model_call",
"timestamp": datetime.now().astimezone().isoformat(timespec="seconds"),
"model": model_name,
"provider": provider,
"input_tokens": input_tokens,
"output_tokens": output_tokens,
"total_tokens": input_tokens + output_tokens,
"latency_ms": round(latency_ms, 1),
"success": success,
"cost": round(cost, 6),
"task_id": task_id,
}
with _lock:
METRICS_FILE.parent.mkdir(parents=True, exist_ok=True)
with open(METRICS_FILE, "a", encoding="utf-8") as f:
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
except Exception as exc: # noqa: BLE001
logger.warning("指标写入失败:%s", exc)
def record_task(
task_id: str,
duration_s: float = 0,
status: str = "done",
steps: int = 0,
project_id: str = "",
) -> None:
"""记录任务执行指标。"""
try:
entry = {
"type": "task",
"timestamp": datetime.now().astimezone().isoformat(timespec="seconds"),
"task_id": task_id,
"duration_s": round(duration_s, 1),
"status": status,
"steps": steps,
"project_id": project_id,
}
with _lock:
METRICS_FILE.parent.mkdir(parents=True, exist_ok=True)
with open(METRICS_FILE, "a", encoding="utf-8") as f:
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
except Exception as exc: # noqa: BLE001
logger.warning("指标写入失败:%s", exc)
def _read_metrics(hours: int = 24) -> list[dict]:
"""读取最近 N 小时的指标。"""
if not METRICS_FILE.exists():
return []
cutoff = datetime.now().astimezone() - timedelta(hours=hours)
results = []
try:
with open(METRICS_FILE, encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
try:
entry = json.loads(line)
ts = entry.get("timestamp", "")
if ts and datetime.fromisoformat(ts) >= cutoff:
results.append(entry)
except (json.JSONDecodeError, ValueError):
continue
except Exception as exc: # noqa: BLE001
logger.warning("读取指标失败:%s", exc)
return results
def get_dashboard(hours: int = 24) -> dict:
"""
获取监控仪表盘数据(最近 N 小时)。
【返回】
model_stats: 按模型聚合的 token/成本/延迟/调用次数
task_stats: 任务状态分布、平均耗时
totals: 总 token / 总成本 / 总调用次数
"""
entries = _read_metrics(hours)
model_calls = [e for e in entries if e.get("type") == "model_call"]
task_calls = [e for e in entries if e.get("type") == "task"]
# 按模型聚合
model_stats: dict[str, dict] = {}
provider_stats: dict[str, dict] = {}
for e in model_calls:
name = e.get("model", "unknown")
provider = e.get("provider") or "unknown"
# 按模型聚合
if name not in model_stats:
model_stats[name] = {
"model": name,
"provider": provider,
"calls": 0,
"input_tokens": 0,
"output_tokens": 0,
"total_tokens": 0,
"cost": 0.0,
"total_latency_ms": 0.0,
"success_count": 0,
}
m = model_stats[name]
m["calls"] += 1
m["input_tokens"] += e.get("input_tokens", 0)
m["output_tokens"] += e.get("output_tokens", 0)
m["total_tokens"] += e.get("total_tokens", 0)
m["cost"] += e.get("cost", 0)
m["total_latency_ms"] += e.get("latency_ms", 0)
if e.get("success"):
m["success_count"] += 1
# 按 Provider 聚合(痛点 1:多平台用量统一查看)
if provider not in provider_stats:
provider_stats[provider] = {
"provider": provider,
"calls": 0,
"input_tokens": 0,
"output_tokens": 0,
"total_tokens": 0,
"cost": 0.0,
"total_latency_ms": 0.0,
"success_count": 0,
"models": set(),
}
p = provider_stats[provider]
p["calls"] += 1
p["input_tokens"] += e.get("input_tokens", 0)
p["output_tokens"] += e.get("output_tokens", 0)
p["total_tokens"] += e.get("total_tokens", 0)
p["cost"] += e.get("cost", 0)
p["total_latency_ms"] += e.get("latency_ms", 0)
p["models"].add(name)
if e.get("success"):
p["success_count"] += 1
# 计算平均延迟
for m in model_stats.values():
m["avg_latency_ms"] = round(m["total_latency_ms"] / m["calls"], 1) if m["calls"] > 0 else 0
m["success_rate"] = round(m["success_count"] / m["calls"] * 100, 1) if m["calls"] > 0 else 0
m["cost"] = round(m["cost"], 4)
for p in provider_stats.values():
p["avg_latency_ms"] = round(p["total_latency_ms"] / p["calls"], 1) if p["calls"] > 0 else 0
p["success_rate"] = round(p["success_count"] / p["calls"] * 100, 1) if p["calls"] > 0 else 0
p["cost"] = round(p["cost"], 4)
p["models"] = sorted(p["models"])
# 任务统计
status_dist: dict[str, int] = {}
total_duration = 0
for e in task_calls:
s = e.get("status", "unknown")
status_dist[s] = status_dist.get(s, 0) + 1
total_duration += e.get("duration_s", 0)
avg_duration = round(total_duration / len(task_calls), 1) if task_calls else 0
# 汇总
total_cost = sum(m["cost"] for m in model_stats.values())
total_tokens = sum(m["total_tokens"] for m in model_stats.values())
total_calls = sum(m["calls"] for m in model_stats.values())
return {
"period_hours": hours,
"model_stats": sorted(model_stats.values(), key=lambda x: x["cost"], reverse=True),
"provider_stats": sorted(provider_stats.values(), key=lambda x: x["cost"], reverse=True),
"task_stats": {
"total": len(task_calls),
"status_distribution": status_dist,
"avg_duration_s": avg_duration,
},
"totals": {
"model_calls": total_calls,
"total_tokens": total_tokens,
"total_cost": round(total_cost, 4),
"avg_latency_ms": round(
sum(m["total_latency_ms"] for m in model_stats.values()) / total_calls, 1
)
if total_calls > 0
else 0,
},
}
# ========== 趋势分析与成本预测(B2:用量深度分析)==========
def get_trend(days: int = 7) -> dict:
"""
按天聚合用量趋势(最近 N 天)。
【返回】
daily: [{date, calls, tokens, cost, avg_latency}]
providers: 按 Provider 的每日趋势
summary: 日均用量、峰值
"""
# 读取最近 N 天的数据(hours = days * 24)
entries = _read_metrics(days * 24)
model_calls = [e for e in entries if e.get("type") == "model_call"]
# 按日期聚合
daily_map: dict[str, dict] = {}
provider_daily: dict[str, dict[str, dict]] = {}
for e in model_calls:
date = e.get("timestamp", "")[:10] # YYYY-MM-DD
if not date:
continue
provider = e.get("provider") or "unknown"
# 全局每日
if date not in daily_map:
daily_map[date] = {
"date": date,
"calls": 0,
"input_tokens": 0,
"output_tokens": 0,
"total_tokens": 0,
"cost": 0.0,
"total_latency_ms": 0.0,
}
d = daily_map[date]
d["calls"] += 1
d["input_tokens"] += e.get("input_tokens", 0)
d["output_tokens"] += e.get("output_tokens", 0)
d["total_tokens"] += e.get("total_tokens", 0)
d["cost"] += e.get("cost", 0)
d["total_latency_ms"] += e.get("latency_ms", 0)
# 按 Provider 每日
if provider not in provider_daily:
provider_daily[provider] = {}
if date not in provider_daily[provider]:
provider_daily[provider][date] = {
"date": date,
"calls": 0,
"tokens": 0,
"cost": 0.0,
}
pd = provider_daily[provider][date]
pd["calls"] += 1
pd["tokens"] += e.get("total_tokens", 0)
pd["cost"] += e.get("cost", 0)
# 转列表并排序
daily = sorted(daily_map.values(), key=lambda x: x["date"])
for d in daily:
d["cost"] = round(d["cost"], 4)
d["avg_latency_ms"] = round(d["total_latency_ms"] / d["calls"], 1) if d["calls"] else 0
# Provider 趋势
provider_trend = []
for prov, day_map in provider_daily.items():
days_list = sorted(day_map.values(), key=lambda x: x["date"])
for item in days_list:
item["cost"] = round(item["cost"], 4)
provider_trend.append({"provider": prov, "daily": days_list})
# 日均与峰值
if daily:
avg_cost = sum(d["cost"] for d in daily) / len(daily)
avg_calls = sum(d["calls"] for d in daily) / len(daily)
peak_day = max(daily, key=lambda x: x["cost"])
else:
avg_cost = avg_calls = 0
peak_day = None
return {
"period_days": days,
"daily": daily,
"provider_trend": provider_trend,
"summary": {
"avg_daily_cost": round(avg_cost, 4),
"avg_daily_calls": round(avg_calls, 1),
"peak_day": peak_day,
"total_days": len(daily),
},
}
def get_cost_forecast(days: int = 7) -> dict:
"""
基于最近 N 天用量预测未来 30 天成本。
【算法】按日均成本线性外推 + 最近 3 天加权平均(近期趋势权重高)。
"""
entries = _read_metrics(days * 24)
model_calls = [e for e in entries if e.get("type") == "model_call"]
daily_cost: dict[str, float] = {}
for e in model_calls:
date = e.get("timestamp", "")[:10]
if date:
daily_cost[date] = daily_cost.get(date, 0) + e.get("cost", 0)
if not daily_cost:
return {
"forecast_30d": 0,
"avg_daily_cost": 0,
"basis_days": 0,
"note": "暂无用量数据",
}
dates = sorted(daily_cost.keys())
total_cost = sum(daily_cost.values())
avg_daily = total_cost / len(dates)
# 最近 3 天加权平均(近期权重 0.6,历史 0.4)
recent_dates = dates[-3:]
recent_avg = sum(daily_cost[d] for d in recent_dates) / len(recent_dates)
weighted_daily = recent_avg * 0.6 + avg_daily * 0.4
forecast_30d = weighted_daily * 30
return {
"forecast_30d": round(forecast_30d, 2),
"avg_daily_cost": round(avg_daily, 4),
"recent_daily_cost": round(recent_avg, 4),
"weighted_daily_cost": round(weighted_daily, 4),
"basis_days": len(dates),
"date_range": {"start": dates[0], "end": dates[-1]},
}