//! 用量: every model call (a bot's step, its quick model, a summary, a check, a goal's judge…) is //! written down as one line in `usage/YYYY-MM.jsonl` in the data folder — when, which provider //! and model, which bot and what for (from the request's session name, e.g. `anybot-bot-12`, //! `anybot-check-12`), and the tokens it used, with the cost when the provider says it. //! 「/usage」 sums the last day and the last week, by bot and by model. Like grok-build's //! `grok usage`. Nothing here guesses prices: a cost shows only when the provider gave one. use crate::providers::{ChatRequest, Usage}; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use std::io::Write; use std::path::PathBuf; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Entry { /// When (ms). pub at: i64, pub provider: String, pub model: String, /// The request's session name: whose call and what for. #[serde(default)] pub session: String, #[serde(flatten)] pub usage: Usage, } impl Entry { /// The bot it was for (0: none), and what for: a step, a check, a goal's judge… pub fn whose(&self) -> (u64, &'static str) { let s = self.session.as_str(); for (prefix, what) in [("anybot-bot-", "回合"), ("anybot-check-", "發布前檢查"), ("anybot-goal-", "目標檢查"), ("anybot-btw-", "支線")] { if let Some(id) = s.strip_prefix(prefix).and_then(|r| r.parse::().ok()) { return (id, what); } } (0, "其他") } } fn dir() -> PathBuf { crate::model::State::path().parent().map(|p| p.to_path_buf()).unwrap_or_else(std::env::temp_dir).join("usage") } fn file_for(at: chrono::DateTime) -> PathBuf { dir().join(format!("{}.jsonl", at.format("%Y-%m"))) } /// Write down what one model call used (nothing when the provider said nothing). pub fn note(req: &ChatRequest, u: &Usage) { if u.is_empty() { return; } let now = chrono::Local::now(); let e = Entry { at: now.timestamp_millis(), provider: req.kind.label().to_string(), model: req.model.clone(), session: req.session.clone(), usage: *u }; let _ = std::fs::create_dir_all(dir()); if let (Ok(mut f), Ok(line)) = (std::fs::OpenOptions::new().create(true).append(true).open(file_for(now)), serde_json::to_string(&e)) { let _ = writeln!(f, "{line}"); } } /// What was written down since `since` (ms): this month's file and last month's. pub fn since(since: i64) -> Vec { let now = chrono::Local::now(); let last_month = now.checked_sub_months(chrono::Months::new(1)).unwrap_or(now); let mut out = vec![]; for f in [file_for(last_month), file_for(now)] { for line in std::fs::read_to_string(f).unwrap_or_default().lines() { if let Ok(e) = serde_json::from_str::(line) { if e.at >= since { out.push(e); } } } } out } /// What was written down since `since` (ms), however long ago: every month's file from then on /// (個人資料 reads a year). pub fn since_any(since: i64) -> Vec { use chrono::TimeZone; let now = chrono::Local::now(); let mut month = chrono::Local.timestamp_millis_opt(since).single().unwrap_or(now); let mut out = vec![]; for _ in 0..40 { for line in std::fs::read_to_string(file_for(month)).unwrap_or_default().lines() { if let Ok(e) = serde_json::from_str::(line) { if e.at >= since { out.push(e); } } } if month.format("%Y-%m").to_string() >= now.format("%Y-%m").to_string() { break; } month = month.checked_add_months(chrono::Months::new(1)).unwrap_or(now); } out } fn k(n: u64) -> String { match n { 0..=999 => n.to_string(), 1_000..=999_999 => format!("{:.1}k", n as f64 / 1_000.0), _ => format!("{:.2}M", n as f64 / 1_000_000.0), } } fn line(u: &Usage) -> String { let mut s = format!("輸入 {}、輸出 {}", k(u.input + u.cache_read + u.cache_write), k(u.output)); let read = u.input + u.cache_read + u.cache_write; if u.cache_read > 0 && read > 0 { s.push_str(&format!("(快取讀了 {}%)", u.cache_read * 100 / read)); } if u.cost_micros > 0 { s.push_str(&format!(",花了 US${:.2}", u.cost_micros as f64 / 1_000_000.0)); } s } /// 「/usage」: the last day and the last week, by bot and by model. `name`: a bot's name by id. pub fn summary(entries: &[Entry], now_ms: i64, name: &dyn Fn(u64) -> Option) -> String { const DAY: i64 = 86_400_000; let total = |from: i64| { let mut u = Usage::default(); let mut n = 0; for e in entries.iter().filter(|e| e.at >= from) { u.add(&e.usage); n += 1; } (u, n) }; let (day, nd) = total(now_ms - DAY); let (week, nw) = total(now_ms - 7 * DAY); if nw == 0 { return "最近 7 天還沒有用量紀錄(模型服務有回報用量才記得到)。".into(); } let mut s = format!("用量(模型服務回報的 token)\n最近 24 小時:{nd} 次呼叫,{}\n最近 7 天:{nw} 次呼叫,{}", line(&day), line(&week)); let mut by_bot: BTreeMap = BTreeMap::new(); let mut by_model: BTreeMap = BTreeMap::new(); for e in entries.iter().filter(|e| e.at >= now_ms - 7 * DAY) { let (id, what) = e.whose(); let who = if id == 0 { what.to_string() } else { format!("{}({what})", name(id).unwrap_or_else(|| format!("Bot {id}"))) }; by_bot.entry(who).or_default().add(&e.usage); by_model.entry(format!("{} · {}", e.provider, e.model)).or_default().add(&e.usage); } let mut top = |title: &str, m: BTreeMap| { let mut rows: Vec<(String, Usage)> = m.into_iter().collect(); rows.sort_by_key(|(_, u)| std::cmp::Reverse(u.input + u.cache_read + u.cache_write + u.output)); s.push_str(&format!("\n\n{title}(7 天):")); for (who, u) in rows.iter().take(8) { s.push_str(&format!("\n- {who}:{}", line(u))); } }; top("依 Bot", by_bot); top("依模型", by_model); s } /// 「/usage」 (nothing after it). pub fn command(text: &str) -> bool { text.trim() == "/usage" } #[cfg(test)] mod tests { use super::*; fn e(at: i64, session: &str, model: &str, input: u64, output: u64, cache_read: u64) -> Entry { Entry { at, provider: "Claude".into(), model: model.into(), session: session.into(), usage: Usage { input, output, cache_read, ..Default::default() } } } #[test] fn whose_call_it_was_comes_from_the_session() { assert_eq!(e(0, "anybot-bot-12", "m", 1, 1, 0).whose(), (12, "回合")); assert_eq!(e(0, "anybot-check-3", "m", 1, 1, 0).whose(), (3, "發布前檢查")); assert_eq!(e(0, "anybot-goal-7", "m", 1, 1, 0).whose(), (7, "目標檢查")); assert_eq!(e(0, "", "m", 1, 1, 0).whose(), (0, "其他")); } #[test] fn the_summary_adds_up_the_day_and_the_week() { let now = 30 * 86_400_000; let list = vec![ e(now - 3_600_000, "anybot-bot-1", "claude-x", 1_000, 200, 9_000), e(now - 2 * 86_400_000, "anybot-bot-1", "claude-x", 500, 100, 0), e(now - 3_600_000, "anybot-check-2", "grok-mini", 300, 10, 0), e(now - 20 * 86_400_000, "anybot-bot-1", "claude-x", 99_999, 1, 0), ]; let s = summary(&list, now, &|id| (id == 1).then(|| "進化之神".to_string())); assert!(s.contains("最近 24 小時:2 次呼叫,輸入 10.3k、輸出 210(快取讀了 87%)"), "{s}"); assert!(s.contains("最近 7 天:3 次呼叫"), "{s}"); assert!(s.contains("- 進化之神(回合):輸入 10.5k、輸出 300") && s.contains("- Bot 2(發布前檢查)"), "{s}"); assert!(s.contains("- Claude · claude-x") && !s.contains("100.0k"), "older than a week is left out: {s}"); assert!(summary(&[], now, &|_| None).contains("還沒有用量紀錄")); } #[test] fn a_call_is_written_down_and_read_back() { let req = ChatRequest { kind: crate::providers::ProviderKind::Anthropic, base_url: String::new(), api_key: String::new(), model: "claude-test".into(), system: String::new(), history: vec![], tools: vec![], session: "anybot-bot-42".into(), effort: String::new() }; let t0 = chrono::Local::now().timestamp_millis(); note(&req, &Usage { input: 7, output: 3, cost_micros: 1_500, ..Default::default() }); note(&req, &Usage::default()); let got: Vec = since(t0).into_iter().filter(|e| e.model == "claude-test").collect(); assert_eq!(got.len(), 1, "nothing written for a call that said nothing"); assert_eq!((got[0].whose(), got[0].usage.cost_micros), ((42, "回合"), 1_500)); assert!(command(" /usage ") && !command("/usage x") && !command("/usages")); } }