获取指定日期范围的 token 使用统计
(
start_date: str,
end_date: str,
group_by: str = "date"
)
| 164 | |
| 165 | |
| 166 | def get_usage_stats( |
| 167 | start_date: str, |
| 168 | end_date: str, |
| 169 | group_by: str = "date" |
| 170 | ) -> Dict[str, Any]: |
| 171 | """获取指定日期范围的 token 使用统计""" |
| 172 | if not TOKEN_LOG_PATH.exists(): |
| 173 | return {"error": "No token log found"} |
| 174 | |
| 175 | stats = defaultdict(lambda: { |
| 176 | "embedding_input": 0, |
| 177 | "embedding_output": 0, |
| 178 | "llm_input": 0, |
| 179 | "llm_output": 0, |
| 180 | "cost": 0, |
| 181 | "calls": 0, |
| 182 | }) |
| 183 | |
| 184 | with open(TOKEN_LOG_PATH, "r", encoding="utf-8") as f: |
| 185 | for line in f: |
| 186 | record = json.loads(line) |
| 187 | record_date = record.get("date", "") |
| 188 | |
| 189 | if not (start_date <= record_date <= end_date): |
| 190 | continue |
| 191 | |
| 192 | if _is_daily_aggregate_record(record): |
| 193 | key = record.get(group_by, record_date) if group_by == "date" else "aggregate" |
| 194 | s = stats[key] |
| 195 | s["embedding_input"] += int(record.get("embedding_tokens", 0)) |
| 196 | s["llm_input"] += int(record.get("llm_tokens", 0)) |
| 197 | s["calls"] += int(record.get("call_count", 0)) |
| 198 | continue |
| 199 | |
| 200 | key = record.get(group_by, "unknown") |
| 201 | s = stats[key] |
| 202 | |
| 203 | task_type = record.get("task_type", "") |
| 204 | input_tokens = record.get("input_tokens", 0) |
| 205 | output_tokens = record.get("output_tokens", 0) |
| 206 | model = record.get("model", "") |
| 207 | |
| 208 | s["calls"] += 1 |
| 209 | |
| 210 | if "embedding" in task_type.lower(): |
| 211 | s["embedding_input"] += input_tokens |
| 212 | s["embedding_output"] += output_tokens |
| 213 | else: |
| 214 | s["llm_input"] += input_tokens |
| 215 | s["llm_output"] += output_tokens |
| 216 | |
| 217 | s["cost"] += calculate_cost(task_type, model, input_tokens, output_tokens) |
| 218 | |
| 219 | return dict(stats) |
| 220 | |
| 221 | |
| 222 | def benchmark_one_day( |
no test coverage detected