AnyBot/src/usage.rs

210 lines
8.9 KiB
Rust
Raw Normal View History

feat: 每一次模型呼叫都記用量;/usage 看最近一天和一週 工程基礎計畫 E8,參考 grok-build 的 `grok usage`。 - providers.rs:StepOutput 多一個 usage(輸入、輸出、快取讀、快取寫、花費)。OpenAI 系的串流最後一段的 usage(OpenAI、xAI、OpenRouter 的請求加 stream_options.include_usage;其他有給也讀);Anthropic 從 message_start 和 message_delta 讀。OpenAI 的 prompt_tokens 包含快取讀的,拆開,兩家的「輸入」同一個意思。OpenRouter 回的 cost 記成百萬分之一美元。拿掉沒人讀的 CACHE_STATS。 - usage.rs:run_step_as_written(每一次模型呼叫都經過)之後寫一行到資料夾的 usage/YYYY-MM.jsonl:時間、供應商、模型、session(看得出哪個 Bot、做什麼:回合、發布前檢查、目標檢查、支線)、token、花費。沒回報用量的呼叫不寫。 - 「/usage」(電腦、螢幕、手機):最近 24 小時和 7 天的呼叫次數、輸入、輸出、快取讀了幾成、花費(有回報才寫),依 Bot、依模型各列前 8 名。不猜價錢。 - / 清單、手機的指令清單多一個 usage;功能地圖 chat.md、FEATURES.md。 已驗證:cargo test 全過、cargo clippy -D warnings 過。新測試:兩種串流的用量讀得對(OpenAI 的快取拆出來、OpenRouter 的花費、Anthropic 的四種),只對認得的服務送 stream_options;session 看得出是誰的;一天和一週的加總、依 Bot 和依模型、七天前的不算;寫一行再讀回來,沒用量的不寫。 未驗證:真的 OpenAI/xAI/OpenRouter 回的 usage(照它們的文件寫,假模型測過格式)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 03:27:34 +00:00
//! 用量: 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::<u64>().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<chrono::Local>) -> 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<Entry> {
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::<Entry>(line) {
if e.at >= since {
out.push(e);
}
}
}
}
out
}
個人資料與用量(計畫 C4、C5,照 OpenBot 的排版):設定多一頁「個人資料」(左下角選單也有「個人資料與用量…」)。名字和「過去一年有 N 個活躍日」;五張卡——Token(過去一年,不算快取命中)、最活躍的一天、訊息、目前連續天數(今天還沒用不算斷)、最長連續天數;「活動」一年的熱度格子(53 週,越忙越深,滑過看日期、token、訊息數);「用量」7/30/90 天/一年:token(新讀、寫、快取讀到)、呼叫次數、花費(只算模型服務回報的,沒回報寫「未定價」,不是 0 元)、每天一條、依模型、依 Bot。 全部從已經有的紀錄算(stats.rs:usage/YYYY-MM.jsonl 和每則訊息的時間,usage::since_any 讀一年),用大腦的時區切日子,打開時在背景算、一分鐘內不重算。螢幕電腦向大腦要(api/sync/stats),手機的路是 api/stats(擁有者才有,手機頁面還沒做)。卡片做成 kit.rs 的 stat_card(設計檢查不准散落的手工卡片)。功能地圖 settings.md(settings-me、驗證步驟)、FEATURES.md、計畫 C4/C5 狀態、版面檢查加「設定 › 個人資料」。 已驗證: cargo test 全綠(831),新測試 stats::a_year_in_figures(不算快取命中、最忙的一天、訊息、今天還沒用不斷、最長、台北時區 23:30 還算那天、熱度四級、7 天的依模型依 Bot、檢查算在它的 Bot、刪掉的 Bot、花費和未定價)、counts_and_costs_are_said_plainly、me_ui 的日期;layout_audit 過(第一版卡片的邊框讓頁面寬了 4 px,被它抓到);clippy 錯誤數跟之前一樣(12);桌面截圖(scratch 寫進一年假的用量紀錄):五張卡、熱度格子、用量的 30 天、每日條、依模型、依 Bot;verify-anybot:api/stats 回 371 天、四個期間,沒登入 401。 未驗證: 螢幕電腦向大腦要(要兩台);真的一年資料的大腦算多久(Jenny 那台 3.5 萬則舊訊息)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha2uBHmbnuWBhNzjbJm
2026-11-21 05:54:31 +00:00
/// 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<Entry> {
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::<Entry>(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
}
feat: 每一次模型呼叫都記用量;/usage 看最近一天和一週 工程基礎計畫 E8,參考 grok-build 的 `grok usage`。 - providers.rs:StepOutput 多一個 usage(輸入、輸出、快取讀、快取寫、花費)。OpenAI 系的串流最後一段的 usage(OpenAI、xAI、OpenRouter 的請求加 stream_options.include_usage;其他有給也讀);Anthropic 從 message_start 和 message_delta 讀。OpenAI 的 prompt_tokens 包含快取讀的,拆開,兩家的「輸入」同一個意思。OpenRouter 回的 cost 記成百萬分之一美元。拿掉沒人讀的 CACHE_STATS。 - usage.rs:run_step_as_written(每一次模型呼叫都經過)之後寫一行到資料夾的 usage/YYYY-MM.jsonl:時間、供應商、模型、session(看得出哪個 Bot、做什麼:回合、發布前檢查、目標檢查、支線)、token、花費。沒回報用量的呼叫不寫。 - 「/usage」(電腦、螢幕、手機):最近 24 小時和 7 天的呼叫次數、輸入、輸出、快取讀了幾成、花費(有回報才寫),依 Bot、依模型各列前 8 名。不猜價錢。 - / 清單、手機的指令清單多一個 usage;功能地圖 chat.md、FEATURES.md。 已驗證:cargo test 全過、cargo clippy -D warnings 過。新測試:兩種串流的用量讀得對(OpenAI 的快取拆出來、OpenRouter 的花費、Anthropic 的四種),只對認得的服務送 stream_options;session 看得出是誰的;一天和一週的加總、依 Bot 和依模型、七天前的不算;寫一行再讀回來,沒用量的不寫。 未驗證:真的 OpenAI/xAI/OpenRouter 回的 usage(照它們的文件寫,假模型測過格式)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 03:27:34 +00:00
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>) -> 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<String, Usage> = BTreeMap::new();
let mut by_model: BTreeMap<String, Usage> = 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<String, Usage>| {
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<Entry> = 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"));
}
}