AnyBot/src/stats.rs

304 lines
15 KiB
Rust
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.

//! 個人資料與用量 (plan C4, C5): what the person did with AnyBot over the past year, worked out
//! when asked from what is already kept — every model call's tokens (`usage/YYYY-MM.jsonl`) and
//! every message's time — nothing stored apart. Days are cut in the brain's time zone.
//!
//! The figures: tokens over the past year (not counting cache hits: what the model read anew and
//! wrote), the busiest day, messages, the current and the longest run of days used (today not
//! used yet doesn't end a run), a year of days for the heat map (53 weeks), and for 7 / 30 / 90 /
//! 365 days the tokens by kind, what the providers said it cost (a call none priced is counted as
//! 「未定價」, never $0), by model and by bot, and per day.
use crate::usage::Entry;
use chrono::{Datelike, NaiveDate, TimeZone};
use serde_json::{json, Value};
use std::collections::{BTreeMap, HashMap};
/// What the figures are made from (gathered on the app's thread: the chats live there).
pub struct Inputs {
/// When each message the person or a bot wrote was written (ms), any bot, any conversation.
pub messages: Vec<i64>,
/// Bots by id, for the names in 「依 Bot」.
pub names: HashMap<u64, String>,
/// The brain's time zone (設定 › 一般 › Bot › 時區).
pub timezone: String,
}
/// The days of the heat map: 53 weeks, ending today.
pub const DAYS: i64 = 53 * 7;
const DAY_MS: i64 = 86_400_000;
/// From the app's state: every message's time (the person's and the bots' words, not steps or
/// AnyBot's own lines), the bots' names, the time zone.
pub fn inputs(st: &crate::model::State) -> Inputs {
use crate::model::Role;
let from = crate::model::now_ms() - (DAYS + 2) * DAY_MS;
let counts = |m: &crate::model::Message| matches!(m.role, Role::User | Role::Assistant) && !m.note && m.at >= from && !(m.role == Role::Assistant && m.text.trim().is_empty());
let mut messages = vec![];
for b in &st.bots {
messages.extend(b.messages.iter().filter(|m| counts(m)).map(|m| m.at));
for (_, t) in b.threads.iter() {
messages.extend(t.iter().filter(|m| counts(m)).map(|m| m.at));
}
}
Inputs { messages, names: st.bots.iter().map(|b| (b.id, b.name.clone())).collect(), timezone: st.timezone.clone() }
}
/// Everything, from the inputs and the year's usage on disk.
pub fn build(inp: &Inputs, now_ms: i64) -> Value {
compute(inp, &crate::usage::since_any(now_ms - (DAYS + 2) * DAY_MS), now_ms)
}
/// Tokens that count: what the model read anew (and wrote to its cache) and what it wrote — a
/// cache hit is the same words read again, cheaply.
fn counted(u: &crate::providers::Usage) -> u64 {
u.input + u.cache_write + u.output
}
pub fn compute(inp: &Inputs, entries: &[Entry], now_ms: i64) -> Value {
let tz = crate::routines::tz_of(&inp.timezone);
let day_of = |ms: i64| tz.timestamp_millis_opt(ms).single().map(|t| t.date_naive());
let Some(today) = day_of(now_ms) else { return json!({}) };
let first = today - chrono::Duration::days(DAYS - 1);
// Per day of the past year: tokens, messages.
let mut days: BTreeMap<NaiveDate, (u64, u64)> = BTreeMap::new();
for e in entries {
if let Some(d) = day_of(e.at).filter(|d| *d >= first && *d <= today) {
days.entry(d).or_default().0 += counted(&e.usage);
}
}
for &at in &inp.messages {
if let Some(d) = day_of(at).filter(|d| *d >= first && *d <= today) {
days.entry(d).or_default().1 += 1;
}
}
let year_from = today - chrono::Duration::days(364);
let in_year = |d: &NaiveDate| *d >= year_from;
let tokens_year: u64 = days.iter().filter(|(d, _)| in_year(d)).map(|(_, v)| v.0).sum();
let messages_year: u64 = days.iter().filter(|(d, _)| in_year(d)).map(|(_, v)| v.1).sum();
let busiest = days.iter().filter(|(d, v)| in_year(d) && v.0 > 0).max_by_key(|(d, v)| (v.0, std::cmp::Reverse(**d))).map(|(d, v)| json!({"date": d.to_string(), "tokens": v.0}));
let active = |d: &NaiveDate| days.get(d).is_some_and(|v| v.0 > 0 || v.1 > 0);
// The run up to today (today not used yet: up to yesterday).
let mut end = today;
if !active(&end) {
end = today - chrono::Duration::days(1);
}
let mut start = end;
while active(&start) && start > first {
start -= chrono::Duration::days(1);
}
let start = if active(&start) { start } else { start + chrono::Duration::days(1) };
let now_run = if active(&end) { (end - start).num_days() + 1 } else { 0 };
// The longest run in the year.
let (mut best, mut best_from, mut best_to, mut run, mut run_from) = (0i64, first, first, 0i64, first);
let mut d = first;
while d <= today {
if active(&d) {
if run == 0 {
run_from = d;
}
run += 1;
if run > best {
(best, best_from, best_to) = (run, run_from, d);
}
} else {
run = 0;
}
d += chrono::Duration::days(1);
}
let active_days = days.iter().filter(|(d, v)| in_year(d) && (v.0 > 0 || v.1 > 0)).count();
// The heat map: every day from `first` (a Sunday-started week grid is the page's to draw).
let max = days.values().map(|v| v.0).max().unwrap_or(0).max(1);
let max_msgs = days.values().map(|v| v.1).max().unwrap_or(0).max(1);
let level = |t: u64, m: u64| -> u8 {
// Tokens when there are any; a day with only messages (a provider that reports none) by them.
let share = if t > 0 { t as f64 / max as f64 } else { m as f64 / max_msgs as f64 };
if t == 0 && m == 0 {
0
} else if share < 0.25 {
1
} else if share < 0.5 {
2
} else if share < 0.75 {
3
} else {
4
}
};
let mut grid = vec![];
let mut d = first;
while d <= today {
let (t, m) = days.get(&d).copied().unwrap_or_default();
grid.push(json!([d.to_string(), t, m, level(t, m)]));
d += chrono::Duration::days(1);
}
// 用量: the last 7 / 30 / 90 / 365 days.
let name = |id: u64, what: &str| -> String {
if id == 0 {
return format!("({what})");
}
let n = inp.names.get(&id).cloned().unwrap_or_else(|| format!("Bot {id}(已刪除)"));
if what == "回合" { n } else { format!("{n}({what})") }
};
let mut periods = serde_json::Map::new();
for span in [7i64, 30, 90, 365] {
let from = today - chrono::Duration::days(span - 1);
let mut total = crate::providers::Usage::default();
let (mut calls, mut unpriced) = (0u64, 0u64);
let mut by_model: BTreeMap<String, (u64, u64, u64)> = BTreeMap::new();
let mut by_bot: BTreeMap<String, (u64, u64, u64)> = BTreeMap::new();
let mut per_day: BTreeMap<NaiveDate, u64> = BTreeMap::new();
for e in entries {
let Some(d) = day_of(e.at).filter(|d| *d >= from && *d <= today) else { continue };
total.add(&e.usage);
calls += 1;
if e.usage.cost_micros == 0 {
unpriced += 1;
}
let t = counted(&e.usage);
let m = by_model.entry(format!("{} · {}", e.provider, e.model)).or_default();
(m.0, m.1, m.2) = (m.0 + t, m.1 + e.usage.cost_micros, m.2 + 1);
let (id, what) = e.whose();
let b = by_bot.entry(name(id, what)).or_default();
(b.0, b.1, b.2) = (b.0 + t, b.1 + e.usage.cost_micros, b.2 + 1);
*per_day.entry(d).or_default() += t;
}
let rows = |m: BTreeMap<String, (u64, u64, u64)>| -> Vec<Value> {
let mut v: Vec<(String, (u64, u64, u64))> = m.into_iter().collect();
v.sort_by_key(|(k, x)| (std::cmp::Reverse(x.0), k.clone()));
v.into_iter().map(|(k, x)| json!({"name": k, "tokens": x.0, "cost_micros": x.1, "calls": x.2})).collect()
};
let mut daily = vec![];
let mut d = from;
while d <= today {
daily.push(json!([d.to_string(), per_day.get(&d).copied().unwrap_or(0)]));
d += chrono::Duration::days(1);
}
periods.insert(
span.to_string(),
json!({
"tokens": counted(&total), "input": total.input, "output": total.output, "cache_read": total.cache_read, "cache_write": total.cache_write,
"cost_micros": total.cost_micros, "calls": calls, "unpriced": unpriced,
"by_model": rows(by_model), "by_bot": rows(by_bot), "daily": daily,
}),
);
}
json!({
"today": today.to_string(),
"first": first.to_string(),
"tokens_year": tokens_year,
"messages_year": messages_year,
"busiest": busiest,
"streak_now": now_run,
"streak_now_since": (now_run > 0).then(|| start.to_string()),
"streak_best": best,
"streak_best_from": (best > 0).then(|| best_from.to_string()),
"streak_best_to": (best > 0).then(|| best_to.to_string()),
"active_days": active_days,
"days": grid,
"periods": periods,
"weekday_first": first.weekday().num_days_from_sunday(),
})
}
/// A count the way the page says it: 9,999; 5993.4萬; 1.20億.
pub fn wan(n: u64) -> String {
match n {
0..=9_999 => {
let s = n.to_string();
if n >= 1_000 { format!("{},{}", &s[..s.len() - 3], &s[s.len() - 3..]) } else { s }
}
// (No「.0」, and no decimal at all past a thousand 萬: 3,699萬, not 3699.0萬.)
// (The edges by what they round to: 9,995,000 is 1,000萬, 99,995,000 is 1億.)
10_000..=9_994_999 => format!("{:.1}萬", n as f64 / 10_000.0).replace(".0萬", "萬"),
9_995_000..=99_994_999 => {
let s = ((n as f64 / 10_000.0).round() as u64).to_string();
format!("{},{}萬", &s[..s.len() - 3], &s[s.len() - 3..])
}
_ => format!("{:.2}億", n as f64 / 100_000_000.0).replace(".00億", "億"),
}
}
/// What the providers said it cost, or 「未定價」 when none did.
pub fn cost_words(micros: u64, unpriced: u64, calls: u64) -> String {
if micros == 0 {
return "未定價".into();
}
let s = format!("US${:.2}", micros as f64 / 1_000_000.0);
if unpriced > 0 && unpriced < calls {
format!("{s}(另有 {unpriced} 次呼叫未定價)")
} else {
s
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::providers::Usage;
fn at(tz: &str, y: i32, m: u32, d: u32, h: u32) -> i64 {
crate::routines::tz_of(tz).with_ymd_and_hms(y, m, d, h, 0, 0).unwrap().timestamp_millis()
}
fn entry(ms: i64, model: &str, session: &str, input: u64, output: u64, cache_read: u64, cost: u64) -> Entry {
Entry { at: ms, provider: "xAI Grok".into(), model: model.into(), session: session.into(), usage: Usage { input, output, cache_read, cache_write: 0, cost_micros: cost } }
}
/// The year in figures: tokens without cache hits, the busiest day, messages, the run up to
/// today (today not used yet doesn't end it), the longest run, days cut in the brain's zone.
#[test]
fn a_year_in_figures() {
let tz = "Asia/Taipei";
let now = at(tz, 2026, 11, 21, 15);
let inp = Inputs {
// 11/18, 11/19, 11/20 (one at 23:30 Taipei — 15:30 UTC, still the 20th there), nothing today.
messages: vec![at(tz, 2026, 11, 18, 10), at(tz, 2026, 11, 19, 10), at(tz, 2026, 11, 20, 23) + 30 * 60_000],
names: [(2u64, "賴桑".to_string())].into_iter().collect(),
timezone: tz.into(),
};
let entries = vec![
entry(at(tz, 2026, 11, 19, 9), "grok-4", "anybot-bot-2", 1_000, 200, 50_000, 0),
entry(at(tz, 2026, 11, 20, 9), "grok-4", "anybot-bot-2", 3_000, 500, 0, 0),
entry(at(tz, 2026, 11, 20, 10), "kimi-k3", "anybot-check-2", 100, 10, 0, 12_000),
// A year and more ago: not in the year.
entry(at(tz, 2025, 11, 1, 9), "grok-4", "anybot-bot-9", 9_999_999, 0, 0, 0),
// Two weeks ago, one day alone.
entry(at(tz, 2026, 11, 7, 9), "grok-4", "anybot-bot-9", 10, 0, 0, 0),
];
let s = compute(&inp, &entries, now);
assert_eq!(s["tokens_year"], 1_200 + 3_500 + 110 + 10, "cache hits aren't counted");
assert_eq!(s["busiest"], json!({"date": "2026-11-20", "tokens": 3_610}));
assert_eq!(s["messages_year"], 3);
assert_eq!((s["streak_now"].as_i64(), s["streak_now_since"].as_str()), (Some(3), Some("2026-11-18")), "today not used yet: the run still stands");
assert_eq!((s["streak_best"].as_i64(), s["streak_best_from"].as_str(), s["streak_best_to"].as_str()), (Some(3), Some("2026-11-18"), Some("2026-11-20")));
assert_eq!(s["active_days"], 4);
let days = s["days"].as_array().unwrap();
assert_eq!(days.len() as i64, DAYS);
assert_eq!(days.last().unwrap()[0], "2026-11-21");
let lvl = |date: &str| days.iter().find(|d| d[0] == date).map(|d| d[3].as_u64().unwrap()).unwrap();
assert_eq!((lvl("2026-11-20"), lvl("2026-11-19"), lvl("2026-11-21")), (4, 2, 0));
// 用量 for 7 days: by model, by bot (a check by its bot), what it cost, what wasn't priced.
let w = &s["periods"]["7"];
assert_eq!((w["calls"].as_u64(), w["unpriced"].as_u64(), w["cost_micros"].as_u64()), (Some(3), Some(2), Some(12_000)));
assert_eq!(w["by_model"][0]["name"], "xAI Grok · grok-4");
let bots: Vec<&str> = w["by_bot"].as_array().unwrap().iter().map(|r| r["name"].as_str().unwrap()).collect();
assert_eq!(bots, ["賴桑", "賴桑(發布前檢查)"]);
assert_eq!(w["daily"].as_array().unwrap().len(), 7);
assert_eq!(s["periods"]["30"]["by_bot"].as_array().unwrap().iter().find(|r| r["name"] == "Bot 9(已刪除)").map(|r| r["tokens"].as_u64()), Some(Some(10)));
// A day used today: the run goes through today.
let mut inp2 = inp;
inp2.messages.push(at(tz, 2026, 11, 21, 9));
assert_eq!(compute(&inp2, &entries, now)["streak_now"], 4);
}
#[test]
fn counts_and_costs_are_said_plainly() {
assert_eq!((wan(999), wan(9_999), wan(59_934_000), wan(294_000), wan(120_000_000)), ("999".into(), "9,999".into(), "5,993萬".into(), "29.4萬".into(), "1.20億".into()));
assert_eq!((wan(20_000), wan(100_000_000)), ("2萬".into(), "1億".into()));
assert_eq!((wan(9_994_999), wan(9_995_000), wan(99_994_999), wan(99_995_000)), ("999.5萬".into(), "1,000萬".into(), "9,999萬".into(), "1億".into()));
assert_eq!(cost_words(0, 5, 5), "未定價");
assert_eq!(cost_words(1_230_000, 0, 4), "US$1.23");
assert_eq!(cost_words(1_230_000, 2, 4), "US$1.23(另有 2 次呼叫未定價)");
}
}