diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b8f07101..1f136f17 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -80,12 +80,27 @@ clean the diff is: ## The price list -`crates/tw-pricing` embeds a pinned snapshot. It is **not** auto-updated: -following upstream automatically means two builds can compute different -prices, and "yesterday's number doesn't match today's" cannot be -explained to a user. Update steps are in -`crates/tw-pricing/data/PROVENANCE.md`, and a CI test compares the -snapshot against the hand-checked `data/verified.yaml` row by row. +Prices come in two layers. + +- **The default price table** is LiteLLM's public dataset. A pinned + snapshot is embedded in `crates/tw-pricing`, so a fresh install and an + offline machine have one. Update steps are in + `crates/tw-pricing/data/PROVENANCE.md`, and a CI test compares the + snapshot against the hand-checked `data/verified.yaml` row by row. At + runtime the control plane refreshes the table once a day (unless + `pricing.auto_update: false`) and saves it as `model_prices.json` beside + `config.yaml`. Whichever of the two is newer prices requests. +- **Price sheets** live in `config.yaml` under `pricing.sheets`: a + multiplier over the default table, plus per-model overrides with every + field written out (dollars per million tokens; nothing is inferred at + pricing time). An upstream picks a sheet with `pricing:`. Without one, + the default table applies. + +A refresh or an edited sheet changes the price of requests from then on, +never of the ones already recorded. Each request stores its cost and where +the price came from: the default table and its date, a sheet's multiplier, +or a sheet's override. "Yesterday's number doesn't match today's" is then +answered on the request itself. ## Cutting a release diff --git a/Cargo.lock b/Cargo.lock index 21a0b3de..5847388c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2808,6 +2808,7 @@ dependencies = [ "thiserror", "tokio", "tw-engine", + "tw-pricing", "tw-redact", "tw-secret", "tw-types", @@ -2819,7 +2820,6 @@ name = "tw-control" version = "0.1.2" dependencies = [ "axum", - "blake3", "bytes", "chrono", "futures", @@ -2935,13 +2935,12 @@ dependencies = [ name = "tw-pricing" version = "0.1.2" dependencies = [ + "arc-swap", "flate2", "serde", "serde_json", "serde_yaml_ng", - "tempfile", "thiserror", - "tracing", ] [[package]] diff --git a/README.md b/README.md index a4dfe60f..db160d33 100644 --- a/README.md +++ b/README.md @@ -31,9 +31,10 @@ Point a client (Claude Code, Codex, and friends) at a local port, and: upstream, rewriting parameters, or refusing outright. - **Fail over mid-flight** — before the first byte an upstream can be swapped transparently; after it, the only honest thing left is to report what happened. -- **Make cost visible** — token usage, cache hits, priced against a snapshot - table. What cannot be priced is labelled *unknown* rather than given an - invented number. +- **Make cost visible** — token usage, cache hits, priced against a public + price table that refreshes daily, with price sheets for upstreams that + charge differently. What cannot be priced is labelled *unknown* rather + than given an invented number. - **Redact outbound** — secrets in a request are replaced with placeholders before they reach a relay, and restored when the model echoes them back. - **Inspect inbound** — tool calls returned by an upstream are checked against diff --git a/bin/twcore/src/main.rs b/bin/twcore/src/main.rs index 2bc89d1d..329a6f1f 100644 --- a/bin/twcore/src/main.rs +++ b/bin/twcore/src/main.rs @@ -657,15 +657,9 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> rt.block_on(async move { let state = tw_gateway::AppState::new(cfg.clone()) .map_err(|e| anyhow::anyhow!("{}", e.message))?; - // **和观测那一层用同一份价目表。**两处各拿一份的话,「成本栏 - // 显示的」和「按最便宜选的」会对不上(用户覆盖层就是 - // `cheapest` 唯一的判据来源)。读不了就用内置那份,转发照常。 - match tw_pricing::Prices::builtin() - .and_then(|p| p.with_overrides(&dir.join("pricing.yaml"))) - { - Ok(p) => state.set_prices(p), - Err(e) => tracing::warn!("价目表的用户覆盖读不了,按内置那份算:{e}"), - } + // 默认价目表:上次联网刷新存下的那份,或者内置的。自定义价目表已经 + // 随配置进了价格簿 + state.set_price_table(tw_control::pricing::load_table(&config_path)); // 观测这一层。**起不来不是致命的** —— 历史记录看不见,而网关 // 照常转发。所以这里所有的失败都只记一行日志。 @@ -673,7 +667,7 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> // body 的通道在这里建:**它是唯一同时看得见网关和存储的地方**, // 而两边各有各的同形结构,是为了不让「观测」挂到「转发」下面。 let (body_tx, body_rx) = tokio::sync::mpsc::channel(tw_gateway::bodies::CHANNEL_CAP); - let store = build_store(&dir, state.bus.clone(), body_rx); + let store = build_store(&dir, state.bus.clone(), state.pricing.clone(), body_rx); if store.is_some() { state.set_body_sink(body_tx); } @@ -704,6 +698,7 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> cfg: manager, gateway_addr: if safe { None } else { Some(addr.to_string()) }, store, + price_updater: Default::default(), }; // 盯着客户端配置面。**只报告** —— 这条路径上没有任何 // 一处会改用户的文件。盯不住就只是少了「变更时告警」,页面上 @@ -712,6 +707,8 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> // 不是人发起的配置写入** —— 理由是服务器换发新 refresh token 的 // 那一刻旧的就作废了,不写回等于让配置文件从那一秒起就是坏的。 tw_control::rotation::spawn(control.clone()); + // 定期刷新默认价目表(`pricing.auto_update`,默认开) + tw_control::pricing::spawn(control.clone()); let _scan_watch = match tw_control::scan::spawn_watcher(control.clone()) { Ok(w) => Some(w), @@ -803,6 +800,8 @@ fn build_store( // **收整条总线,不只是一个订阅端。**存储层算完价钱要往回报一条 // (见 `Event::RequestPriced`)—— 它是这条链上唯一知道单价的地方。 bus: tw_observe::EventBus, + // **和网关同一份价格簿**,不是一份副本:改了价目表,下一个结束的请求就按新价算 + pricing: tw_pricing::Shared, bodies: tokio::sync::mpsc::Receiver, ) -> Option>> { let events = bus.subscribe(); @@ -813,17 +812,6 @@ fn build_store( return None; } }; - // 价目表解不开是个打包错误,但同样不该挡住转发 —— 那时成本一栏 - // 是空的,而请求照常。 - let prices = match tw_pricing::Prices::builtin() - .and_then(|p| p.with_overrides(&dir.join("pricing.yaml"))) - { - Ok(p) => p, - Err(e) => { - tracing::warn!("价目表读不了,成本一栏会是空的:{e}"); - return None; - } - }; let blobs = tw_store::Blobs::new(dir.join("blobs")); // 两边的 body 结构在这里对接。**一次移动,不复制** —— `Bytes` 的 // 克隆是引用计数。 @@ -849,7 +837,7 @@ fn build_store( Some(tw_store::task::spawn( // 算完价钱往回报一条 —— 见 `Event::RequestPriced`。这里是唯一 // 同时看得见总线和存储层的地方,所以接线在这儿完成。 - tw_store::Recorder::new(db, blobs, prices).reporting_to(bus), + tw_store::Recorder::new(db, blobs, pricing).reporting_to(bus), events, rx, )) diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 82f2fbdc..2175a416 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -452,6 +452,20 @@ pub struct Overview { /// 并发上限 #[serde(default)] pub limits: LimitsView, + /// 自定义价目表。默认价目表不在这里 —— 它的状态看 `/pricing` + #[serde(default)] + pub price_sheets: Vec, +} + +/// 一张自定义价目表。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PriceSheetView { + pub name: String, + pub multiplier: f64, + /// 单独覆盖了几个模型 + pub overrides: usize, + /// 哪些上游选了它。**删之前要知道**,改名时它们会跟着改 + pub used_by: Vec, } /// 一个出站代理。 @@ -567,6 +581,9 @@ pub struct ProviderView { pub redact_explicit: bool, /// 谁在引用它。**删之前要知道**,改名时它们会跟着改 pub references: Vec, + /// 选的价目表。空 = 默认价目表 + #[serde(default)] + pub pricing: Option, } /// 配置里引用了某个上游的一处。 @@ -814,73 +831,164 @@ pub enum PatchValue { Null, } -/// 「检查价格更新」第一步:**先说要访问什么、多大**。 -/// -/// **绝不在启动时后台偷偷拉。**零上传那句承诺,也意味着零静默下载 —— -/// 而「先告诉你要连哪儿」是这条承诺里最容易被省掉的一半。 -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct UpdateOffer { - pub url: String, - /// 字节。`None` = 对面没给 `Content-Length` - pub bytes: Option, - /// 现在这份快照是哪天的 - pub current_date: String, -} +// ─────────────────────────────────────────────────────────── 价目表 -/// 第二步:下载完、解析完,**给 diff,还没写**。 +/// 默认价目表现在的状态。 #[derive(Debug, Clone, Serialize, Deserialize)] -pub struct UpdatePreview { - /// 拉回来的表里有多少个带价的模型 +pub struct PricingStatus { + /// 这份表的数据日期。**费用旁边要标它** + pub date: String, + /// `builtin`(随版本内置)/ `fetched`(联网刷新过)/ `empty` + pub source: String, + /// 表里有多少个模型 pub models: usize, - /// 真的变了的那些。**不列没动的** —— 三千多个里绝大多数没动, - /// 一起列出来等于把那几十条真的变化埋掉 - pub changes: Vec, - /// 这份东西的指纹。第三步要带着它回来 —— 否则「确认写入」写的 - /// 可能是另一次下载的结果 - pub token: String, + /// 定期刷新开没开 + pub auto_update: bool, + /// 最近一次刷新的时间,成功失败都算。这次启动以来没刷过就是空 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub checked_at_ms: Option, + /// 最近一次刷新失败的原因 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub error: Option, + /// 最近 7 天里**无法计价**的请求数。 + /// + /// 用户不会主动想起要配价格,只有「有 37 次请求无法计价」这种具体 + /// 证据才会。 + pub unpriced_recent: i64, + /// 那些请求走的是哪个上游、哪个模型。**直接告诉他要在哪张价目表里设 + /// 什么**,按请求数从多到少 + pub unpriced_models: Vec, } -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct PriceChangeView { +/// 一个无法计价的 (上游, 模型)。 +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct UnpricedModel { + pub provider: String, pub model: String, - /// `null` = 新增的 - pub old_input: Option, - pub new_input: f64, - pub old_output: Option, - pub new_output: f64, + pub requests: i64, } -/// 一条用户自己写的价格(第三层)。 -/// -/// **单位是每百万 token 的美元**,和厂商定价页上印的一样 —— 让用户 -/// 在界面上填 `0.000003` 是在要求他做一次换算,而换算是会错的。 +/// 刷新了一次之后。 #[derive(Debug, Clone, Serialize, Deserialize)] -pub struct PriceRow { - /// 哪个上游。`None` = 对所有上游生效 +pub struct PricingRefreshed { + pub status: PricingStatus, + /// 和刷新之前比,价格变了、新增或者移除了的模型数 + pub changed: usize, +} + +/// 开关定期刷新。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AutoUpdateSave { + pub on: bool, #[serde(default, skip_serializing_if = "Option::is_none")] - pub provider: Option, - pub model: String, - /// 每百万 token 的美元 + pub base_version: Option, +} + +/// 一个模型的单价,**每百万 tokens 的美元**,和厂商定价页上印的一样。 +/// +/// 查价返回的是**实际计费用的**单价:数据集里没单独定价的缓存档已经按 +/// 计费规则补上。所以它可以原样作为一条覆盖价的起点。 +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct PriceFields { pub input: f64, pub output: f64, - /// 内置快照里有没有这个模型。**界面要能说「这条是在覆盖」**, - /// 因为覆盖一个本来就有价的模型,和补一个没价的,是两件事 + pub cache_read: f64, + pub cache_write_5m: f64, + pub cache_write_1h: f64, + /// 单次请求输入超过 200K tokens 之后的单价。**成对出现**;没有 = 不分档 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub input_above_200k: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub output_above_200k: Option, +} + +/// 一个价格是从哪儿来的。**每一笔费用都要能追溯到它。** +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum PriceSourceView { + /// 默认价目表。`date` 是那份表的数据日期 + Default { date: String }, + /// 默认价目表 × 某张价目表的倍率 + Scaled { + sheet: String, + multiplier: f64, + date: String, + }, + /// 某张价目表单独覆盖的 + Override { sheet: String }, +} + +/// 新建或修改一张价目表时交过来的定义。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PriceSheetInput { + pub name: String, + /// 作用于默认价目表的全部单价 + #[serde(default = "one")] + pub multiplier: f64, + /// 单独覆盖的模型。**覆盖价不受倍率影响** #[serde(default)] - pub overrides_builtin: bool, + pub models: std::collections::BTreeMap, +} + +fn one() -> f64 { + 1.0 } -/// 用户的价格覆盖,连同「内置那份是什么时候的」。 #[derive(Debug, Clone, Serialize, Deserialize)] -pub struct PricingView { - pub rows: Vec, - pub snapshot_date: String, - /// 最近这段时间里**算不出价钱**的请求数。 - /// - /// **这是这一页存在的理由** —— 用户不会主动想起要配价格,只有 - /// 「有 37 条请求算不出钱」这种具体证据才会(触发条件)。 - pub unpriced_recent: i64, - /// 那些算不出价钱的请求用的是哪些模型。**直接告诉他要填什么** - pub unpriced_models: Vec, +pub struct PriceSheetSave { + pub sheet: PriceSheetInput, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub base_version: Option, +} + +/// 按哪张价目表查价。 +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum SheetRef { + /// 默认价目表 + Default, + /// 一张已经保存的价目表 + Named { name: String }, + /// 编辑中、还没保存的那一张 + Draft { sheet: PriceSheetInput }, +} + +/// 查价。**界面不自己实现计价顺序**,要显示什么价就来问。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PriceQuery { + pub sheet: SheetRef, + /// 要查的模型。给了就只查这些 + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub models: Vec, + /// 没给模型时按名字搜:默认价目表里的模型,加上这张价目表单独覆盖的 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub search: Option, + /// 搜索最多返回几个。默认 50 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub limit: Option, +} + +/// 一个模型查到的价格。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ResolvedPrice { + pub model: String, + /// 价格和来源。`None` = 无法计价 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub price: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source: Option, + /// 价格是从别的平台借来的。**按它算出来的钱是估算** + pub estimated: bool, + /// 上下文窗口 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_input_tokens: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PriceQueryResult { + pub items: Vec, + /// 按名字搜时,一共有多少个模型对得上(`items` 可能被 `limit` 截断) + pub matched: usize, } /// 光标落在配置的哪一段上。 @@ -947,6 +1055,9 @@ pub struct ProviderInput { /// 发送前脱敏的类别。不给就按地址识别;**空列表是「不脱敏」** #[serde(default, skip_serializing_if = "Option::is_none")] pub redact: Option>, + /// 按哪张价目表计价。不给就是默认价目表 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pricing: Option, } fn direct() -> String { @@ -1244,6 +1355,9 @@ pub struct HistoryRow { /// 路由决策与尝试链。老记录没有它 #[serde(default, skip_serializing_if = "Option::is_none")] pub routing: Option, + /// 按什么价格算的。没算出金额的、老记录没有它 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub price_source: Option, } /// 一条请求的全部细节。**详情抽屉吃这个。** diff --git a/crates/tw-config/Cargo.toml b/crates/tw-config/Cargo.toml index 84dec2fe..3a460c98 100644 --- a/crates/tw-config/Cargo.toml +++ b/crates/tw-config/Cargo.toml @@ -12,6 +12,7 @@ tw-engine = { workspace = true } tw-types = { workspace = true } tw-secret = { workspace = true } tw-redact = { workspace = true } +tw-pricing = { workspace = true } # 凭据轮换要把一个标量写回 config.yaml。**span 补丁,不是 # serde 往返** —— 往返会把用户的注释和排版全洗掉 tw-yaml = { workspace = true } diff --git a/crates/tw-config/src/edit.rs b/crates/tw-config/src/edit.rs index 553a838a..54cbe34e 100644 --- a/crates/tw-config/src/edit.rs +++ b/crates/tw-config/src/edit.rs @@ -157,6 +157,10 @@ pub fn upsert( } /// 删掉叫 `name` 的那一项。引用它的地方由调用方先检查。 +/// +/// **删掉的是最后一项时,整段列表连同因此变空的父段一起删。**这几段列表 +/// 不写和写成空列表是一回事,而默认值不写进文件 —— 留下一个 +/// `pricing: { sheets: [] }` 只是噪音。 pub fn remove(text: &str, section: Section, name: &str) -> Result { let doc = parse(text)?; let index = section @@ -165,7 +169,11 @@ pub fn remove(text: &str, section: Section, name: &str) -> Result, + /// 价目表:默认价目表要不要定期刷新,以及用户自己的价目表。 + #[serde(default, skip_serializing_if = "is_default")] + pub pricing: tw_pricing::PricingConfig, /// 客户端自己发的辅助请求怎么处理。默认只拦 A 类。 #[serde(default, skip_serializing_if = "is_default")] pub client_probes: ClientProbes, @@ -102,6 +105,7 @@ impl Default for Config { clients: Vec::new(), providers: Vec::new(), proxies: Vec::new(), + pricing: tw_pricing::PricingConfig::default(), client_probes: ClientProbes::default(), security: Security::default(), limits: Limits::default(), @@ -139,11 +143,20 @@ impl Default for Provider { trust: None, proxy: default_proxy(), on_proxy_fail: OnProxyFail::default(), + pricing: None, } } } impl Config { + /// 哪个上游选了哪张价目表。**没选的不在里面** —— 它们按默认价目表。 + pub fn price_assign(&self) -> Vec<(String, String)> { + self.providers + .iter() + .filter_map(|p| p.pricing.clone().map(|s| (p.name.clone(), s))) + .collect() + } + /// 按配置建一个路由引擎。 pub fn engine(&self) -> tw_engine::Engine { tw_engine::Engine::new( @@ -552,6 +565,9 @@ pub struct Provider { pub proxy: String, #[serde(default, skip_serializing_if = "is_default_on_proxy_fail")] pub on_proxy_fail: OnProxyFail, + /// 按哪张价目表计价。不写就是默认价目表。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pricing: Option, } /// 这家上游可不可信。 diff --git a/crates/tw-config/src/refs.rs b/crates/tw-config/src/refs.rs index 644e9f11..f45072ef 100644 --- a/crates/tw-config/src/refs.rs +++ b/crates/tw-config/src/refs.rs @@ -66,6 +66,30 @@ pub fn proxy_users(cfg: &Config, name: &str) -> Vec { .collect() } +/// 选了 `name` 这张价目表的上游。 +pub fn sheet_users(cfg: &Config, name: &str) -> Vec { + cfg.providers + .iter() + .filter(|p| p.pricing.as_deref() == Some(name)) + .map(|p| p.name.clone()) + .collect() +} + +/// 把 `text` 里选了价目表 `old` 的上游都改成选 `new`。 +pub fn rename_sheet(text: &str, cfg: &Config, old: &str, new: &str) -> Result { + let mut out = text.to_string(); + for (i, p) in cfg.providers.iter().enumerate() { + if p.pricing.as_deref() == Some(old) { + out = edit::set( + &out, + &[Step::key("providers"), Step::Index(i), Step::key("pricing")], + Some(&Value::String(new.to_string())), + )?; + } + } + Ok(out) +} + /// 把 `text` 里引用上游 `old` 的地方都改成 `new`。`cfg` 是 `text` 解析 /// 出来的那一份 —— 下标要对得上。 pub fn rename_provider( @@ -230,6 +254,32 @@ routes: assert_eq!(after.groups[0].providers, ["relay-hk", "官方"]); } + #[test] + fn renaming_a_price_sheet_moves_the_upstreams_that_use_it() { + let text = CFG.replace(" proxy: hk\n", " proxy: hk\n pricing: 中转\n") + + "pricing:\n sheets:\n - name: 中转\n multiplier: 0.8\n"; + let c = cfg(&text); + assert_eq!(sheet_users(&c, "中转"), ["relay"]); + let renamed = edit::upsert( + &text, + edit::PRICE_SHEETS, + Some("中转"), + &serde_yaml_ng::from_str("name: 中转协议价\nmultiplier: 0.8\n").unwrap(), + ) + .unwrap(); + let out = rename_sheet(&renamed, &c, "中转", "中转协议价").unwrap(); + let after = cfg(&out); + assert_eq!(sheet_users(&after, "中转协议价"), ["relay"]); + } + + #[test] + fn a_provider_pointing_at_a_missing_sheet_is_a_config_error() { + // 静默退回默认价的话,算出来的钱看起来正常,而折扣从没生效过 + let text = CFG.replace(" proxy: hk\n", " proxy: hk\n pricing: 没有这张\n"); + let e = crate::try_parse(&text).unwrap_err(); + assert!(e.message.contains("没有这张"), "{}", e.message); + } + #[test] fn renaming_a_proxy_moves_the_upstreams_that_use_it() { let c = cfg(CFG); diff --git a/crates/tw-config/src/validate.rs b/crates/tw-config/src/validate.rs index 358202df..ca54b6bc 100644 --- a/crates/tw-config/src/validate.rs +++ b/crates/tw-config/src/validate.rs @@ -34,6 +34,10 @@ pub enum ValidationError { BadCidr { entry: String, reason: String }, #[error("provider `{name}` 的 key 写法读不懂:{why}")] BadKeyShape { name: String, why: String }, + #[error("{0}")] + Pricing(#[from] tw_pricing::SheetError), + #[error("上游「{provider}」选的价目表「{sheet}」不存在")] + UnknownPriceSheet { provider: String, sheet: String }, } /// `key:` 到底哪儿写错了。 @@ -159,6 +163,21 @@ pub fn validate(cfg: &Config) -> Result<(), ValidationError> { } } + // 价目表本身(名字、倍率、单价),以及上游选的价目表在不在。 + // **选了一张不存在的价目表不能静默退回默认价** —— 那样算出来的钱 + // 看起来正常,而用户设的折扣从来没生效过。 + cfg.pricing.validate()?; + for p in &cfg.providers { + if let Some(sheet) = &p.pricing + && cfg.pricing.sheet(sheet).is_none() + { + return Err(ValidationError::UnknownPriceSheet { + provider: p.name.clone(), + sheet: sheet.clone(), + }); + } + } + // 路由规则的目标、比较式写法,都在这里查。**一条永远不命中、或者 // 指向不存在的 provider 的规则,在运行时是完全静默的**( // 「我明明配了为什么不生效」)。 diff --git a/crates/tw-control/Cargo.toml b/crates/tw-control/Cargo.toml index efcda5c9..f69ebd8b 100644 --- a/crates/tw-control/Cargo.toml +++ b/crates/tw-control/Cargo.toml @@ -13,8 +13,6 @@ tw-api = { workspace = true } libc = { workspace = true } tw-config = { workspace = true } tw-adopt = { workspace = true } -# 更新那份价目表时给下载内容按指纹 —— 用户看的 diff 和落盘的必须是同一份 -blake3 = { workspace = true } tw-scan = { workspace = true } tw-redact = { workspace = true } bytes = { workspace = true } diff --git a/crates/tw-control/src/diagnostics.rs b/crates/tw-control/src/diagnostics.rs index 349689a6..c109b758 100644 --- a/crates/tw-control/src/diagnostics.rs +++ b/crates/tw-control/src/diagnostics.rs @@ -44,7 +44,23 @@ pub async fn bundle(State(s): State) -> String { line(&mut out, "core", env!("CARGO_PKG_VERSION")); line(&mut out, "控制面 API", tw_api::CONTROL_API_VERSION); line(&mut out, "配置 schema", cfg.version); - line(&mut out, "价目表快照", tw_pricing::SNAPSHOT_DATE); + { + // **生效的那一份,不是内置快照的日期** —— 刷新过之后两者不同,而对账 + // 对不上时要问的正是「按哪天的价格算的」 + let book = s.gateway.pricing.load(); + let t = book.table(); + let source = match t.source { + tw_pricing::TableSource::Builtin => "内置", + tw_pricing::TableSource::Fetched => "联网刷新", + tw_pricing::TableSource::Empty => "未加载", + }; + line( + &mut out, + "默认价目表", + format!("{}({source},{} 个模型)", t.date, t.len()), + ); + line(&mut out, "自定义价目表", cfg.pricing.sheets.len()); + } line(&mut out, "平台", std::env::consts::OS); line(&mut out, "架构", std::env::consts::ARCH); line( @@ -74,13 +90,13 @@ pub async fn bundle(State(s): State) -> String { // ---- 上游 let _ = writeln!( out, - "\n## 上游({} 个)\n\n| 名字 | 地址 | 协议 | 代理 | 熔断 | 脱敏 | 信任 |\n|---|---|---|---|---|---|---|", + "\n## 上游({} 个)\n\n| 名字 | 地址 | 协议 | 代理 | 熔断 | 脱敏 | 信任 | 价目表 |\n|---|---|---|---|---|---|---|---|", cfg.providers.len() ); for p in &cfg.providers { let _ = writeln!( out, - "| {} | {} | {} | {} | {} | {} | {} |", + "| {} | {} | {} | {} | {} | {} | {} | {} |", p.name, // **地址也要脱敏** —— 中转站的 base_url 里常常带着 key tw_secret::redact_url(&p.base_url), @@ -102,6 +118,7 @@ pub async fn bundle(State(s): State) -> String { } }, p.effective_trust().label(), + p.pricing.as_deref().unwrap_or("默认"), ); } diff --git a/crates/tw-control/src/dryrun.rs b/crates/tw-control/src/dryrun.rs index d5a37bf9..e14dd945 100644 --- a/crates/tw-control/src/dryrun.rs +++ b/crates/tw-control/src/dryrun.rs @@ -34,25 +34,13 @@ fn order_like_the_data_plane( return d.candidates.clone(); } let cfg = s.config(); - let prices = s.gateway.prices.load(); let facts = tw_engine::Facts { session: None, seq: s.gateway.bus.peek_id(), ttfb_ms: s.gateway.latency.snapshot(&d.candidates), - price: d - .candidates - .iter() - .filter_map(|name| { - let p = cfg.providers.iter().find(|p| &p.name == name)?; - match p.billing { - Some(tw_config::Billing::Subscription) => Some((name.clone(), (0, 0))), - Some(tw_config::Billing::Unknown) => None, - _ => prices - .unit_micros(name, &f.model) - .map(|u| (name.clone(), u)), - } - }) - .collect(), + price: s + .gateway + .unit_prices(&cfg.providers, &d.candidates, &f.model), }; engine.order(Some(&gname), &d.candidates, &facts) } diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index 09fe5b99..6c463236 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -20,6 +20,7 @@ pub mod config; pub mod diagnostics; pub mod dryrun; pub mod nics; +pub mod pricing; pub mod replay; pub mod resources; pub mod rotation; @@ -41,6 +42,8 @@ pub struct ControlState { /// 请求历史。**可能没有** —— 磁盘起不来时观测这一层整个不在, /// 而那时网关照常转发,所以它是 Option 而不是必需品。 pub store: Option>>, + /// 定期刷新默认价目表的那个任务。**价格本身不在这里**,在网关的价格簿里 + pub price_updater: Arc, /// 用户的 home。接管要顺着它去找各客户端的配置。 /// /// **是个字段,不是每次现读 `$HOME`。**进程级的环境变量是全局可变 @@ -92,13 +95,6 @@ pub fn router(state: ControlState) -> Router { ) .route("/config/history", get(config_history)) .route("/config/at", get(config::path_at)) - .route("/pricing", get(pricing_get).put(pricing_put)) - // 「检查价格更新」三步走。**三个端点,不是一个** - // —— 一个端点意味着「检查」和「写入」是同一次调用,而那正是 - // 「静默下载」的定义 - .route("/pricing/update/offer", post(update_offer)) - .route("/pricing/update/fetch", post(update_fetch)) - .route("/pricing/update/apply", post(update_apply)) .route("/config/rollback", post(config_rollback)) .route("/summary", get(summary)) .route("/summary/buckets", get(cost_buckets)) @@ -139,6 +135,7 @@ pub fn router(state: ControlState) -> Router { .route("/mcp/plan", post(clients::mcp_plan_op)) .route("/mcp/apply", post(clients::mcp_apply)) .merge(resources::router()) + .merge(pricing::router()) .with_state(state) } @@ -318,6 +315,7 @@ async fn overview(State(s): State) -> Json { mode: mode.slug().to_string(), }) .collect(), + price_sheets: pricing::sheet_views(cfg), limits: tw_api::LimitsView { max_concurrent: cfg.limits.max_concurrent, per_provider: cfg.limits.per_provider, @@ -394,6 +392,7 @@ fn provider_view( .iter() .map(resources::reference_view) .collect(), + pricing: p.pricing.clone(), } } @@ -627,7 +626,7 @@ async fn summary( cache_saved_micros: x.cache_saved_micros, flagged_requests: x.flagged_requests, redacted_requests: x.redacted_requests, - pricing_date: tw_pricing::SNAPSHOT_DATE.to_string(), + pricing_date: s.gateway.pricing.load().table().date.clone(), })) } @@ -677,28 +676,23 @@ async fn speed_quote( Json(req): Json, ) -> Result, Fail> { let cfg = s.config(); - let prices = prices(&s); + let book = s.gateway.pricing.load(); let items: Vec = targets(&cfg, req.provider.as_deref())? .iter() .map(|p| { tw_gateway::l3::estimate( - &prices, + &book, &p.name, &req.model, - // 订阅型上游的判据:配置里写明了,或者最近一次响应里报过 - // 额度(不写时自动判,和成本栏同一个口径)。 - p.billing == Some(tw_config::Billing::Subscription) - || s.gateway - .quotas() - .get(&p.name) - .is_some_and(|q| !q.is_empty()), + // 和记账同一个口径:配置里写明了,或者最近一次响应里报过额度 + s.gateway.billing_of(p) == tw_config::Billing::Subscription, ) }) .collect(); Ok(Json(tw_api::SpeedQuote { total_micros: tw_gateway::l3::total_micros(&items), items: items.into_iter().map(quote_item).collect(), - pricing_date: tw_pricing::SNAPSHOT_DATE.to_string(), + pricing_date: book.table().date.clone(), })) } @@ -770,257 +764,6 @@ fn quote_item(e: tw_gateway::Estimate) -> tw_api::SpeedEstimate { } } -/// 第一步:**只问「要访问什么、多大」,一个字节都不下载。** -/// -/// 零上传的承诺同时意味着**零静默下载** —— 而这条承诺里最容易被 -/// 省掉的一半,正是「先告诉你要连哪儿」。 -async fn update_offer(State(s): State) -> Result, Fail> { - let r = s - .http() - .head(tw_pricing::UPDATE_URL) - .send() - .await - .map_err(|e| fail(StatusCode::BAD_GATEWAY, format!("连不上:{e}")))?; - Ok(Json(tw_api::UpdateOffer { - url: tw_pricing::UPDATE_URL.to_string(), - bytes: r.content_length(), - current_date: tw_pricing::SNAPSHOT_DATE.to_string(), - })) -} - -/// 第二步:下载、解析、**给 diff,但不写盘**。 -async fn update_fetch(State(s): State) -> Result, Fail> { - let raw = s - .http() - .get(tw_pricing::UPDATE_URL) - .send() - .await - .map_err(|e| fail(StatusCode::BAD_GATEWAY, format!("下载失败:{e}")))? - .bytes() - .await - .map_err(|e| fail(StatusCode::BAD_GATEWAY, format!("下载失败:{e}")))?; - let table = tw_pricing::parse_upstream(&raw) - .map_err(|e| fail(StatusCode::BAD_GATEWAY, e.to_string()))?; - let cur = prices(&s); - let changes = tw_pricing::diff(cur.table(), &table); - let token = blake3::hash(&raw).to_hex()[..16].to_string(); - // **存在磁盘上,不存在内存里。**第三步可能几分钟之后才来(用户在 - // 看 diff),而这中间进程完全可能重启 - let path = pending_path(&s); - if let Some(d) = path.parent() { - let _ = std::fs::create_dir_all(d); - } - std::fs::write(&path, &raw) - .map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, format!("存不下来:{e}")))?; - Ok(Json(tw_api::UpdatePreview { - models: table.len(), - changes: changes - .into_iter() - // 三千多个模型全列出来没人看得完。**改价的排在前面** - // (见 `tw_pricing::diff`),所以截断截掉的是新增那一批 - .take(200) - .map(|c| tw_api::PriceChangeView { - model: c.model, - old_input: c.old_input, - new_input: c.new_input, - old_output: c.old_output, - new_output: c.new_output, - }) - .collect(), - token, - })) -} - -/// 第三步:**确认之后才写**。 -async fn update_apply( - State(s): State, - Json(req): Json, -) -> Result, Fail> { - let path = pending_path(&s); - let raw = std::fs::read(&path).map_err(|_| { - fail( - StatusCode::BAD_REQUEST, - "没有待确认的更新 —— 先点「检查更新」".to_string(), - ) - })?; - // **指纹要对上。**不对上的话,「确认写入」写的可能是另一次下载的 - // 结果 —— 用户看的 diff 和落盘的东西不是一回事 - let token = blake3::hash(&raw).to_hex()[..16].to_string(); - if token != req.token { - return Err(fail( - StatusCode::CONFLICT, - "这份更新和你看到的 diff 对不上,重新检查一次".to_string(), - )); - } - let dir = s - .config_path() - .parent() - .map(std::path::Path::to_path_buf) - .unwrap_or_default(); - // 落到数据目录,加载时优先于内置快照 - std::fs::rename(&path, dir.join("model_prices.json")) - .map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, format!("写不进去:{e}")))?; - pricing_get(State(s)).await -} - -#[derive(serde::Deserialize)] -struct ApplyReq { - token: String, -} - -/// 下载完还没确认的那份放哪儿。 -fn pending_path(s: &ControlState) -> std::path::PathBuf { - s.config_path() - .parent() - .map(std::path::Path::to_path_buf) - .unwrap_or_default() - .join("model_prices.pending.json") -} - -/// 用户自己写的那份价格(第三层)。 -/// -/// **这一页存在的理由是「有 N 条请求算不出钱」** —— 用户不会主动想起 -/// 要配价格(高级功能的触发条件要绑在「这个问题存不存在」上)。 -async fn pricing_get(State(s): State) -> Result, Fail> { - let p = prices(&s); - let rows = p - .overrides_list() - .into_iter() - .map(|(provider, model, mp)| tw_api::PriceRow { - overrides_builtin: p.builtin_has(&model), - provider, - // **每百万 token 的美元** —— 和厂商定价页上印的一样 - input: mp.input * 1_000_000.0, - output: mp.output * 1_000_000.0, - model, - }) - .collect(); - // 算不出价钱的那些。**拿不到存储就是 0** —— 观测层起不来时网关 - // 照常转发,这一页也该照常打开 - let (unpriced_recent, unpriced_models) = match &s.store { - Some(st) => { - let g = st.lock().await; - g.db().unpriced_recent(7).unwrap_or_else(|e| { - tracing::debug!("算不出价钱的统计取不到:{e}"); - (0, Vec::new()) - }) - } - None => (0, Vec::new()), - }; - Ok(Json(tw_api::PricingView { - rows, - // **这份表自己的日期,不是那个常量。**用户点过更新之后还显示 - // 内置快照的日期,等于把「你的价目表是哪天的」这个问题答错了 - // —— 而成本旁边标它的全部意义就是回答那个问题 - snapshot_date: p.snapshot_date.clone(), - unpriced_recent, - unpriced_models, - })) -} - -/// 整份写回去。**和配置文件同一条纪律**:先在内存里验一遍,再原子写。 -async fn pricing_put( - State(s): State, - Json(rows): Json>, -) -> Result, Fail> { - use std::collections::HashMap; - let mut models: HashMap> = HashMap::new(); - let mut providers: HashMap> = HashMap::new(); - for r in &rows { - if r.model.trim().is_empty() { - return Err(fail( - StatusCode::BAD_REQUEST, - "有一行没填模型名".to_string(), - )); - } - // **负价不是「便宜」,是写错了。**让它进去的话,`cheapest` 会 - // 永远选中那一家,而成本栏会往下走 - if r.input < 0.0 || r.output < 0.0 { - return Err(fail( - StatusCode::BAD_REQUEST, - format!("`{}` 的单价是负数", r.model), - )); - } - let mp = tw_pricing::ModelPrice { - input: r.input / 1_000_000.0, - output: r.output / 1_000_000.0, - cache_read: None, - cache_write_5m: None, - cache_write_1h: None, - input_above_200k: None, - output_above_200k: None, - max_input_tokens: None, - }; - match r.provider.as_ref().filter(|p| !p.trim().is_empty()) { - Some(p) => { - providers - .entry(p.clone()) - .or_default() - .insert(r.model.clone(), mp); - } - None => { - models.insert(r.model.clone(), Some(mp)); - } - } - } - let text = serde_yaml_ng::to_string(&tw_pricing::Overrides { models, providers }) - .map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; - let head = "# ThinkWatch 的用户价格覆盖(第三层)。\n\ - # 单位是**每 token** 的美元 —— 界面上填的是每百万,这里换算过了。\n\ - # 这个文件是界面写的,但手改也没问题:它只是一份普通 YAML。\n"; - let dir = s - .config_path() - .parent() - .map(std::path::Path::to_path_buf) - .unwrap_or_default(); - tw_config::store::write_atomic(&dir.join("pricing.yaml"), &format!("{head}{text}")) - .map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; - pricing_get(State(s)).await -} - -/// 价目表。**每次现建** —— 用户可能刚改过 pricing.yaml,而报价这件事 -/// 一年也点不了几次。 -pub(crate) fn prices(s: &ControlState) -> tw_pricing::Prices { - let dir = s - .config_path() - .parent() - .map(std::path::Path::to_path_buf) - .unwrap_or_default(); - tw_pricing::Prices::builtin() - // 用户点过「更新」的话,用拉回来的那份(第二层)。 - // **读不了就退回内置那份** —— 一个损坏的更新文件不该让成本栏 - // 整个变成「未知」 - .map(|mut p| { - let f = dir.join("model_prices.json"); - match std::fs::read(&f).ok().and_then(|raw| { - // **要给一个人看得懂的日期。**成本旁边标的是「这份 - // 价目表是哪天的」,而「第 20800 天」回答不了那个问题 - let date = std::fs::metadata(&f) - .and_then(|m| m.modified()) - .ok() - .map(|t| { - let dt: chrono::DateTime = t.into(); - dt.format("%Y-%m-%d").to_string() - }) - .unwrap_or_else(|| "用户更新的".to_string()); - tw_pricing::parse_upstream(&raw).ok().map(|t| (t, date)) - }) { - Some((t, date)) => { - p.replace_table(t, date); - p - } - None => p, - } - }) - .and_then(|p| p.with_overrides(&dir.join("pricing.yaml"))) - .unwrap_or_else(|e| { - tracing::warn!("价目表读不了,测速报价会说「价格未知」:{e}"); - // 建不出来时给一个空表 —— 那时每一项都是「价格未知」, - // 而那正是诚实的答案 - tw_pricing::Prices::empty() - }) -} - fn targets<'a>( cfg: &'a tw_config::Config, provider: Option<&str>, @@ -1216,6 +959,11 @@ fn history_row(r: tw_store::RequestRow) -> tw_api::HistoryRow { .and_then(|j| serde_json::from_str(j).ok()), billing: r.billing, cache_saved_micros: r.cache_saved_micros, + // 同上:解不开就当没有 + price_source: r + .price_source + .as_deref() + .and_then(|j| serde_json::from_str(j).ok()), } } diff --git a/crates/tw-control/src/pricing.rs b/crates/tw-control/src/pricing.rs new file mode 100644 index 00000000..e263cce9 --- /dev/null +++ b/crates/tw-control/src/pricing.rs @@ -0,0 +1,654 @@ +//! 价目表:默认价目表的刷新、自定义价目表的增删改、查价。 +//! +//! 两层(见 `tw_pricing`): +//! +//! - **默认价目表**是公开价格数据集。随版本内置一份;联网刷新之后存在配置 +//! 目录的数据文件里 —— 它是数据,不是配置:不进版本历史,也不该跟着配置 +//! 回滚。`pricing.auto_update` 开着时每天刷新一次。 +//! - **自定义价目表**写在 config.yaml 的 `pricing.sheets` 里,上游用 +//! `pricing:` 选一张。增删改和上游、代理走同一条路:结构进来, +//! `tw_config::edit` 落盘,改名时引用跟着改,被引用时不能删。 +//! +//! 所有金额都从网关那一份价格簿里算(`AppState::pricing`)。**这里不自己 +//! 实现计价顺序** —— 界面要显示什么价,就来问 `/pricing/query`。 + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use axum::Json; +use axum::extract::{Path as UrlPath, Query, State}; +use axum::http::StatusCode; +use axum::routing::{get, post, put}; +use serde_yaml_ng::Value; +use tw_config::edit; +use tw_config::history::Origin; +use tw_config::refs; +use tw_yaml::Step; + +use crate::resources::{checked_name, invalid, mapping, quoted}; +use crate::{ApplyError, ControlState, Fail, apply_fail, fail}; + +pub fn router() -> axum::Router { + axum::Router::new() + .route("/pricing", get(status)) + .route("/pricing/refresh", post(refresh_now)) + .route("/pricing/auto_update", put(set_auto_update)) + .route("/pricing/query", post(query)) + .route("/pricing/sheets", post(create_sheet)) + .route( + "/pricing/sheets/{name}", + put(update_sheet).delete(delete_sheet), + ) +} + +// ─────────────────────────────────────────────────────────── 默认价目表 + +/// 联网刷新下来的默认价目表,存在配置文件旁边。 +const DATA_FILE: &str = "model_prices.json"; + +/// 数据集现在两 MB 多。**上限给到 32 MB**:够它再长十倍,又不至于让一个 +/// 出错的响应把内存吃满。 +const MAX_DATASET: usize = 32 * 1024 * 1024; + +/// 整个下载的时限。网关的客户端没有整体超时(一个长任务不该被掐断), +/// 而一次后台刷新不该无限期挂着。 +const FETCH_TIMEOUT: Duration = Duration::from_secs(120); + +fn data_path(config: &Path) -> PathBuf { + config + .parent() + .map(Path::to_path_buf) + .unwrap_or_default() + .join(DATA_FILE) +} + +/// 启动时用哪份默认价目表:上次刷新存下的那份,或者随版本内置的 —— **哪份 +/// 新用哪份**。 +/// +/// 存下的那份比内置的旧,说明应用升级过、之后还没刷新成功过。存下的那份 +/// 读不了(被截断、被改坏)也用内置的:一个坏掉的数据文件不该让每一笔费用 +/// 都变成无法计价。 +pub fn load_table(config: &Path) -> tw_pricing::Table { + let saved = read_saved(&data_path(config)); + match tw_pricing::Table::builtin() { + Ok(builtin) => match saved { + Some(t) if t.date >= builtin.date => t, + _ => builtin, + }, + Err(e) => { + tracing::warn!("内置价目表加载失败:{e}"); + saved.unwrap_or_else(tw_pricing::Table::empty) + } + } +} + +fn read_saved(path: &Path) -> Option { + let raw = match std::fs::read(path) { + Ok(raw) => raw, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return None, + Err(e) => { + tracing::warn!("{} 读不了,按内置价目表计价:{e}", path.display()); + return None; + } + }; + // 数据日期是这份文件写下的那天,也就是刷新成功的那天 + let saved_at = saved_at(path)?; + match tw_pricing::Table::fetched(&raw, local_date(saved_at)) { + Ok(t) => Some(t), + Err(e) => { + tracing::warn!("{} 读不通,按内置价目表计价:{e}", path.display()); + None + } + } +} + +fn saved_at(path: &Path) -> Option { + std::fs::metadata(path).and_then(|m| m.modified()).ok() +} + +fn local_date(t: SystemTime) -> String { + let dt: chrono::DateTime = t.into(); + dt.format("%Y-%m-%d").to_string() +} + +fn millis(t: SystemTime) -> u64 { + t.duration_since(UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) +} + +/// 刷新默认价目表的那个后台任务,以及它最近一次的结果。 +pub struct Updater { + /// 去哪儿拉。**只能在代码里给,不从配置读** —— 见 `tw_pricing::UPDATE_URL` + url: String, + schedule: Schedule, + last: std::sync::Mutex, + /// 同一时间只有一次刷新在跑 + running: tokio::sync::Mutex<()>, + /// 定期刷新刚被打开:不用等到下一轮 + wake: tokio::sync::Notify, +} + +/// 什么时候去刷新。 +#[derive(Debug, Clone, Copy)] +pub struct Schedule { + /// 启动之后多久第一次检查。**不在启动那一刻** —— 那时网关在起、客户端在连 + pub first_check: Duration, + /// 多久看一次到没到时间。看一次只是比较时间,不联网。 + /// + /// **不是睡满一整天再醒。**笔记本合盖时单调时钟不走,睡「24 小时」 + /// 可能睡上好几天;按墙上时间一轮轮比,开盖之后下一轮就会刷新。 + pub tick: Duration, + /// 上次刷新成功之后多久再刷新 + pub every: Duration, + /// 失败之后多久再试。离线的时候每一轮都去撞一次没有意义 + pub retry: Duration, +} + +impl Default for Schedule { + fn default() -> Self { + Self { + first_check: Duration::from_secs(60), + tick: Duration::from_secs(10 * 60), + every: Duration::from_secs(24 * 3600), + retry: Duration::from_secs(3600), + } + } +} + +#[derive(Debug, Clone, Default)] +struct Attempt { + at_ms: Option, + error: Option, +} + +#[derive(Debug, thiserror::Error)] +pub enum RefreshError { + #[error("{0}")] + Fetch(String), + #[error("下载到的内容不是价格数据集:{0}")] + Dataset(String), + #[error("价目表无法保存:{0}")] + Save(String), +} + +impl Default for Updater { + fn default() -> Self { + Self::new(tw_pricing::UPDATE_URL, Schedule::default()) + } +} + +impl Updater { + pub fn new(url: impl Into, schedule: Schedule) -> Self { + Self { + url: url.into(), + schedule, + last: Default::default(), + running: Default::default(), + wake: Default::default(), + } + } + + fn last(&self) -> Attempt { + self.last.lock().map(|g| g.clone()).unwrap_or_default() + } + + fn record(&self, r: &Result, at: SystemTime) { + if let Ok(mut last) = self.last.lock() { + last.at_ms = Some(millis(at)); + last.error = r.as_ref().err().map(ToString::to_string); + } + } + + /// 到没到该刷新的时候。 + fn due(&self, config: &Path, now: SystemTime) -> bool { + let fresh = saved_at(&data_path(config)) + // 文件时间比现在还晚(时钟往回调过):算刚刷新过,而不是每一轮都去拉 + .map(|t| now.duration_since(t).unwrap_or_default()) + .is_some_and(|age| age < self.schedule.every); + if fresh { + return false; + } + match self.last() { + Attempt { + at_ms: Some(at), + error: Some(_), + } => millis(now).saturating_sub(at) >= self.schedule.retry.as_millis() as u64, + _ => true, + } + } + + async fn pause(&self, d: Duration) { + tokio::select! { + _ = tokio::time::sleep(d) => {} + _ = self.wake.notified() => {} + } + } +} + +/// 起那个后台任务。 +pub fn spawn(s: ControlState) { + tokio::spawn(async move { + let u = s.price_updater.clone(); + u.pause(u.schedule.first_check).await; + loop { + if s.config().pricing.auto_update + && u.due(s.config_path(), SystemTime::now()) + && let Err(e) = refresh(&s).await + { + tracing::info!("默认价目表刷新失败,稍后重试:{e}"); + } + u.pause(u.schedule.tick).await; + } + }); +} + +/// 刷新一次,返回有几个模型的价格变了。 +/// +/// **先落盘再换表** —— 换了但没存下来的话,重启之后又回到旧表,而界面 +/// 刚说过已经更新。 +pub async fn refresh(s: &ControlState) -> Result { + let u = s.price_updater.clone(); + let _one = u.running.lock().await; + let result = match fetch(s.http(), &u.url).await { + Ok(raw) => { + let s = s.clone(); + // 解析两 MB 的 JSON、写文件:都不该占着异步线程 + tokio::task::spawn_blocking(move || apply(&s, &raw)) + .await + .unwrap_or_else(|e| Err(RefreshError::Save(e.to_string()))) + } + Err(e) => Err(e), + }; + u.record(&result, SystemTime::now()); + result +} + +async fn fetch(http: &reqwest::Client, url: &str) -> Result, RefreshError> { + let mut resp = http + .get(url) + .timeout(FETCH_TIMEOUT) + .send() + .await + .map_err(|e| RefreshError::Fetch(format!("连接价格数据源失败:{}", chain(&e))))?; + if !resp.status().is_success() { + return Err(RefreshError::Fetch(format!( + "价格数据源返回 HTTP {}", + resp.status().as_u16() + ))); + } + let mut raw = Vec::new(); + while let Some(chunk) = resp + .chunk() + .await + .map_err(|e| RefreshError::Fetch(format!("下载中断:{}", chain(&e))))? + { + if raw.len() + chunk.len() > MAX_DATASET { + return Err(RefreshError::Dataset(format!( + "大小超过 {} MB", + MAX_DATASET / 1024 / 1024 + ))); + } + raw.extend_from_slice(&chunk); + } + Ok(raw) +} + +fn apply(s: &ControlState, raw: &[u8]) -> Result { + let table = tw_pricing::Table::fetched(raw, local_date(SystemTime::now())) + .map_err(|e| RefreshError::Dataset(e.to_string()))?; + // 解析成功就一定是 UTF-8(JSON 只能是) + let text = std::str::from_utf8(raw).map_err(|e| RefreshError::Dataset(e.to_string()))?; + tw_config::store::write_atomic(&data_path(s.config_path()), text) + .map_err(|e| RefreshError::Save(e.to_string()))?; + let changed = table.changed_from(s.gateway.pricing.load().table()); + s.gateway.set_price_table(table); + Ok(changed) +} + +/// reqwest 的错误只说最外面一层(「error sending request」),原因在里面。 +fn chain(e: &dyn std::error::Error) -> String { + let mut out = e.to_string(); + let mut cur = e.source(); + while let Some(c) = cur { + out.push(':'); + out.push_str(&c.to_string()); + cur = c.source(); + } + out +} + +async fn status(State(s): State) -> Json { + Json(pricing_status(&s).await) +} + +async fn pricing_status(s: &ControlState) -> tw_api::PricingStatus { + let (date, source, models) = { + let book = s.gateway.pricing.load(); + let t = book.table(); + (t.date.clone(), t.source.slug().to_string(), t.len()) + }; + let last = s.price_updater.last(); + // **拿不到存储就是 0** —— 观测层起不来时网关照常转发,这一页也该照常打开 + let (unpriced_recent, unpriced_models) = match &s.store { + Some(st) => st.lock().await.db().unpriced_recent(7).unwrap_or_else(|e| { + tracing::debug!("无法计价的请求统计取不到:{e}"); + (0, Vec::new()) + }), + None => (0, Vec::new()), + }; + tw_api::PricingStatus { + date, + source, + models, + auto_update: s.config().pricing.auto_update, + checked_at_ms: last.at_ms, + error: last.error, + unpriced_recent, + unpriced_models, + } +} + +/// 立即刷新。**不看定期刷新开没开** —— 这是用户自己点的。 +async fn refresh_now( + State(s): State, +) -> Result, Fail> { + let changed = refresh(&s).await.map_err(|e| { + let code = match e { + RefreshError::Save(_) => StatusCode::INTERNAL_SERVER_ERROR, + _ => StatusCode::BAD_GATEWAY, + }; + fail(code, e) + })?; + Ok(Json(tw_api::PricingRefreshed { + status: pricing_status(&s).await, + changed, + })) +} + +async fn set_auto_update( + State(s): State, + Json(req): Json, +) -> Result, Fail> { + let version = s + .cfg + .transform(req.base_version.as_deref(), Origin::Ui, |text, _| { + // 开着是默认值,**默认值不写进文件** + let value = (!req.on).then_some(Value::Bool(false)); + Ok(edit::set( + text, + &[Step::key("pricing"), Step::key("auto_update")], + value.as_ref(), + )?) + }) + .await + .map_err(apply_fail)?; + if req.on { + s.price_updater.wake.notify_one(); + } + Ok(Json(tw_api::ConfigWritten { version })) +} + +// ─────────────────────────────────────────────────────────── 查价 + +/// 搜索默认最多返回几个。 +const SEARCH_LIMIT: usize = 50; +const SEARCH_LIMIT_MAX: usize = 500; + +async fn query( + State(s): State, + Json(q): Json, +) -> Result, Fail> { + let loaded = s.gateway.pricing.load_full(); + let (book, sheet) = match q.sheet { + tw_api::SheetRef::Default => (loaded, None), + tw_api::SheetRef::Named { name } => { + if loaded.config().sheet(&name).is_none() { + return Err(fail( + StatusCode::NOT_FOUND, + format!("没有叫「{name}」的价目表"), + )); + } + (loaded, Some(name)) + } + tw_api::SheetRef::Draft { sheet } => { + let def = sheet_def(&sheet).map_err(|e| fail(StatusCode::BAD_REQUEST, e))?; + let name = def.name.clone(); + (Arc::new(loaded.with_draft(def)), Some(name)) + } + }; + let (models, matched) = if q.models.is_empty() { + search( + &book, + sheet.as_deref(), + q.search.as_deref().unwrap_or_default(), + q.limit.unwrap_or(SEARCH_LIMIT).min(SEARCH_LIMIT_MAX), + ) + } else { + let n = q.models.len(); + (q.models, n) + }; + let date = &book.table().date; + let items = models + .into_iter() + .map(|model| { + let r = book.resolve(sheet.as_deref(), &model); + tw_api::ResolvedPrice { + price: r + .as_ref() + .map(|r| price_fields(&tw_pricing::PerMillion::of(&r.price))), + source: r.as_ref().map(|r| tw_store::price_source(&r.source, date)), + estimated: r.as_ref().is_some_and(|r| r.cross_platform), + max_input_tokens: r.as_ref().and_then(|r| r.price.max_input_tokens), + model, + } + }) + .collect(); + Ok(Json(tw_api::PriceQueryResult { items, matched })) +} + +/// 按名字搜模型:默认价目表里的,加上这张价目表单独覆盖的。 +/// +/// **不带平台前缀的名字排在前面。**数据集里同一个模型常有七八个写法 +/// (`bedrock/…`、`vertex_ai/…`、`anthropic.…-v1:0`),客户端发来的是不带 +/// 前缀的那个。 +fn search( + book: &tw_pricing::PriceBook, + sheet: Option<&str>, + needle: &str, + limit: usize, +) -> (Vec, usize) { + let needle = needle.trim().to_lowercase(); + let mut names: std::collections::BTreeSet<&str> = book.table().models().collect(); + if let Some(def) = sheet.and_then(|n| book.config().sheet(n)) { + names.extend(def.models.keys().map(String::as_str)); + } + let mut hits: Vec<&str> = names + .into_iter() + .filter(|m| needle.is_empty() || m.to_lowercase().contains(&needle)) + .collect(); + let prefixed = |m: &str| m.contains('/') || m.contains(':'); + hits.sort_by_key(|m| prefixed(m)); + let matched = hits.len(); + ( + hits.into_iter().take(limit).map(str::to_string).collect(), + matched, + ) +} + +// ─────────────────────────────────────────────────────────── 自定义价目表 + +async fn create_sheet( + State(s): State, + Json(req): Json, +) -> Result, Fail> { + let version = s + .cfg + .transform(req.base_version.as_deref(), Origin::Ui, |text, _| { + let def = sheet_def(&req.sheet).map_err(invalid)?; + Ok(edit::upsert( + text, + edit::PRICE_SHEETS, + None, + &mapping(&def)?, + )?) + }) + .await + .map_err(apply_fail)?; + Ok(Json(tw_api::ConfigWritten { version })) +} + +async fn update_sheet( + State(s): State, + UrlPath(name): UrlPath, + Json(req): Json, +) -> Result, Fail> { + let version = s + .cfg + .transform(req.base_version.as_deref(), Origin::Ui, |text, cfg| { + let def = sheet_def(&req.sheet).map_err(invalid)?; + let mut out = edit::upsert(text, edit::PRICE_SHEETS, Some(&name), &mapping(&def)?)?; + if def.name != name { + // **和那一张在同一个版本里改** —— 分两次写的话,中间那一版的 + // 上游选着一张不存在的价目表,会被校验拒掉 + out = refs::rename_sheet(&out, cfg, &name, &def.name)?; + } + Ok(out) + }) + .await + .map_err(apply_fail)?; + Ok(Json(tw_api::ConfigWritten { version })) +} + +async fn delete_sheet( + State(s): State, + UrlPath(name): UrlPath, + Query(q): Query, +) -> Result, Fail> { + let version = s + .cfg + .transform(q.base_version.as_deref(), Origin::Ui, |text, cfg| { + let users = refs::sheet_users(cfg, &name); + if !users.is_empty() { + return Err(ApplyError::InUse(format!( + "价目表「{name}」仍被上游{}使用,解除后才能删除", + quoted(&users) + ))); + } + Ok(edit::remove(text, edit::PRICE_SHEETS, &name)?) + }) + .await + .map_err(apply_fail)?; + Ok(Json(tw_api::ConfigWritten { version })) +} + +/// 概览里的自定义价目表。 +pub(crate) fn sheet_views(cfg: &tw_config::Config) -> Vec { + cfg.pricing + .sheets + .iter() + .map(|sh| tw_api::PriceSheetView { + name: sh.name.clone(), + multiplier: sh.multiplier, + overrides: sh.models.len(), + used_by: refs::sheet_users(cfg, &sh.name), + }) + .collect() +} + +fn sheet_def(input: &tw_api::PriceSheetInput) -> Result { + let def = tw_pricing::SheetDef { + name: checked_name(&input.name, "价目表")?, + multiplier: input.multiplier, + models: input + .models + .iter() + .map(|(m, p)| (m.clone(), per_million(p))) + .collect(), + }; + def.validate().map_err(|e| e.to_string())?; + Ok(def) +} + +fn per_million(p: &tw_api::PriceFields) -> tw_pricing::PerMillion { + tw_pricing::PerMillion { + input: p.input, + output: p.output, + cache_read: p.cache_read, + cache_write_5m: p.cache_write_5m, + cache_write_1h: p.cache_write_1h, + input_above_200k: p.input_above_200k, + output_above_200k: p.output_above_200k, + } +} + +fn price_fields(p: &tw_pricing::PerMillion) -> tw_api::PriceFields { + tw_api::PriceFields { + input: p.input, + output: p.output, + cache_read: p.cache_read, + cache_write_5m: p.cache_write_5m, + cache_write_1h: p.cache_write_1h, + input_above_200k: p.input_above_200k, + output_above_200k: p.output_above_200k, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_saved_table_older_than_the_builtin_one_is_not_used() { + let d = tempfile::tempdir().unwrap(); + let config = d.path().join("config.yaml"); + std::fs::write( + data_path(&config), + r#"{"m":{"input_cost_per_token":1e-6,"output_cost_per_token":2e-6}}"#, + ) + .unwrap(); + // 刚写的:比内置快照新 + let t = load_table(&config); + assert_eq!(t.source, tw_pricing::TableSource::Fetched); + assert_eq!(t.len(), 1); + + // 改成内置快照之前的日期:应用升级过,那份过时了 + let old = SystemTime::UNIX_EPOCH + Duration::from_secs(1_600_000_000); + std::fs::File::options() + .write(true) + .open(data_path(&config)) + .unwrap() + .set_modified(old) + .unwrap(); + assert_eq!(load_table(&config).source, tw_pricing::TableSource::Builtin); + } + + #[test] + fn a_broken_saved_table_falls_back_to_the_builtin_one() { + let d = tempfile::tempdir().unwrap(); + let config = d.path().join("config.yaml"); + std::fs::write(data_path(&config), "{\"truncated").unwrap(); + assert_eq!(load_table(&config).source, tw_pricing::TableSource::Builtin); + } + + #[test] + fn a_refresh_is_due_once_the_saved_table_is_a_day_old_and_a_failure_waits_an_hour() { + let d = tempfile::tempdir().unwrap(); + let config = d.path().join("config.yaml"); + let u = Updater::default(); + let now = SystemTime::now(); + // 从没刷新过 + assert!(u.due(&config, now)); + // 刚刷新过 + std::fs::write(data_path(&config), "{}").unwrap(); + assert!(!u.due(&config, now)); + // 一天之后 + let tomorrow = now + Duration::from_secs(24 * 3600 + 1); + assert!(u.due(&config, tomorrow)); + // 那时刷新失败了:一小时之内不再试 + u.record(&Err(RefreshError::Fetch("离线".into())), tomorrow); + assert!(!u.due(&config, tomorrow + Duration::from_secs(60))); + assert!(u.due(&config, tomorrow + Duration::from_secs(3601))); + } +} diff --git a/crates/tw-control/src/replay.rs b/crates/tw-control/src/replay.rs index eda753dc..485f45f9 100644 --- a/crates/tw-control/src/replay.rs +++ b/crates/tw-control/src/replay.rs @@ -104,12 +104,9 @@ pub async fn quote( // 没有的话按字节粗估(和路由用的是同一个系数) let input = row.input_tokens.unwrap_or((raw.len() / 4) as i64).max(0) as u64; let output = row.output_tokens.unwrap_or(0).max(0) as u64; - let prices = crate::prices(&s); - let subscription = s - .gateway - .quotas() - .get(&provider.name) - .is_some_and(|q| !q.is_empty()); + let book = s.gateway.pricing.load(); + // 和记账同一个口径:配置里写明了,或者最近一次响应里报过额度 + let subscription = s.gateway.billing_of(provider) == tw_config::Billing::Subscription; let usage = tw_pricing::Usage { input, // 输出按上次那条的实际输出估。**它只是个估计**,模型这次可能 @@ -123,7 +120,8 @@ pub async fn quote( format!("不计费,但会消耗约 {} tokens 的额度", input + usage.output), ) } else { - match prices.cost(&row.model, &usage, false) { + // **按要重放到的那个上游查价**,不是原来那条走的上游 + match book.cost_for(&provider.name, &row.model, &usage, false) { tw_pricing::Cost::Known(m) | tw_pricing::Cost::Estimated(m) => ( Some(m), // **金额再小也要显示。**用户按下按钮时有权知道自己在花什么 @@ -149,7 +147,7 @@ pub async fn quote( // 脱敏在重放里照做,但用户有权在按下去之前知道 will_redact: !tw_gateway::guard::effective_kinds(provider, &tw_engine::Guard::default()) .is_empty(), - pricing_date: tw_pricing::SNAPSHOT_DATE.to_string(), + pricing_date: book.table().date.clone(), })) } diff --git a/crates/tw-control/src/resources.rs b/crates/tw-control/src/resources.rs index 9e27a27f..b72565c6 100644 --- a/crates/tw-control/src/resources.rs +++ b/crates/tw-control/src/resources.rs @@ -219,6 +219,7 @@ fn to_provider( .transpose()?, proxy: input.proxy.trim().to_string(), on_proxy_fail: slug("代理不可用时的处理", &input.on_proxy_fail)?, + pricing: input.pricing.clone(), }) } @@ -330,11 +331,7 @@ async fn delete_proxy( if !users.is_empty() { return Err(ApplyError::InUse(format!( "代理「{name}」仍被上游{}使用,解除后才能删除", - users - .iter() - .map(|u| format!("「{u}」")) - .collect::>() - .join("、") + quoted(&users) ))); } Ok(edit::remove(text, edit::PROXIES, &name)?) @@ -411,7 +408,7 @@ fn to_proxy( // ─────────────────────────────────────────────────────────── 共用 -fn checked_name(raw: &str, what: &str) -> Result { +pub(crate) fn checked_name(raw: &str, what: &str) -> Result { if raw.trim().is_empty() { return Err(format!("{what}名称不能为空")); } @@ -427,7 +424,7 @@ fn slug(what: &str, v: &str) -> Result(v: &T) -> Result { +pub(crate) fn mapping(v: &T) -> Result { match serde_yaml_ng::to_value(v) { Ok(Value::Mapping(m)) => Ok(m), Ok(_) => Err(invalid("写不成一个映射".to_string())), @@ -435,7 +432,7 @@ fn mapping(v: &T) -> Result ApplyError { +pub(crate) fn invalid(msg: String) -> ApplyError { ApplyError::Edit(EditError::Unwritable(msg)) } @@ -446,6 +443,15 @@ fn not_found(what: &'static str, name: &str) -> ApplyError { }) } +/// 「「relay-hk」、「relay-sg」」 +pub(crate) fn quoted(names: &[String]) -> String { + names + .iter() + .map(|n| format!("「{n}」")) + .collect::>() + .join("、") +} + /// 「路由「默认」的规则「长上下文」、策略组「pool」」 fn describe(refs: &[ProviderRef]) -> String { refs.iter() diff --git a/crates/tw-control/tests/adopt.rs b/crates/tw-control/tests/adopt.rs index 11d8fd40..81625280 100644 --- a/crates/tw-control/tests/adopt.rs +++ b/crates/tw-control/tests/adopt.rs @@ -39,6 +39,7 @@ fn bed_with_store(store: Option (tempfile::TempDir, axum::Router) { gateway_addr: None, store: None, started: std::time::Instant::now(), + price_updater: Default::default(), home: d.path().join("home"), }; (d, tw_control::router(state)) diff --git a/crates/tw-control/tests/m4_acceptance.rs b/crates/tw-control/tests/m4_acceptance.rs index c84fbab3..39de6785 100644 --- a/crates/tw-control/tests/m4_acceptance.rs +++ b/crates/tw-control/tests/m4_acceptance.rs @@ -42,6 +42,7 @@ fn bed() -> Bed { gateway_addr: None, store: None, started: std::time::Instant::now(), + price_updater: Default::default(), // **测试里绝不能碰开发者自己的配置** home: home.clone(), }; diff --git a/crates/tw-control/tests/pricing.rs b/crates/tw-control/tests/pricing.rs new file mode 100644 index 00000000..be370403 --- /dev/null +++ b/crates/tw-control/tests/pricing.rs @@ -0,0 +1,451 @@ +//! 价目表:自定义价目表的增删改、查价、默认价目表的刷新。 +//! +//! 写配置的那几条,断言落在**文件本身**上;刷新的那几条,用一个本地的 +//! 假数据源 —— 测试不联网,也不碰开发者自己的配置目录。 + +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Duration; + +use axum::body::Body; +use axum::http::{Request, StatusCode}; +use tower::ServiceExt; +use tw_control::pricing::{Schedule, Updater}; +use tw_control::{ConfigManager, ControlState}; + +const BASE: &str = "version: 1 +clients: + - name: c + key: tw-k +providers: + - name: 官方 + base_url: https://api.anthropic.com + key: sk-official + - name: relay-hk + base_url: https://relay.example + key: sk-relay +"; + +struct Bed { + dir: tempfile::TempDir, + state: ControlState, + app: axum::Router, +} + +impl Bed { + fn file(&self) -> String { + std::fs::read_to_string(self.dir.path().join("config.yaml")).unwrap() + } + fn parsed(&self) -> tw_config::Config { + tw_config::try_parse(&self.file()).unwrap() + } + fn data_file(&self) -> std::path::PathBuf { + self.dir.path().join("model_prices.json") + } +} + +fn bed_with(yaml: &str, updater: Updater) -> Bed { + let d = tempfile::tempdir().unwrap(); + let p = d.path().join("config.yaml"); + std::fs::write(&p, yaml).unwrap(); + let cfg = tw_config::try_parse(yaml).unwrap(); + let gw = tw_gateway::AppState::new(cfg).unwrap(); + let bus = gw.bus.clone(); + let state = ControlState { + cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus)), + gateway: gw, + gateway_addr: None, + store: None, + started: std::time::Instant::now(), + price_updater: Arc::new(updater), + // **测试里绝不能碰开发者自己的配置** + home: d.path().join("home"), + }; + Bed { + app: tw_control::router(state.clone()), + state, + dir: d, + } +} + +fn bed(yaml: &str) -> Bed { + bed_with(yaml, Updater::default()) +} + +async fn call( + app: &axum::Router, + method: &str, + path: &str, + body: serde_json::Value, +) -> (StatusCode, serde_json::Value) { + let r = app + .clone() + .oneshot( + Request::builder() + .method(method) + .uri(path) + .header("content-type", "application/json") + .body(Body::from(body.to_string())) + .unwrap(), + ) + .await + .unwrap(); + let st = r.status(); + let b = axum::body::to_bytes(r.into_body(), 1 << 22).await.unwrap(); + let text = String::from_utf8_lossy(&b).to_string(); + let v = serde_json::from_str(&text).unwrap_or(serde_json::Value::String(text)); + (st, v) +} + +/// 一条覆盖价:每百万 tokens 的美元,五个字段都写明。 +fn full(input: f64, output: f64) -> serde_json::Value { + serde_json::json!({ + "input": input, + "output": output, + "cache_read": input / 10.0, + "cache_write_5m": input * 1.25, + "cache_write_1h": input * 2.0, + }) +} + +fn relay_sheet(name: &str) -> serde_json::Value { + serde_json::json!({ "sheet": { + "name": name, + "multiplier": 0.8, + "models": { "claude-sonnet-4-5-thinking": full(3.0, 15.0) }, + }}) +} + +// ─────────────────────────────────────────────────────────── 自定义价目表 + +#[tokio::test] +async fn a_sheet_is_created_chosen_renamed_and_deleted_only_once_nobody_uses_it() { + let b = bed(BASE); + let (st, body) = call(&b.app, "POST", "/pricing/sheets", relay_sheet("中转协议价")).await; + assert_eq!(st, StatusCode::OK, "{body}"); + let sheet = b.parsed().pricing.sheets[0].clone(); + assert_eq!(sheet.multiplier, 0.8); + assert_eq!( + sheet.models["claude-sonnet-4-5-thinking"].cache_write_1h, + 6.0 + ); + + // 上游选它 + let (st, body) = call( + &b.app, + "PUT", + "/providers/relay-hk", + serde_json::json!({ "provider": { "name": "relay-hk", "pricing": "中转协议价" } }), + ) + .await; + assert_eq!(st, StatusCode::OK, "{body}"); + let (_, ov) = call(&b.app, "GET", "/overview", serde_json::json!(null)).await; + assert_eq!( + ov["price_sheets"][0]["used_by"], + serde_json::json!(["relay-hk"]) + ); + assert_eq!(ov["price_sheets"][0]["overrides"], 1); + assert_eq!(ov["providers"][1]["pricing"], "中转协议价"); + + // 改名:选了它的上游跟着改,同一个版本 + let (st, body) = call( + &b.app, + "PUT", + "/pricing/sheets/中转协议价", + relay_sheet("中转价"), + ) + .await; + assert_eq!(st, StatusCode::OK, "{body}"); + assert_eq!(b.parsed().providers[1].pricing.as_deref(), Some("中转价")); + + // 还在用:删不掉,并且说清是谁在用 + let (st, body) = call( + &b.app, + "DELETE", + "/pricing/sheets/中转价", + serde_json::json!(null), + ) + .await; + assert_eq!(st, StatusCode::CONFLICT, "{body}"); + assert!(body.as_str().unwrap().contains("relay-hk"), "{body}"); + + // 上游改回默认价目表之后才能删;删完不留空段 + let (st, body) = call( + &b.app, + "PUT", + "/providers/relay-hk", + serde_json::json!({ "provider": { "name": "relay-hk" } }), + ) + .await; + assert_eq!(st, StatusCode::OK, "{body}"); + let (st, body) = call( + &b.app, + "DELETE", + "/pricing/sheets/中转价", + serde_json::json!(null), + ) + .await; + assert_eq!(st, StatusCode::OK, "{body}"); + assert_eq!(b.file(), BASE); +} + +#[tokio::test] +async fn an_upstream_cannot_choose_a_sheet_that_does_not_exist() { + // 静默退回默认价的话,算出来的钱看起来正常,而折扣从没生效过 + let b = bed(BASE); + let (st, body) = call( + &b.app, + "PUT", + "/providers/relay-hk", + serde_json::json!({ "provider": { "name": "relay-hk", "pricing": "没有这张" } }), + ) + .await; + assert_eq!(st, StatusCode::BAD_REQUEST, "{body}"); + assert!(body.as_str().unwrap().contains("没有这张"), "{body}"); + assert_eq!(b.file(), BASE); +} + +#[tokio::test] +async fn a_sheet_with_a_half_written_override_is_refused_with_the_reason() { + let b = bed(BASE); + let (st, body) = call( + &b.app, + "POST", + "/pricing/sheets", + serde_json::json!({ "sheet": { + "name": "中转", + "models": { "m": { + "input": 1, "output": 2, "cache_read": 0.1, "cache_write_5m": 1.25, + "cache_write_1h": 2, "input_above_200k": 2, + }}, + }}), + ) + .await; + assert_eq!(st, StatusCode::BAD_REQUEST, "{body}"); + assert!(body.as_str().unwrap().contains("长上下文"), "{body}"); + assert_eq!(b.file(), BASE); +} + +// ─────────────────────────────────────────────────────────── 查价 + +#[tokio::test] +async fn a_saved_sheet_prices_each_model_and_says_where_the_price_came_from() { + let b = bed(BASE); + call(&b.app, "POST", "/pricing/sheets", relay_sheet("中转协议价")).await; + let (st, r) = call( + &b.app, + "POST", + "/pricing/query", + serde_json::json!({ + "sheet": { "kind": "named", "name": "中转协议价" }, + "models": ["claude-sonnet-4-5", "claude-sonnet-4-5-thinking", "中转站自己起的名字"], + }), + ) + .await; + assert_eq!(st, StatusCode::OK, "{r}"); + let items = &r["items"]; + assert_eq!(items[0]["source"]["kind"], "scaled"); + assert_eq!(items[0]["source"]["multiplier"], 0.8); + assert_eq!(items[0]["price"]["input"], 2.4); + // 倍率同样作用于缓存单价 + assert_eq!(items[0]["price"]["cache_read"], 0.24); + assert_eq!(items[0]["max_input_tokens"], 200_000); + assert_eq!(items[1]["source"]["kind"], "override"); + assert_eq!(items[1]["price"]["input"], 3.0); + // 无法计价就是无法计价,不是 0 + assert!(items[2].get("price").is_none(), "{r}"); + assert!(items[2].get("source").is_none(), "{r}"); +} + +#[tokio::test] +async fn a_draft_is_priced_without_being_saved() { + let b = bed(BASE); + let (st, r) = call( + &b.app, + "POST", + "/pricing/query", + serde_json::json!({ + "sheet": { "kind": "draft", "sheet": { "name": "草稿", "multiplier": 0.5 } }, + "models": ["claude-sonnet-4-5"], + }), + ) + .await; + assert_eq!(st, StatusCode::OK, "{r}"); + assert_eq!(r["items"][0]["price"]["input"], 1.5); + assert_eq!(b.file(), BASE); + + let (st, _) = call( + &b.app, + "POST", + "/pricing/query", + serde_json::json!({ "sheet": { "kind": "named", "name": "没有这张" }, "models": ["m"] }), + ) + .await; + assert_eq!(st, StatusCode::NOT_FOUND); +} + +#[tokio::test] +async fn a_search_lists_the_names_clients_send_before_platform_keys() { + let b = bed(BASE); + let (st, r) = call( + &b.app, + "POST", + "/pricing/query", + serde_json::json!({ "sheet": { "kind": "default" }, "search": "Claude-Sonnet-4-5", "limit": 3 }), + ) + .await; + assert_eq!(st, StatusCode::OK, "{r}"); + let items = r["items"].as_array().unwrap(); + assert_eq!(items.len(), 3); + assert!(r["matched"].as_u64().unwrap() > 3, "{r}"); + let first = items[0]["model"].as_str().unwrap(); + assert!(!first.contains('/') && !first.contains(':'), "{first}"); +} + +// ─────────────────────────────────────────────────────────── 默认价目表 + +#[tokio::test] +async fn turning_auto_update_off_writes_one_line_and_turning_it_back_on_removes_it() { + let b = bed(BASE); + let (st, body) = call(&b.app, "GET", "/pricing", serde_json::json!(null)).await; + assert_eq!(st, StatusCode::OK, "{body}"); + assert_eq!(body["auto_update"], true); + assert_eq!(body["source"], "builtin"); + + let (st, body) = call( + &b.app, + "PUT", + "/pricing/auto_update", + serde_json::json!({ "on": false }), + ) + .await; + assert_eq!(st, StatusCode::OK, "{body}"); + assert_eq!(b.file(), format!("{BASE}pricing:\n auto_update: false\n")); + let (_, body) = call(&b.app, "GET", "/pricing", serde_json::json!(null)).await; + assert_eq!(body["auto_update"], false); + + call( + &b.app, + "PUT", + "/pricing/auto_update", + serde_json::json!({ "on": true }), + ) + .await; + assert_eq!(b.file(), BASE); +} + +/// 一个假的价格数据源。返回它的地址和被请求了几次。 +async fn price_source(status: u16, body: &'static str) -> (String, Arc) { + let hits = Arc::new(AtomicUsize::new(0)); + let h = hits.clone(); + let app = axum::Router::new().fallback(move || { + let h = h.clone(); + async move { + h.fetch_add(1, Ordering::SeqCst); + (StatusCode::from_u16(status).unwrap(), body) + } + }); + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = l.local_addr().unwrap(); + tokio::spawn(async move { + axum::serve(l, app).await.unwrap(); + }); + (format!("http://{addr}/model_prices.json"), hits) +} + +const DATASET: &str = r#"{ + "claude-sonnet-4-5": { "input_cost_per_token": 4e-6, "output_cost_per_token": 2e-5, "max_input_tokens": 200000 }, + "新出的模型": { "input_cost_per_token": 1e-6, "output_cost_per_token": 2e-6 } +}"#; + +#[tokio::test] +async fn a_refresh_saves_the_new_table_and_prices_with_it_straight_away() { + let (url, hits) = price_source(200, DATASET).await; + let b = bed_with(BASE, Updater::new(url, Schedule::default())); + let (st, r) = call(&b.app, "POST", "/pricing/refresh", serde_json::json!(null)).await; + assert_eq!(st, StatusCode::OK, "{r}"); + assert_eq!(hits.load(Ordering::SeqCst), 1); + assert!(r["changed"].as_u64().unwrap() > 0, "{r}"); + let status = &r["status"]; + assert_eq!(status["source"], "fetched"); + assert_eq!(status["models"], 2); + assert_eq!( + status["date"], + chrono::Local::now().format("%Y-%m-%d").to_string() + ); + assert!(status["checked_at_ms"].as_u64().is_some(), "{r}"); + assert!(status.get("error").is_none(), "{r}"); + + // 存下来了:重启之后用的还是这一份 + assert_eq!(std::fs::read_to_string(b.data_file()).unwrap(), DATASET); + let reloaded = tw_control::pricing::load_table(&b.dir.path().join("config.yaml")); + assert_eq!(reloaded.len(), 2); + + // 不用重启就按新表计价 + let (_, q) = call( + &b.app, + "POST", + "/pricing/query", + serde_json::json!({ "sheet": { "kind": "default" }, "models": ["新出的模型", "claude-sonnet-4-5"] }), + ) + .await; + assert_eq!(q["items"][0]["price"]["input"], 1.0); + assert_eq!(q["items"][1]["price"]["input"], 4.0); + assert_eq!( + b.state.gateway.pricing.load().table().date, + status["date"].as_str().unwrap() + ); +} + +#[tokio::test] +async fn a_failed_refresh_keeps_the_table_and_reports_why() { + for (code, body, says) in [ + (500, "internal error", "HTTP 500"), + (200, r#"{"error": "rate limited"}"#, "不是价格数据集"), + ] { + let (url, _) = price_source(code, body).await; + let b = bed_with(BASE, Updater::new(url, Schedule::default())); + let (st, r) = call(&b.app, "POST", "/pricing/refresh", serde_json::json!(null)).await; + assert_eq!(st, StatusCode::BAD_GATEWAY, "{r}"); + assert!(r.as_str().unwrap().contains(says), "{r}"); + let (_, status) = call(&b.app, "GET", "/pricing", serde_json::json!(null)).await; + assert_eq!(status["source"], "builtin"); + assert!(status["error"].as_str().unwrap().contains(says), "{status}"); + assert!(!b.data_file().exists()); + } +} + +#[tokio::test] +async fn the_background_refresh_waits_while_auto_update_is_off_and_runs_once_it_is_on() { + let (url, hits) = price_source(200, DATASET).await; + let quick = Schedule { + first_check: Duration::from_millis(20), + tick: Duration::from_millis(20), + every: Duration::from_secs(24 * 3600), + retry: Duration::from_secs(3600), + }; + let b = bed_with( + &format!("{BASE}pricing:\n auto_update: false\n"), + Updater::new(url, quick), + ); + tw_control::pricing::spawn(b.state.clone()); + tokio::time::sleep(Duration::from_millis(300)).await; + assert_eq!(hits.load(Ordering::SeqCst), 0, "关着的时候不该联网"); + + let (st, body) = call( + &b.app, + "PUT", + "/pricing/auto_update", + serde_json::json!({ "on": true }), + ) + .await; + assert_eq!(st, StatusCode::OK, "{body}"); + let deadline = std::time::Instant::now() + Duration::from_secs(10); + while !b.data_file().exists() && std::time::Instant::now() < deadline { + tokio::time::sleep(Duration::from_millis(20)).await; + } + assert!(b.data_file().exists(), "打开之后没有刷新"); + // 刚刷新过:之后几轮都不再联网 + tokio::time::sleep(Duration::from_millis(300)).await; + assert_eq!(hits.load(Ordering::SeqCst), 1); +} diff --git a/crates/tw-control/tests/resources.rs b/crates/tw-control/tests/resources.rs index 90b42a55..2228cb28 100644 --- a/crates/tw-control/tests/resources.rs +++ b/crates/tw-control/tests/resources.rs @@ -58,6 +58,7 @@ fn bed(yaml: &str) -> Bed { gateway_addr: None, store: None, started: std::time::Instant::now(), + price_updater: Default::default(), // **测试里绝不能碰开发者自己的配置** home: d.path().join("home"), }; diff --git a/crates/tw-control/tests/speed.rs b/crates/tw-control/tests/speed.rs index 8916149d..a2dad773 100644 --- a/crates/tw-control/tests/speed.rs +++ b/crates/tw-control/tests/speed.rs @@ -29,6 +29,7 @@ fn bed(yaml: &str) -> Bed { gateway_addr: None, store: None, started: std::time::Instant::now(), + price_updater: Default::default(), // **测试里绝不能碰开发者自己的配置** home: d.path().join("home"), }; diff --git a/crates/tw-gateway/src/l3.rs b/crates/tw-gateway/src/l3.rs index 9e8ebe38..0d1feb7b 100644 --- a/crates/tw-gateway/src/l3.rs +++ b/crates/tw-gateway/src/l3.rs @@ -251,7 +251,7 @@ fn has_content(chunk: &[u8]) -> bool { /// 算一次测速要花多少。 pub fn estimate( - prices: &tw_pricing::Prices, + prices: &tw_pricing::PriceBook, provider: &str, model: &str, subscription: bool, @@ -270,7 +270,7 @@ pub fn estimate( format!("不计费,但会消耗约 {} tokens 的额度", input + MAX_TOKENS), ) } else { - match prices.cost(model, &usage, false) { + match prices.cost_for(provider, model, &usage, false) { tw_pricing::Cost::Known(m) | tw_pricing::Cost::Estimated(m) => ( Some(m), // **金额再小也要显示。**用户按下按钮时有权知道自己在花 @@ -320,8 +320,8 @@ pub fn total_micros(es: &[Estimate]) -> Option { mod tests { use super::*; - fn prices() -> tw_pricing::Prices { - tw_pricing::Prices::builtin().unwrap() + fn prices() -> tw_pricing::PriceBook { + tw_pricing::PriceBook::builtin().unwrap() } #[test] diff --git a/crates/tw-gateway/src/server.rs b/crates/tw-gateway/src/server.rs index d4c21301..9bb755ed 100644 --- a/crates/tw-gateway/src/server.rs +++ b/crates/tw-gateway/src/server.rs @@ -266,11 +266,12 @@ pub struct AppState { /// /// **跨重载存活**:改一条规则不该让所有上游回到「没测过」。 pub latency: Arc, - /// 价目表。`cheapest` 策略靠它排序。 + /// 价格簿:默认价目表 + 自定义价目表 + 哪个上游用哪张。 /// - /// **可能是空的** —— 价目表加载失败时成本一律标「未知」, - /// 而那时 `cheapest` 组里所有人都「算不出价钱」,退回配置顺序。 - pub prices: Arc>, + /// **全进程只有这一份。**`cheapest` 排序、记账、测速报价、回放都从这 + /// 里取 —— 以前记账那一层攥着启动时的一份副本,改了价格要重启才生效。 + /// 配置重载时换掉自定义价目表,刷新默认价目表时换掉底表。 + pub pricing: tw_pricing::Shared, /// 轮换出来的新 refresh token 往哪儿交。 /// /// **和 body 那条路同一个形状**:数据面只管交出去,写文件是控制面的 @@ -295,6 +296,8 @@ impl AppState { .map_err(|e| GatewayError::config(format!("HTTP 客户端建不起来:{e}")))?; let limits = config.limits.clone(); let catalog = catalog_from(&config); + let pricing_config = config.pricing.clone(); + let price_assign = config.price_assign(); let rt = Runtime::build(config, None)?; Ok(Self { rt: Arc::new(arc_swap::ArcSwap::from_pointee(rt)), @@ -310,13 +313,15 @@ impl AppState { relisten: Arc::new(tokio::sync::Notify::new()), oauth: Arc::new(crate::oauth::Cache::new()), latency: Arc::new(crate::latency::Latency::new()), - prices: Arc::new(arc_swap::ArcSwap::from_pointee( - tw_pricing::Prices::builtin().unwrap_or_else(|e| { + pricing: tw_pricing::shared(tw_pricing::PriceBook::new( + Arc::new(tw_pricing::Table::builtin().unwrap_or_else(|e| { // **加载不了不能挡住启动**:那时成本显示「未知」, // 而转发照常 - tracing::warn!("价目表加载失败,成本一律标未知:{e}"); - tw_pricing::Prices::empty() - }), + tracing::warn!("内置价目表加载失败,成本一律标未知:{e}"); + tw_pricing::Table::empty() + })), + pricing_config, + price_assign, )), rotation_sink: Arc::new(std::sync::Mutex::new(None)), rotation_told: Arc::new(std::sync::Mutex::new(Default::default())), @@ -448,14 +453,66 @@ impl AppState { } } - /// 换一份带用户覆盖的价目表进来。 + /// 换一份默认价目表进来(启动时读到的上次刷新结果,或者刚刷新的)。 + pub fn set_price_table(&self, table: tw_pricing::Table) { + let table = Arc::new(table); + // **rcu,不是 load 再 store。**刷新和配置重载可能同时发生,后者 + // 换的是自定义价目表 —— 先读后写会把对方刚换进去的那一半覆盖掉 + self.pricing.rcu(|book| book.with_table(table.clone())); + } + + /// 这家实际怎么收钱。 + /// + /// **配置里写了就听配置的,没写就自动判**:响应头里报过订阅额度的就是 + /// 订阅型。那个信号一直在我们手上,不该变成一个用户要填的 + /// 字段 —— 而一个填错了的字段比没有更糟。 /// - /// **一定要调。**`AppState::new` 里那份只有内置快照,没有用户的 - /// `pricing.yaml` —— 而中转站的价格只有用户自己知道, - /// 那正是 `cheapest` 唯一的判据来源。两处各拿一份不同的价目表, - /// 会让「成本栏显示的」和「按最便宜选的」对不上。 - pub fn set_prices(&self, p: tw_pricing::Prices) { - self.prices.store(std::sync::Arc::new(p)); + /// **自动判有一个已知的边界:每次进程启动之后,打给一家订阅上游的第一个 + /// 请求会被按量计价。**那时我们还没见过它的额度头。之后就对了。 + /// + /// 没有更好的办法:额度头只在响应里,而计价发生在响应之后 —— 想在第一 + /// 个请求之前知道,只能主动探测,而那条路是明确否掉的(会占用户 + /// 自己的配额)。在乎那一条记录的人,在配置里写一行 `billing: + /// subscription` 就没有歧义了。 + pub fn billing_of(&self, p: &tw_config::Provider) -> tw_config::Billing { + if let Some(b) = p.billing { + return b; + } + let reported = self + .quotas + .lock() + .map(|g| g.get(&p.name).is_some_and(|q| !q.is_empty())) + .unwrap_or(false); + if reported { + tw_config::Billing::Subscription + } else { + tw_config::Billing::PerToken + } + } + + /// `cheapest` 排序用的单价:每家跑这个模型的 (输入, 输出),微分/百万 token。 + /// + /// **路由和预演共用这一个** —— 各写一份的话,预演说会选 A,实际选的是 B。 + pub fn unit_prices( + &self, + providers: &[tw_config::Provider], + candidates: &[String], + model: &str, + ) -> std::collections::HashMap { + let book = self.pricing.load(); + candidates + .iter() + .filter_map(|name| { + let p = providers.iter().find(|p| &p.name == name)?; + // **订阅制的边际成本是零,它就是最便宜的那家**。 + // 而「价格未知」不是「免费」 —— 它不在这张表里,排到最后去 + match p.billing { + Some(tw_config::Billing::Subscription) => Some((name.clone(), (0, 0))), + Some(tw_config::Billing::Unknown) => None, + _ => book.unit_micros(name, model).map(|u| (name.clone(), u)), + } + }) + .collect() } /// 接上轮换的去处。**控制面起来之后才调** —— 在那之前轮换只报不写。 @@ -493,6 +550,10 @@ impl AppState { } let relisten = old.config.listen.gateway.socket_addr() != next.config.listen.gateway.socket_addr(); + // 自定义价目表和上游的选择跟着配置走,默认价目表不变 + let (sheets, assign) = (next.config.pricing.clone(), next.config.price_assign()); + self.pricing + .rcu(|book| book.with_config(sheets.clone(), assign.clone())); self.rt.store(Arc::new(next)); if relisten { // 只通知,不在这里重建 —— 换监听器要 await,而这个函数被 @@ -1020,26 +1081,7 @@ async fn pipeline( }, price: match kind { tw_engine::GroupType::Cheapest => { - let prices = state.prices.load(); - decision - .candidates - .iter() - .filter_map(|name| { - let p = rt.config.providers.iter().find(|p| &p.name == name)?; - // **订阅制的边际成本是零,它就是最便宜的那家**。 - // 而「价格未知」不是「免费」 —— - // 它要排到最后去 - match p.billing { - Some(tw_config::Billing::Subscription) => { - Some((name.clone(), (0, 0))) - } - Some(tw_config::Billing::Unknown) => None, - _ => prices - .unit_micros(name, &facts.model) - .map(|u| (name.clone(), u)), - } - }) - .collect() + state.unit_prices(&rt.config.providers, &decision.candidates, &facts.model) } _ => Default::default(), }, @@ -1344,7 +1386,7 @@ async fn pipeline( // 最终服务的那家怎么收钱。**跟着请求走,不能事后查配置** —— // 配置随时会被热重载,而一条三天前的记录该按它当时那家的算。 let billing = used - .map(|p| effective_billing(&state, p)) + .map(|p| state.billing_of(p)) .unwrap_or(tw_config::Billing::PerToken); state.bus.emit(tw_api::Event::RequestRouted { id, @@ -1812,30 +1854,6 @@ async fn serve_once( .await } -/// 这家实际怎么收钱。 -/// -/// **配置里写了就听配置的,没写就自动判**:响应头里报过订阅额度的就是 -/// 订阅型。那个信号一直在我们手上,不该变成一个用户要填的 -/// 字段 —— 而一个填错了的字段比没有更糟。 -/// -/// **自动判有一个已知的边界:每次进程启动之后,打给一家订阅上游的第一个 -/// 请求会被按量计价。**那时我们还没见过它的额度头。之后就对了。 -/// -/// 没有更好的办法:额度头只在响应里,而计价发生在响应之后 —— 想在第一 -/// 个请求之前知道,只能主动探测,而那条路是明确否掉的(会占用户 -/// 自己的配额)。在乎那一条记录的人,在配置里写一行 `billing: -/// subscription` 就没有歧义了。 -fn effective_billing(state: &AppState, p: &tw_config::Provider) -> tw_config::Billing { - if let Some(b) = p.billing { - return b; - } - if state.quotas().get(&p.name).is_some_and(|q| !q.is_empty()) { - tw_config::Billing::Subscription - } else { - tw_config::Billing::PerToken - } -} - fn hop(provider: &str, outcome: String, started: std::time::Instant) -> tw_api::AttemptView { tw_api::AttemptView { provider: provider.to_string(), diff --git a/crates/tw-gateway/tests/passthrough.rs b/crates/tw-gateway/tests/passthrough.rs index 02d68a6c..89723c2b 100644 --- a/crates/tw-gateway/tests/passthrough.rs +++ b/crates/tw-gateway/tests/passthrough.rs @@ -438,6 +438,7 @@ async fn a_rule_sends_opus_to_one_upstream_and_everything_else_to_another() { ], groups: Vec::new(), proxies: Vec::new(), + pricing: Default::default(), limits: Default::default(), client_probes: Default::default(), security: Default::default(), diff --git a/crates/tw-pricing/Cargo.toml b/crates/tw-pricing/Cargo.toml index 7e120964..e8742d39 100644 --- a/crates/tw-pricing/Cargo.toml +++ b/crates/tw-pricing/Cargo.toml @@ -5,16 +5,15 @@ edition.workspace = true rust-version.workspace = true license.workspace = true repository.workspace = true -description = "Price table: a built-in snapshot, user overrides, and three-state cost (measured, estimated, unpriced)" +description = "Pricing: the public price table, user price sheets, and three-state cost (measured, estimated, unpriced)" [dependencies] +arc-swap = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } -serde_yaml_ng = { workspace = true } flate2 = { workspace = true } thiserror = { workspace = true } -tracing = { workspace = true } [dev-dependencies] +# 价目表写在 config.yaml 里,而读 YAML 是 tw-config 的事。这里只在测试里用它 serde_yaml_ng = { workspace = true } -tempfile = "3" diff --git a/crates/tw-pricing/data/PROVENANCE.md b/crates/tw-pricing/data/PROVENANCE.md index 8413612a..7244c965 100644 --- a/crates/tw-pricing/data/PROVENANCE.md +++ b/crates/tw-pricing/data/PROVENANCE.md @@ -48,3 +48,16 @@ One measured example. OpenAI cut the price of a model on 2026-08-22, and a widely used dataset **did not correct it for three days**, returning a figure 25% too high the whole time. The cause was that their sync script automates the model list but not the prices, which arrive by hand-written PR. + +## At runtime + +The snapshot is what a fresh install and an offline machine price with. +Once running, the control plane fetches the same file from the dataset's +`main` branch once a day, unless `pricing.auto_update: false`, and saves it +as `model_prices.json` beside `config.yaml`. Whichever of the two is newer +prices requests. + +Following `main` at runtime is the trade the snapshot refuses at build +time, and it is taken on purpose: vendor price cuts and relay rates move +faster than releases. It stays explainable because every request records +the date of the table that priced it. diff --git a/crates/tw-pricing/data/verified.yaml b/crates/tw-pricing/data/verified.yaml index a53d9211..2ea9be70 100644 --- a/crates/tw-pricing/data/verified.yaml +++ b/crates/tw-pricing/data/verified.yaml @@ -17,8 +17,8 @@ # # 1. 打开下面那个官方定价页,看新价格对不对; # 2. 对得上就改这里的数字并更新 `checked_on`; -# 3. 对不上就说明上游数据集错了 —— 用 `pricing.yaml` 的覆盖层顶住, -# 并去上游提 issue。 +# 3. 对不上就说明上游数据集错了 —— 去上游提 issue。修正之前,受影响的 +# 用户可以在 config.yaml 里建一张价目表,单独覆盖那个模型。 # # ## 和原计划不同的一处取舍 # diff --git a/crates/tw-pricing/src/book.rs b/crates/tw-pricing/src/book.rs new file mode 100644 index 00000000..d1f96dec --- /dev/null +++ b/crates/tw-pricing/src/book.rs @@ -0,0 +1,487 @@ +//! 价格簿:默认价目表 + 自定义价目表 + 哪个上游用哪张。 +//! +//! **全进程只有一份,而且是活的。**网关的 `cheapest`、记账、测速报价、 +//! 回放都从同一个 [`Shared`] 里取 —— 以前记账那一层攥着启动时的一份 +//! 副本,改了价格要重启才生效,而「成本栏显示的」和「按最便宜选的」 +//! 可以是两份不同的表。 +//! +//! 生效单价按这个顺序定(对上游 U、模型 M): +//! +//! 1. U 没有选价目表:默认价目表里 M 的单价。 +//! 2. U 选了价目表 P:P 单独覆盖了 M,就用覆盖价;否则默认价目表单价 × P 的倍率。 + +use std::collections::HashMap; +use std::sync::Arc; + +use crate::{Cost, Micros, ModelPrice, PricingConfig, SheetDef, Table, Usage, name, to_micros}; + +/// 全进程共用的那一份,可以原子地整份换掉。 +pub type Shared = Arc>; + +pub fn shared(book: PriceBook) -> Shared { + Arc::new(arc_swap::ArcSwap::from_pointee(book)) +} + +#[derive(Debug)] +pub struct PriceBook { + table: Arc, + config: PricingConfig, + /// 编译好的价目表:覆盖价已经换算成每 token、缺的字段已经补全 + sheets: HashMap, + /// 上游 → 它选的价目表 + assign: HashMap, +} + +#[derive(Debug)] +struct Sheet { + multiplier: f64, + overrides: HashMap, +} + +impl Sheet { + fn compile(def: &SheetDef, table: &Table) -> Self { + Self { + multiplier: def.multiplier, + overrides: def + .models + .iter() + .map(|(m, p)| { + ( + m.clone(), + p.to_price(table.get(m).and_then(|b| b.max_input_tokens)), + ) + }) + .collect(), + } + } +} + +/// 一个价格是从哪儿来的。**每一个金额都要能追溯到它。** +#[derive(Debug, Clone, PartialEq)] +pub enum Source { + /// 默认价目表 + Default, + /// 默认价目表 × 某张价目表的倍率 + Scaled { sheet: String, multiplier: f64 }, + /// 某张价目表单独覆盖的 + Override { sheet: String }, +} + +#[derive(Debug, Clone)] +pub struct Resolved { + pub price: ModelPrice, + pub source: Source, + /// 只在别的平台的键上找到了价格。**按它算出来的钱一律标成估算** + pub cross_platform: bool, +} + +impl Resolved { + /// 用了这么多 token 花了多少。`estimated`:用量是不是估的。 + pub fn cost(&self, usage: &Usage, estimated: bool) -> Cost { + // 价格本身就不精确的话,结果一定是估算 —— 哪怕 usage 是上游给的 + cost_of(&self.price, usage, estimated || self.cross_platform) + } + + /// 用了缓存之后净省(或净多花)了多少。见 [`saving_of`]。 + pub fn cache_saving(&self, usage: &Usage) -> Micros { + if usage.cache_read == 0 && usage.cache_write == 0 { + return 0; + } + saving_of(&self.price, usage) + } +} + +impl PriceBook { + /// `assign`:上游名 → 价目表名。没有出现的上游按默认价目表。 + pub fn new( + table: Arc
, + config: PricingConfig, + assign: impl IntoIterator, + ) -> Self { + let sheets = config + .sheets + .iter() + .map(|s| (s.name.clone(), Sheet::compile(s, &table))) + .collect(); + Self { + table, + config, + sheets, + assign: assign.into_iter().collect(), + } + } + + /// 只有内置快照、没有自定义价目表。测试和兜底用。 + pub fn builtin() -> Result { + Ok(Self::new( + Arc::new(Table::builtin()?), + PricingConfig::default(), + [], + )) + } + + /// 换一份默认价目表,**自定义价目表按新表重新补全**。 + pub fn with_table(&self, table: Arc
) -> Self { + Self::new(table, self.config.clone(), self.assign.clone()) + } + + /// 换一份配置(价目表和上游的选择),默认价目表不变。 + pub fn with_config( + &self, + config: PricingConfig, + assign: impl IntoIterator, + ) -> Self { + Self::new(self.table.clone(), config, assign) + } + + pub fn table(&self) -> &Arc
{ + &self.table + } + + pub fn config(&self) -> &PricingConfig { + &self.config + } + + /// 这个上游选了哪张价目表。`None` = 默认价目表。 + pub fn sheet_of(&self, provider: &str) -> Option<&str> { + self.assign.get(provider).map(String::as_str) + } + + /// 按某张价目表查价。`None` 查默认价目表。 + pub fn resolve(&self, sheet: Option<&str>, model: &str) -> Option { + match sheet { + Some(n) => self.resolve_in(self.sheets.get(n).map(|s| (n, s)), model), + None => self.resolve_in(None, model), + } + } + + /// 放进一张**还没保存**的价目表,同名的那张被它替换。只给编辑对话框预览用。 + pub fn with_draft(&self, def: SheetDef) -> Self { + let mut config = self.config.clone(); + config.sheets.retain(|s| s.name != def.name); + config.sheets.push(def); + Self::new(self.table.clone(), config, self.assign.clone()) + } + + /// 按这个上游选的价目表查价。 + pub fn resolve_for(&self, provider: &str, model: &str) -> Option { + self.resolve(self.sheet_of(provider), model) + } + + fn resolve_in(&self, sheet: Option<(&str, &Sheet)>, model: &str) -> Option { + if let Some((name, s)) = sheet { + // **覆盖的键也要按名字归一化来匹配** —— 用户写的是 + // `claude-sonnet-4-5`,客户端发的是带日期的那个 + for c in name::candidates(model) { + if let Some(p) = s.overrides.get(&c) { + return Some(Resolved { + price: p.clone(), + source: Source::Override { + sheet: name.to_string(), + }, + cross_platform: false, + }); + } + } + } + let (base, cross_platform) = self.table.lookup(model)?; + Some(match sheet { + Some((name, s)) => Resolved { + price: base.scaled(s.multiplier), + source: Source::Scaled { + sheet: name.to_string(), + multiplier: s.multiplier, + }, + cross_platform, + }, + None => Resolved { + price: base.clone(), + source: Source::Default, + cross_platform, + }, + }) + } + + /// 这个上游跑这个模型、用了这么多 token,花了多少。 + pub fn cost_for(&self, provider: &str, model: &str, usage: &Usage, estimated: bool) -> Cost { + match self.resolve_for(provider, model) { + Some(r) => r.cost(usage, estimated), + None => Cost::Unpriced { + model: model.to_string(), + }, + } + } + + /// 这家跑这个模型的 (输入, 输出) 单价,微分/百万 token。给 `cheapest` + /// 排序用 —— **整数**,因为浮点比较在「两家价钱一样」这种边界上会给出 + /// 不稳定的顺序,而那意味着 prompt cache 白断一次。 + pub fn unit_micros(&self, provider: &str, model: &str) -> Option<(Micros, Micros)> { + let p = self.resolve_for(provider, model)?.price; + Some(( + to_micros(p.input * 1_000_000.0), + to_micros(p.output * 1_000_000.0), + )) + } +} + +impl ModelPrice { + /// 所有单价乘上同一个倍率。上下文窗口不变。 + pub fn scaled(&self, m: f64) -> ModelPrice { + ModelPrice { + input: self.input * m, + output: self.output * m, + cache_read: self.cache_read.map(|v| v * m), + cache_write_5m: self.cache_write_5m.map(|v| v * m), + cache_write_1h: self.cache_write_1h.map(|v| v * m), + input_above_200k: self.input_above_200k.map(|v| v * m), + output_above_200k: self.output_above_200k.map(|v| v * m), + max_input_tokens: self.max_input_tokens, + } + } + + /// 实际计费用的每 token 单价。`long`:这次请求落在长上下文那一档。 + /// + /// **计费和显示都走这里**,数据集里没单独定价的档在这里按它的约定补上: + /// 缓存读写没有单独价 = 按输入价算(那是「这家不区分」,不是「免费」); + /// 1 小时写入没有 = 按 5 分钟写入算(**退回时只会低估**)。 + pub fn rates(&self, long: bool) -> Rates { + let input = match self.input_above_200k { + Some(v) if long => v, + _ => self.input, + }; + let output = match self.output_above_200k { + Some(v) if long => v, + _ => self.output, + }; + Rates { + input, + output, + cache_read: self.cache_read.unwrap_or(input), + cache_write_5m: self.cache_write_5m.unwrap_or(input), + cache_write_1h: self.cache_write_1h.or(self.cache_write_5m).unwrap_or(input), + } + } +} + +/// 一档的实际单价,每 token 的美元。见 [`ModelPrice::rates`]。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Rates { + pub input: f64, + pub output: f64, + pub cache_read: f64, + pub cache_write_5m: f64, + pub cache_write_1h: f64, +} + +impl Rates { + fn cache_write(&self, one_hour: bool) -> f64 { + if one_hour { + self.cache_write_1h + } else { + self.cache_write_5m + } + } +} + +/// 按一个单价算一次调用的成本。 +pub(crate) fn cost_of(p: &ModelPrice, u: &Usage, estimated: bool) -> Cost { + // 长上下文分层:**按这次请求的输入量选档**,不是按模型的窗口。 + let r = p.rates(u.input > 200_000); + let usd = u.input as f64 * r.input + + u.output as f64 * r.output + + u.cache_read as f64 * r.cache_read + + u.cache_write as f64 * r.cache_write(u.cache_1h); + let m = to_micros(usd); + if estimated { + Cost::Estimated(m) + } else { + Cost::Known(m) + } +} + +/// 用了缓存之后,净多花还是净少花了多少。 +/// +/// **算的是「如果完全不用缓存,这次要多花多少」** —— 两笔都要算:命中 +/// 省下的(读是 0.1 倍单价),以及写入多花的(**写是 1.25 倍单价,不是 +/// 免费的**)。所以它可以是负数,而负数是一条结论:这个用法上缓存在亏钱。 +/// +/// 没有单独的缓存价时没有节省或溢价 —— 那时它本来就按输入价算。 +pub(crate) fn saving_of(p: &ModelPrice, u: &Usage) -> Micros { + let r = p.rates(u.input + u.cache_read > 200_000); + let saved = u.cache_read as f64 * (r.input - r.cache_read); + let spent = u.cache_write as f64 * (r.cache_write(u.cache_1h) - r.input); + to_micros(saved - spent) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn book(yaml: &str, assign: &[(&str, &str)]) -> PriceBook { + let cfg: PricingConfig = serde_yaml_ng::from_str(yaml).unwrap(); + cfg.validate().unwrap(); + PriceBook::new( + Arc::new(Table::builtin().unwrap()), + cfg, + assign.iter().map(|(p, s)| (p.to_string(), s.to_string())), + ) + } + + const SHEETS: &str = " +sheets: + - name: 中转协议价 + multiplier: 0.8 + models: + claude-sonnet-4-5-thinking: + { input: 3, output: 15, cache_read: 0.3, cache_write_5m: 3.75, cache_write_1h: 6 } +"; + + fn per_m(v: f64) -> f64 { + (v * 1e6 * 1e6).round() / 1e6 + } + + #[test] + fn an_upstream_without_a_sheet_pays_the_default_price() { + let b = book(SHEETS, &[("relay-hk", "中转协议价")]); + let r = b.resolve_for("anthropic", "claude-sonnet-4-5").unwrap(); + assert_eq!(r.source, Source::Default); + assert_eq!(per_m(r.price.input), 3.0); + } + + #[test] + fn a_sheet_scales_every_price_including_the_cache_tiers() { + // 倍率只乘输入输出的话,缓存占大头的流量会被高估 + let b = book(SHEETS, &[("relay-hk", "中转协议价")]); + let r = b + .resolve_for("relay-hk", "claude-sonnet-4-5-20250929") + .unwrap(); + assert_eq!( + r.source, + Source::Scaled { + sheet: "中转协议价".into(), + multiplier: 0.8 + } + ); + assert_eq!(per_m(r.price.input), 2.4); + assert_eq!(per_m(r.price.output), 12.0); + assert_eq!(per_m(r.price.cache_read.unwrap()), 0.24); + assert_eq!(per_m(r.price.cache_write_5m.unwrap()), 3.0); + assert_eq!(per_m(r.price.cache_write_1h.unwrap()), 4.8); + } + + #[test] + fn an_override_is_the_price_and_the_multiplier_does_not_touch_it() { + let b = book(SHEETS, &[("relay-hk", "中转协议价")]); + let r = b + .resolve_for("relay-hk", "claude-sonnet-4-5-thinking") + .unwrap(); + assert_eq!( + r.source, + Source::Override { + sheet: "中转协议价".into() + } + ); + assert_eq!(per_m(r.price.input), 3.0); + assert_eq!(per_m(r.price.cache_write_1h.unwrap()), 6.0); + } + + #[test] + fn an_override_does_not_move_when_the_default_table_is_refreshed() { + // 覆盖价是用户亲手设的。默认价目表每天都可能刷新,它不能跟着变 + let b = book(SHEETS, &[("relay-hk", "中转协议价")]); + let fresh = Table::fetched( + br#"{"claude-sonnet-4-5-thinking":{"input_cost_per_token":9e-6,"output_cost_per_token":9e-5,"cache_read_input_token_cost":9e-7}}"#, + "2026-09-17".into(), + ) + .unwrap(); + let b = b.with_table(Arc::new(fresh)); + let r = b + .resolve_for("relay-hk", "claude-sonnet-4-5-thinking") + .unwrap(); + assert_eq!(per_m(r.price.input), 3.0); + assert_eq!(per_m(r.price.cache_read.unwrap()), 0.3); + } + + #[test] + fn a_long_request_is_charged_at_the_long_context_rates_including_its_cache_reads() { + // 数据集里 Sonnet 4.5 有长上下文档、但没有单独的长上下文缓存价 + let b = book("{}", &[]); + let r = b.resolve(None, "claude-sonnet-4-5").unwrap(); + let long = r.price.rates(true); + assert_eq!(per_m(long.input), 6.0); + assert_eq!(per_m(long.output), 22.5); + let short = r.price.rates(false); + assert_eq!(per_m(short.cache_read), 0.3); + } + + #[test] + fn the_same_request_costs_what_each_upstreams_sheet_says() { + // 这是整件事的目的:按上游设的价格真的进了记账 + let b = book(SHEETS, &[("relay-hk", "中转协议价")]); + // 十万 token:不到长上下文那一档 + let u = Usage { + input: 100_000, + ..Default::default() + }; + let Cost::Known(official) = b.cost_for("anthropic", "claude-sonnet-4-5", &u, false) else { + panic!() + }; + let Cost::Known(relay) = b.cost_for("relay-hk", "claude-sonnet-4-5", &u, false) else { + panic!() + }; + assert_eq!(official, 300_000); + assert_eq!(relay, 240_000); + let (relay_in, _) = b.unit_micros("relay-hk", "claude-sonnet-4-5").unwrap(); + let (official_in, _) = b.unit_micros("anthropic", "claude-sonnet-4-5").unwrap(); + assert!(relay_in < official_in, "cheapest 看到的也得是同一份价"); + } + + #[test] + fn a_model_with_no_price_anywhere_is_unpriced_not_zero() { + let b = book(SHEETS, &[("relay-hk", "中转协议价")]); + assert!(matches!( + b.cost_for( + "relay-hk", + "某个中转站自己起的名字", + &Usage::default(), + false + ), + Cost::Unpriced { .. } + )); + } + + #[test] + fn a_new_default_table_recompiles_the_sheets_on_top_of_it() { + let b = book(SHEETS, &[("relay-hk", "中转协议价")]); + let fresh = Table::fetched( + br#"{"claude-sonnet-4-5":{"input_cost_per_token":5e-6,"output_cost_per_token":25e-6}}"#, + "2026-09-17".into(), + ) + .unwrap(); + let b = b.with_table(Arc::new(fresh)); + assert_eq!(b.table().date, "2026-09-17"); + let r = b.resolve_for("relay-hk", "claude-sonnet-4-5").unwrap(); + assert_eq!(per_m(r.price.input), 4.0); + } + + #[test] + fn a_draft_sheet_is_previewed_without_touching_the_saved_one() { + let b = book(SHEETS, &[("relay-hk", "中转协议价")]); + let draft: SheetDef = + serde_yaml_ng::from_str("name: 中转协议价\nmultiplier: 0.5\n").unwrap(); + let preview = b.with_draft(draft); + let r = preview + .resolve(Some("中转协议价"), "claude-sonnet-4-5") + .unwrap(); + assert_eq!(per_m(r.price.input), 1.5); + // 草稿里去掉了那条覆盖,而默认价目表里没有这个模型 + assert!( + preview + .resolve(Some("中转协议价"), "claude-sonnet-4-5-thinking") + .is_none() + ); + // 保存着的那张没变 + let r = b.resolve_for("relay-hk", "claude-sonnet-4-5").unwrap(); + assert_eq!(per_m(r.price.input), 2.4); + } +} diff --git a/crates/tw-pricing/src/lib.rs b/crates/tw-pricing/src/lib.rs index be9662ae..9911058c 100644 --- a/crates/tw-pricing/src/lib.rs +++ b/crates/tw-pricing/src/lib.rs @@ -1,111 +1,32 @@ //! 价目表。 //! -//! 菜单栏上那个 `$3.42` 的唯一输入。三层: +//! 菜单栏上那个 `$3.42` 的唯一输入。两层: //! -//! | 层 | 内容 | 谁写 | +//! | 层 | 内容 | 从哪儿来 | //! |---|---|---| -//! | 内置快照 | 随版本发布,pin 到具体 commit | 我们,发版时核对过 | -//! | 可选更新 | 用户点「检查价格更新」才拉 | 用户主动触发 | -//! | 用户覆盖 | `~/.thinkwatch/pricing.yaml` | 用户 | +//! | 默认价目表 | 公开价格数据集(LiteLLM) | 随版本内置一份,联网定期刷新 | +//! | 自定义价目表 | 在默认价目表上设倍率、单独覆盖个别模型 | 用户写在 config.yaml 里 | //! -//! 第三层是**必需的**:中转站的价格和官方不同,而且没有任何公开数据集 -//! 会收录它们。 +//! 上游默认按默认价目表计价,可以改选一张自定义价目表;一张自定义价目表 +//! 可以给多个上游用。**中转站的价格和官方不同,而且没有任何公开数据集 +//! 会收录它们** —— 第二层是必需的。 +//! +//! 默认价目表会变,但**已经记下的金额不会跟着变**:每个请求的花费在它 +//! 结束时算好、落库,之后价格更新只影响之后的请求。 //! //! 贯穿这一层的一条规矩:**算不出来就说算不出来。**没有价格的模型不能 //! 记成 0 —— 那是在撒谎,而一个会撒谎的成本面板不如没有。 +mod book; pub mod name; - -use std::collections::HashMap; -use std::path::Path; +mod sheet; +mod table; use serde::{Deserialize, Serialize}; -/// 内置快照。**pin 在一个具体的 commit 上**,来历见 `data/PROVENANCE.md`。 -const SNAPSHOT: &[u8] = include_bytes!("../data/model_prices.json.gz"); - -/// 快照对应的上游 commit 日期。 -/// -/// **成本旁边要标它**:一个两个月前的价目表算出来的数字,和 -/// 一个昨天的,可信度完全不同 —— 而用户没有别的办法知道这件事。 -pub const SNAPSHOT_DATE: &str = "2026-09-09"; -pub const SNAPSHOT_SOURCE: &str = "LiteLLM model_prices_and_context_window.json"; - -/// 更新去哪儿拉(第二层)。 -/// -/// **写死在代码里,不从配置读。**一个「价目表源」配置项等于给了任何能 -/// 改 config.yaml 的人一个往这个进程里喂 JSON 的入口,而那份 JSON 会 -/// 决定用户看到的每一个金额。 -pub const UPDATE_URL: &str = - "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"; - -/// 一份拉回来的价目表**解析成表,但不落盘**。 -/// -/// 分成「解析」和「写入」两步是刻意的:**先给 diff,确认才写**。 -pub fn parse_upstream(raw: &[u8]) -> Result, PricingError> { - let parsed: HashMap = - serde_json::from_slice(raw).map_err(|e| PricingError::Snapshot(e.to_string()))?; - let mut table = HashMap::with_capacity(parsed.len()); - for (k, v) in parsed { - if let Some(p) = price_from(&v) { - table.insert(k, p); - } - } - if table.is_empty() { - return Err(PricingError::Snapshot( - "拉回来的东西里一个带价格的模型都没有 —— 多半不是那份数据集".into(), - )); - } - Ok(table) -} - -/// 一个模型的价格变化。 -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct PriceChange { - pub model: String, - /// `None` = 新增的 - pub old_input: Option, - pub new_input: f64, - pub old_output: Option, - pub new_output: f64, -} - -/// 新旧两份表的差异。 -/// -/// **只列真的变了的**。三千多个模型里绝大多数没动,把它们一起列出来 -/// 等于把那几十条真的变化埋掉。 -pub fn diff( - old: &HashMap, - new: &HashMap, -) -> Vec { - let mut out: Vec = Vec::new(); - for (m, n) in new { - match old.get(m) { - Some(o) - if (o.input - n.input).abs() < f64::EPSILON - && (o.output - n.output).abs() < f64::EPSILON => {} - Some(o) => out.push(PriceChange { - model: m.clone(), - old_input: Some(o.input), - new_input: n.input, - old_output: Some(o.output), - new_output: n.output, - }), - None => out.push(PriceChange { - model: m.clone(), - old_input: None, - new_input: n.input, - old_output: None, - new_output: n.output, - }), - } - } - // **改价的排在新增的前面**:一个模型悄悄涨价,比多了一个模型重要 - out.sort_by(|a, b| { - (a.old_input.is_none(), a.model.as_str()).cmp(&(b.old_input.is_none(), b.model.as_str())) - }); - out -} +pub use book::{PriceBook, Rates, Resolved, Shared, Source, shared}; +pub use sheet::{PerMillion, PricingConfig, SheetDef, SheetError}; +pub use table::{SNAPSHOT_DATE, Table, TableSource, UPDATE_URL}; /// 一个模型的价格。单位一律是**每 token 的美元**,和上游数据集一致。 /// @@ -113,9 +34,6 @@ pub fn diff( /// 是 \$6.00。**只用 5 分钟档会让开了 1 小时 TTL 的用户被系统性低估 /// 60%**,而那是一个看起来很确定的数字。 #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] -// 覆盖文件里写错一个字段名(`inptu`)被静默忽略的话,用户会以为自己 -// 已经改过价格了,而面板上的数字一直是错的。 -#[serde(deny_unknown_fields)] pub struct ModelPrice { pub input: f64, pub output: f64, @@ -150,22 +68,14 @@ pub struct Usage { pub enum Cost { /// 上游给了 usage,价目表里有这个模型 —— 这是个可以相加的数 Known(Micros), - /// usage 是我们估的。**不能混进「今日花费」的精确数字里** + /// usage 是我们估的,或者价格是跨平台借来的。**不能混进「今日花费」 + /// 的精确数字里** Estimated(Micros), /// 价目表里没有这个模型。**不是 0** —— 当成 0 会让总额悄悄偏低, /// 而用户没有任何线索知道少算了什么 Unpriced { model: String }, } -/// 这个价是怎么查到的。 -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Match { - /// 同一个模型、同一条路 —— 只是名字的写法不同 - Exact, - /// 只在别的平台的键上找到了价格。**结果一律标成估算** - CrossPlatform, -} - /// 微分:百万分之一美元。 /// /// **整数,不是浮点。**金额相加是它唯一的用途,而浮点相加一万次之后的 @@ -176,562 +86,12 @@ pub fn to_micros(usd: f64) -> Micros { (usd * 1_000_000.0).round() as i64 } -#[derive(Debug)] -pub struct Prices { - table: HashMap, - /// 用户覆盖层。**查它优先** —— 中转站的价格只有用户自己知道 - overrides: HashMap>, - /// 每家自己的价。**比 `overrides` 还优先** —— 它更具体 - per_provider: HashMap>, - pub snapshot_date: String, -} - #[derive(Debug, thiserror::Error)] pub enum PricingError { #[error("内置价目表解不开,这是个打包错误:{0}")] Snapshot(String), - #[error("读 {path} 失败:{source}")] - Io { - path: String, - source: std::io::Error, - }, - #[error("{path} 不是合法的价格覆盖:{source}")] - Parse { - path: String, - source: serde_yaml_ng::Error, - }, -} - -/// 用户的覆盖文件。 -/// -/// ```yaml -/// models: -/// 中转站自己的模型: -/// input: 0.000001 -/// output: 0.000002 -/// # 删掉一条:写 null,那个模型就变回「没有价格」 -/// gpt-4o: null -/// -/// # 按上游分别写。**同一个模型在不同家不是同一个价** —— 中转站常常 -/// # 打折,而这是 `cheapest` 策略唯一的判据来源 -/// providers: -/// relay-cn: -/// claude-sonnet-4-5: -/// input: 0.0000018 -/// output: 0.000009 -/// ``` -#[derive(Debug, Default, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct Overrides { - #[serde(default)] - pub models: HashMap>, - /// 每家自己的价。**没写就按通用那份算** - #[serde(default)] - pub providers: HashMap>, -} - -impl Prices { - /// 只有内置快照。 - pub fn builtin() -> Result { - let raw = decompress(SNAPSHOT)?; - let parsed: HashMap = - serde_json::from_slice(&raw).map_err(|e| PricingError::Snapshot(e.to_string()))?; - let mut table = HashMap::with_capacity(parsed.len()); - for (k, v) in parsed { - // `sample_spec` 那种说明用的伪条目没有价格,自然会被滤掉。 - if let Some(p) = price_from(&v) { - table.insert(k, p); - } - } - Ok(Self { - table, - overrides: HashMap::new(), - per_provider: HashMap::new(), - snapshot_date: SNAPSHOT_DATE.to_string(), - }) - } - - /// 一张空表。**每个模型都会是「价格未知」** —— 那是价目表读不了 - /// 时唯一诚实的答案,比退回一个可能过期的内置快照好。 - pub fn empty() -> Self { - Self { - table: HashMap::new(), - overrides: HashMap::new(), - per_provider: HashMap::new(), - snapshot_date: "(价目表没能加载)".to_string(), - } - } - - /// 叠上用户的覆盖文件。**文件不存在是正常状态**,不是错误。 - pub fn with_overrides(mut self, path: &Path) -> Result { - let text = match std::fs::read_to_string(path) { - Ok(t) => t, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(self), - Err(source) => { - return Err(PricingError::Io { - path: path.display().to_string(), - source, - }); - } - }; - let o: Overrides = - serde_yaml_ng::from_str(&text).map_err(|source| PricingError::Parse { - path: path.display().to_string(), - source, - })?; - self.overrides = o.models; - self.per_provider = o.providers; - Ok(self) - } - - /// 内置快照里有没有这个模型。界面要用它区分「覆盖」和「补一个」。 - pub fn builtin_has(&self, model: &str) -> bool { - name::candidates(model) - .iter() - .any(|c| self.table.contains_key(c)) - } - - /// 把覆盖文件读成一份可编辑的清单。**顺序稳定** —— 界面上一行行 - /// 摆着的东西,每次打开都换位置会让人以为自己改错了。 - pub fn overrides_list(&self) -> Vec<(Option, String, ModelPrice)> { - let mut out: Vec<(Option, String, ModelPrice)> = Vec::new(); - let mut global: Vec<_> = self - .overrides - .iter() - .filter_map(|(m, p)| p.clone().map(|p| (m.clone(), p))) - .collect(); - global.sort_by(|a, b| a.0.cmp(&b.0)); - out.extend(global.into_iter().map(|(m, p)| (None, m, p))); - let mut per: Vec<_> = self.per_provider.iter().collect(); - per.sort_by_key(|(k, _)| k.to_string()); - for (prov, models) in per { - let mut ms: Vec<_> = models.iter().collect(); - ms.sort_by_key(|(k, _)| k.to_string()); - for (m, p) in ms { - out.push((Some(prov.clone()), m.clone(), p.clone())); - } - } - out - } - - /// 内置表的一份拷贝。给「拉回来的和现在的差在哪」用。 - pub fn table(&self) -> &HashMap { - &self.table - } - - /// 换一份表进来(用户确认过更新之后)。**覆盖层原样保留** —— - /// 那是用户自己写的东西,不该被一次上游更新冲掉。 - pub fn replace_table(&mut self, table: HashMap, date: String) { - self.table = table; - self.snapshot_date = date; - } - - pub fn len(&self) -> usize { - self.table.len() - } - pub fn is_empty(&self) -> bool { - self.table.is_empty() - } - - /// 查一个模型的价格。 - /// - /// **覆盖层优先,而且能删。**用户写 `gpt-4o: null` 就是说「我不要这 - /// 条」—— 那不是一个奇怪的需求:一个只走中转的用户,官方价目表里的 - /// 数字对他是错的。 - /// 这家跑这个模型的单价。**比通用那份优先** —— 它更具体。 - /// - /// 用在 `cheapest` 策略上。没有这一层的话,同一个模型在 - /// 官方和中转站算出来是同一个价,「最便宜」就没有任何判据。 - pub fn get_for(&self, provider: &str, model: &str) -> Option<&ModelPrice> { - if let Some(t) = self.per_provider.get(provider) { - // **归一化走计价那一套**:两套规则会造出「能用但 - // 算不出价钱」这种自相矛盾 - for c in name::candidates(model) { - if let Some(mp) = t.get(&c) { - return Some(mp); - } - } - } - self.get(model) - } - - /// 这家跑这个模型的 (输入, 输出) 单价,微分/百万 token。 - /// - /// 给排序用 —— **整数**,因为浮点比较在「两家价钱一样」这种边界上 - /// 会给出不稳定的顺序,而那意味着 prompt cache 白断一次。 - pub fn unit_micros(&self, provider: &str, model: &str) -> Option<(Micros, Micros)> { - let p = self.get_for(provider, model)?; - Some(( - to_micros(p.input * 1_000_000.0), - to_micros(p.output * 1_000_000.0), - )) - } - - pub fn get(&self, model: &str) -> Option<&ModelPrice> { - self.lookup(model).map(|(p, _)| p) - } - - /// 查价,**并且说清这个价有多可信**。 - fn lookup(&self, model: &str) -> Option<(&ModelPrice, Match)> { - for c in name::candidates(model) { - if let Some(o) = self.overrides.get(&c) { - // 显式删除:命中了但值是 null → 这个模型没有价格 - return o.as_ref().map(|p| (p, Match::Exact)); - } - if let Some(p) = self.table.get(&c) { - return Some((p, Match::Exact)); - } - } - // 跨平台的最后一招。**它不精确**,见 name::cross_platform_fallback - let c = name::cross_platform_fallback(model)?; - if let Some(o) = self.overrides.get(&c) { - return o.as_ref().map(|p| (p, Match::CrossPlatform)); - } - self.table.get(&c).map(|p| (p, Match::CrossPlatform)) - } - - /// 算一次调用的成本。 - pub fn cost(&self, model: &str, u: &Usage, estimated: bool) -> Cost { - let Some((p, m)) = self.lookup(model) else { - return Cost::Unpriced { - model: model.to_string(), - }; - }; - // 价格本身就不精确的话,结果一定是估算 —— 哪怕 usage 是上游给的 - let estimated = estimated || m == Match::CrossPlatform; - // 长上下文分层:**按这次请求的输入量选档**,不是按模型的窗口。 - let long = u.input > 200_000; - let input_rate = if long { - p.input_above_200k.unwrap_or(p.input) - } else { - p.input - }; - let output_rate = if long { - p.output_above_200k.unwrap_or(p.output) - } else { - p.output - }; - // 缓存读没单独定价时按输入价算 —— 那是数据集里「这家不区分」的 - // 表达方式,不是「免费」。 - let cache_read_rate = p.cache_read.unwrap_or(input_rate); - let cache_write_rate = if u.cache_1h { - // 1 小时档没有就退回 5 分钟档,再退回输入价。**退回时只会 - // 低估** —— 所以这条要在文档里说清楚。 - p.cache_write_1h.or(p.cache_write_5m).unwrap_or(input_rate) - } else { - p.cache_write_5m.unwrap_or(input_rate) - }; - - let usd = u.input as f64 * input_rate - + u.output as f64 * output_rate - + u.cache_read as f64 * cache_read_rate - + u.cache_write as f64 * cache_write_rate; - let m = to_micros(usd); - if estimated { - Cost::Estimated(m) - } else { - Cost::Known(m) - } - } -} - -impl Prices { - /// 用了缓存之后,净多花还是净少花了多少。 - /// - /// **算的是「如果完全不用缓存,这次要多花多少」** —— 两笔都要算: - /// - /// · 命中省下的:cache read 是 0.1 倍单价,所以每个读到的 token - /// 省 0.9 倍。 - /// · 写入多花的:**cache write 是 1.25 倍单价,不是免费的。** - /// - /// **第二笔以前没减。**不减的话,一个反复重建缓存、很少命中的用法 - /// 会被报成「省了钱」,而它的真实账单比不开缓存更贵 —— 那正是用户 - /// 最需要知道的一种情况,却被这个数字盖住了。 - /// - /// 所以它可以是负数,而负数是一条结论:这个用法上缓存在亏钱。 - /// 回本线很低 —— 写的溢价是 0.25 倍、每次读省 0.9 倍,读量到写量的 - /// 约 28% 就回本了。 - /// - /// 没有价格、或者这家不按 token 计费时是 `None`。**不是 0** —— - /// 「省了 0 元」和「算不出来省了多少」是两句不同的话。 - pub fn cache_saving(&self, model: &str, u: &Usage) -> Option { - if u.cache_read == 0 && u.cache_write == 0 { - return Some(0); - } - let p = self.get(model)?; - let long = u.input + u.cache_read > 200_000; - let full_rate = if long { - p.input_above_200k.unwrap_or(p.input) - } else { - p.input - }; - // 缓存读没单独定价的话,它本来就按输入价算 —— 那时没有节省 - let saved = match p.cache_read { - Some(read_rate) => u.cache_read as f64 * (full_rate - read_rate), - None => 0.0, - }; - // 写入同理:没单独定价就是按输入价收,没有溢价 - let write_rate = if u.cache_1h { - p.cache_write_1h.or(p.cache_write_5m) - } else { - p.cache_write_5m - }; - let spent = match write_rate { - Some(w) => u.cache_write as f64 * (w - full_rate), - None => 0.0, - }; - Some(to_micros(saved - spent)) - } -} - -fn decompress(gz: &[u8]) -> Result, PricingError> { - use std::io::Read; - let mut d = flate2::read::GzDecoder::new(gz); - let mut out = Vec::with_capacity(2_500_000); - d.read_to_end(&mut out) - .map_err(|e| PricingError::Snapshot(e.to_string()))?; - Ok(out) -} - -fn price_from(v: &serde_json::Value) -> Option { - let f = |k: &str| v.get(k).and_then(|x| x.as_f64()); - // 没有输入或输出单价的条目不是一个能算钱的模型(嵌入、审核、 - // 以及数据集里那条 `sample_spec` 说明)。 - let input = f("input_cost_per_token")?; - let output = f("output_cost_per_token").unwrap_or(0.0); - Some(ModelPrice { - input, - output, - cache_read: f("cache_read_input_token_cost"), - cache_write_5m: f("cache_creation_input_token_cost"), - cache_write_1h: f("cache_creation_input_token_cost_above_1hr"), - input_above_200k: f("input_cost_per_token_above_200k_tokens"), - output_above_200k: f("output_cost_per_token_above_200k_tokens"), - max_input_tokens: v.get("max_input_tokens").and_then(|x| x.as_u64()), - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn prices() -> Prices { - Prices::builtin().unwrap() - } - - #[test] - fn the_builtin_snapshot_loads_and_has_the_models_people_actually_use() { - let p = prices(); - assert!(p.len() > 1000, "只有 {} 个模型,快照像是坏的", p.len()); - for m in [ - "claude-sonnet-4-5", - "claude-opus-4-20250514", - "claude-haiku-4-5", - "claude-3-5-haiku-20241022", - "gpt-4o", - ] { - assert!(p.get(m).is_some(), "查不到 {m}"); - } - } - - #[test] - fn the_one_hour_cache_tier_is_there_and_costs_more_than_five_minutes() { - // **这是选 LiteLLM 的决定性理由**。少了它,开 1 小时 - // TTL 的用户会被系统性低估 60%,而那是个看起来很确定的数字。 - let p = prices(); - let s = p.get("claude-sonnet-4-5").unwrap(); - let five = s.cache_write_5m.expect("没有 5 分钟档"); - let hour = s - .cache_write_1h - .expect("没有 1 小时档 —— 那这个数据集就白选了"); - assert!(hour > five, "1 小时档 {hour} 不比 5 分钟档 {five} 贵?"); - } - - #[test] - fn a_one_hour_cache_write_really_costs_more_than_a_five_minute_one() { - // 上一条测的是数据在不在,这条测的是**我们真的用了它**。 - let p = prices(); - let u = |h| Usage { - cache_write: 100_000, - cache_1h: h, - ..Default::default() - }; - let (Cost::Known(five), Cost::Known(hour)) = ( - p.cost("claude-sonnet-4-5", &u(false), false), - p.cost("claude-sonnet-4-5", &u(true), false), - ) else { - panic!("该是 Known"); - }; - assert!(hour > five, "5 分钟 {five} vs 1 小时 {hour}"); - // Sonnet 4.5 是 $3.75 vs $6.00,差 60% - assert!( - (hour as f64 / five as f64) > 1.5, - "差价没对上:{five} → {hour}" - ); - } - - #[test] - fn a_model_with_no_price_is_unpriced_not_zero() { - // **成本三态的第三态。**当成 0 会让总额悄悄偏低,而用户没有任何 - // 线索知道少算了什么。 - let p = prices(); - let c = p.cost("某个中转站自己起的名字", &Usage::default(), false); - match c { - Cost::Unpriced { model } => assert_eq!(model, "某个中转站自己起的名字"), - other => panic!("该是 Unpriced,实际 {other:?}"), - } - } - - #[test] - fn an_estimated_usage_yields_an_estimated_cost() { - // 估算值不能混进「今日花费」的精确数字里假装准确。 - let p = prices(); - let u = Usage { - input: 1000, - output: 100, - ..Default::default() - }; - assert!(matches!( - p.cost("claude-sonnet-4-5", &u, true), - Cost::Estimated(_) - )); - assert!(matches!( - p.cost("claude-sonnet-4-5", &u, false), - Cost::Known(_) - )); - } - - #[test] - fn a_long_context_request_uses_the_above_200k_rate() { - let p = prices(); - let per_token = |n: u64| { - let Cost::Known(m) = p.cost( - "claude-sonnet-4-5", - &Usage { - input: n, - ..Default::default() - }, - false, - ) else { - panic!() - }; - m as f64 / n as f64 - }; - let short = per_token(100_000); - let long = per_token(300_000); - assert!( - long > short * 1.5, - "超过 200k 之后单价没换档:{short} → {long}" - ); - } - - #[test] - fn the_dated_name_a_client_actually_sends_resolves_to_a_price() { - // Claude Code 发的是带日期的那种。查不到的话,**每一个真实请求 - // 都会变成「没有价格」** —— 而那时成本面板整个是空的。 - let p = prices(); - for m in [ - "claude-sonnet-4-5-20250929", - "claude-3-5-haiku-20241022", - "anthropic/claude-sonnet-4-5", - ] { - assert!(p.get(m).is_some(), "查不到 {m} —— 真实流量用的就是这种名字"); - } - } - - #[test] - fn costs_are_integers_so_that_a_thousand_of_them_add_up_exactly() { - // 浮点相加一万次之后的尾差会让「今日花费」和「逐条相加」对不上, - // 而那种对不上没有任何办法解释给用户听。 - let p = prices(); - let u = Usage { - input: 1234, - output: 567, - ..Default::default() - }; - let Cost::Known(one) = p.cost("claude-sonnet-4-5", &u, false) else { - panic!() - }; - let total: i64 = (0..10_000).map(|_| one).sum(); - assert_eq!(total, one * 10_000); - } - - #[test] - fn a_user_override_wins_over_the_builtin_table() { - // **中转站的价格和官方不同,而且没有任何公开数据集会收录它们。** - let d = tempfile::tempdir().unwrap(); - let f = d.path().join("pricing.yaml"); - std::fs::write( - &f, - "models:\n claude-sonnet-4-5:\n input: 0.000001\n output: 0.000002\n", - ) - .unwrap(); - let p = prices().with_overrides(&f).unwrap(); - let s = p.get("claude-sonnet-4-5").unwrap(); - assert_eq!(s.input, 0.000001); - assert_eq!(s.output, 0.000002); - // 没覆盖的模型不受影响 - assert!(p.get("gpt-4o").unwrap().input > 0.0); - } - - #[test] - fn an_override_can_delete_a_price_so_it_becomes_unpriced() { - // 一个只走中转的用户,官方价目表里的数字对他是错的。**能删是 - // 必需的** —— 而不是逼他填一个自己也不知道的价格。 - let d = tempfile::tempdir().unwrap(); - let f = d.path().join("pricing.yaml"); - std::fs::write(&f, "models:\n claude-sonnet-4-5: null\n").unwrap(); - let p = prices().with_overrides(&f).unwrap(); - assert!(p.get("claude-sonnet-4-5").is_none()); - assert!(matches!( - p.cost("claude-sonnet-4-5", &Usage::default(), false), - Cost::Unpriced { .. } - )); - } - - #[test] - fn a_missing_override_file_is_normal_not_an_error() { - // 绝大多数用户永远不会有这个文件。 - let d = tempfile::tempdir().unwrap(); - let p = prices() - .with_overrides(&d.path().join("nope.yaml")) - .unwrap(); - assert!(p.get("claude-sonnet-4-5").is_some()); - } - - #[test] - fn a_broken_override_file_says_which_file_and_why() { - let d = tempfile::tempdir().unwrap(); - let f = d.path().join("pricing.yaml"); - std::fs::write(&f, "models:\n x:\n inptu: 1\n").unwrap(); - let e = prices().with_overrides(&f).unwrap_err(); - let m = e.to_string(); - assert!(m.contains("pricing.yaml"), "{m}"); - assert!(m.contains("inptu"), "得说清是哪个字段写错了:{m}"); - } - - #[test] - fn the_snapshot_date_is_available_because_it_has_to_be_shown() { - // 一个两个月前的价目表算出来的数字,和一个昨天的,可信度完全 - // 不同 —— 而用户没有别的办法知道这件事。 - assert_eq!(prices().snapshot_date, SNAPSHOT_DATE); - assert_eq!(SNAPSHOT_DATE.len(), 10, "日期得是 YYYY-MM-DD"); - } - - #[test] - fn cache_reads_are_much_cheaper_than_fresh_input() { - // 这是整个 prompt cache 论证的数字基础(命中与否成本差 - // 5 到 10 倍)。数据集要是把它记反了,我们所有关于缓存的建议 - // 都是错的。 - let p = prices(); - let s = p.get("claude-sonnet-4-5").unwrap(); - let read = s.cache_read.expect("没有缓存读价格"); - assert!( - read < s.input / 5.0, - "缓存读 {read} 没比输入 {} 便宜多少", - s.input - ); - } + #[error("价格数据读不通:{0}")] + Dataset(String), } #[cfg(test)] @@ -750,14 +110,15 @@ mod snapshot_invariants { /// 而不是等用户发现账单对不上。 #[test] fn bedrock_and_direct_prices_agree_on_the_headline_rates_but_not_on_cache() { - let p = Prices::builtin().unwrap(); + let t = Table::builtin().unwrap(); let mut checked = 0; let mut differed = 0; - for (k, direct) in &p.table { + for k in t.models() { + let direct = t.exact(k).unwrap(); if k.contains('/') || k.contains('.') { continue; } - let Some(bedrock) = p.table.get(&format!("anthropic.{k}-v1:0")) else { + let Some(bedrock) = t.exact(&format!("anthropic.{k}-v1:0")) else { continue; }; checked += 1; @@ -783,10 +144,10 @@ mod snapshot_invariants { /// 顺手把别名规则推广到所有前缀上。 #[test] fn vertex_prices_differ_which_is_why_the_alias_rule_is_anthropic_only() { - let p = Prices::builtin().unwrap(); + let t = Table::builtin().unwrap(); let (Some(v), Some(b)) = ( - p.table.get("vertex_ai/claude-3-5-haiku"), - p.table.get("anthropic.claude-3-5-haiku-20241022-v1:0"), + t.exact("vertex_ai/claude-3-5-haiku"), + t.exact("anthropic.claude-3-5-haiku-20241022-v1:0"), ) else { // 上游改了键名的话这条自动跳过 —— 它是个警示,不是硬约束 return; @@ -801,7 +162,7 @@ mod snapshot_invariants { /// 任何人会发现。 #[test] fn the_headline_models_cost_what_the_vendor_says_they_cost() { - let p = Prices::builtin().unwrap(); + let p = Table::builtin().unwrap(); // (模型, 输入/百万 token, 输出/百万 token) for (m, input_per_m, output_per_m) in [ ("claude-sonnet-4-5", 3.0, 15.0), @@ -832,9 +193,10 @@ mod cross_platform_tests { // `claude-3-5-haiku-20241022` 是 Claude Code 真的会发的模型,而 // 数据集里只有它的 Bedrock 键。**给一个带波浪号的数字,比给一个 // 空白有用**;而假装它精确,就是那种「看起来很确定的错数字」。 - let p = Prices::builtin().unwrap(); - assert!(p.get("claude-3-5-haiku-20241022").is_some()); - let c = p.cost( + let p = PriceBook::builtin().unwrap(); + assert!(p.table().get("claude-3-5-haiku-20241022").is_some()); + let c = p.cost_for( + "任意一家", "claude-3-5-haiku-20241022", &Usage { input: 1000, @@ -852,9 +214,10 @@ mod cross_platform_tests { #[test] fn a_model_with_a_direct_price_is_not_downgraded_to_estimated() { - let p = Prices::builtin().unwrap(); + let p = PriceBook::builtin().unwrap(); assert!(matches!( - p.cost( + p.cost_for( + "任意一家", "claude-sonnet-4-5", &Usage { input: 1000, @@ -879,19 +242,20 @@ mod cross_platform_tests { } #[test] - fn a_user_override_still_wins_over_the_cross_platform_fallback() { + fn a_sheet_override_still_wins_over_the_cross_platform_fallback() { // 中转站的价格是用户写的,它比我们从别的平台推来的可信得多。 - let d = tempfile::tempdir().unwrap(); - let f = d.path().join("pricing.yaml"); - std::fs::write( - &f, - "models:\n claude-3-5-haiku-20241022:\n input: 0.000009\n output: 0.00001\n", + let cfg: PricingConfig = serde_yaml_ng::from_str( + "sheets:\n - name: 中转\n models:\n claude-3-5-haiku-20241022: { input: 9, output: 10, cache_read: 0.9, cache_write_5m: 11.25, cache_write_1h: 18 }\n", ) .unwrap(); - let p = Prices::builtin().unwrap().with_overrides(&f).unwrap(); - assert_eq!(p.get("claude-3-5-haiku-20241022").unwrap().input, 0.000009); + let p = PriceBook::new( + std::sync::Arc::new(Table::builtin().unwrap()), + cfg, + [("relay".to_string(), "中转".to_string())], + ); assert!(matches!( - p.cost( + p.cost_for( + "relay", "claude-3-5-haiku-20241022", &Usage { input: 1, @@ -901,11 +265,26 @@ mod cross_platform_tests { ), Cost::Known(_), )); + // 没选这张价目表的上游仍然是跨平台估算 + assert!(matches!( + p.cost_for( + "官方", + "claude-3-5-haiku-20241022", + &Usage { + input: 1, + ..Default::default() + }, + false + ), + Cost::Estimated(_), + )); } } #[cfg(test)] mod verified_tests { + use std::collections::HashMap; + use super::*; /// 人工核对过的那份(`data/verified.yaml`)。 @@ -946,10 +325,10 @@ mod verified_tests { #[test] fn the_builtin_snapshot_matches_what_a_human_checked_against_the_vendor_page() { let v = verified(); - let p = Prices::builtin().unwrap(); + let p = PriceBook::builtin().unwrap(); let mut problems = Vec::new(); for (name, want) in &v.models { - let Some(got) = p.get(name) else { + let Some(got) = p.table().get(name) else { problems.push(format!("`{name}` 在快照里查不到了")); continue; }; @@ -1040,53 +419,54 @@ mod verified_tests { mod saving_tests { use super::*; + fn saving(p: &PriceBook, model: &str, u: &Usage) -> Option { + p.resolve(None, model).map(|r| r.cache_saving(u)) + } + #[test] fn a_cache_hit_saves_the_difference_not_the_whole_price() { // **用户想知道的是那个差额**:cache read 是 0.1 倍单价,所以省下 // 的是 0.9 倍,不是全部。 - let p = Prices::builtin().unwrap(); + let p = PriceBook::builtin().unwrap(); let u = Usage { cache_read: 100_000, ..Default::default() }; - let saved = p.cache_saving("claude-sonnet-4-5", &u).unwrap(); + let saved = saving(&p, "claude-sonnet-4-5", &u).unwrap(); // Sonnet 4.5:输入 $3、缓存读 $0.30 → 十万 token 省 $0.27 assert_eq!(saved, 270_000); } #[test] fn no_cache_reads_means_nothing_saved_which_is_a_real_zero() { - let p = Prices::builtin().unwrap(); - assert_eq!( - p.cache_saving("claude-sonnet-4-5", &Usage::default()), - Some(0) - ); + let p = PriceBook::builtin().unwrap(); + assert_eq!(saving(&p, "claude-sonnet-4-5", &Usage::default()), Some(0)); } #[test] fn the_write_premium_is_subtracted_not_ignored() { // **这条是这个函数改过一次的理由。**缓存写是 1.25 倍单价: // 只算读省下的、不减写多花的,等于声称缓存永远只会让人省钱。 - let p = Prices::builtin().unwrap(); - let read_only = p - .cache_saving( - "claude-sonnet-4-5", - &Usage { - cache_read: 100_000, - ..Default::default() - }, - ) - .unwrap(); - let with_writes = p - .cache_saving( - "claude-sonnet-4-5", - &Usage { - cache_read: 100_000, - cache_write: 100_000, - ..Default::default() - }, - ) - .unwrap(); + let p = PriceBook::builtin().unwrap(); + let read_only = saving( + &p, + "claude-sonnet-4-5", + &Usage { + cache_read: 100_000, + ..Default::default() + }, + ) + .unwrap(); + let with_writes = saving( + &p, + "claude-sonnet-4-5", + &Usage { + cache_read: 100_000, + cache_write: 100_000, + ..Default::default() + }, + ) + .unwrap(); // Sonnet 4.5:输入 $3、写 $3.75 → 十万 token 多花 $0.075 assert_eq!(read_only - with_writes, 75_000); } @@ -1095,103 +475,78 @@ mod saving_tests { fn a_cache_that_never_gets_read_is_a_loss_and_says_so() { // **负数是一条结论**,不是一个要被夹到零的边界:这个用法上 // 缓存在亏钱,而那正是最该让人看见的一种情况。 - let p = Prices::builtin().unwrap(); - let v = p - .cache_saving( - "claude-sonnet-4-5", - &Usage { - cache_write: 200_000, - ..Default::default() - }, - ) - .unwrap(); + let p = PriceBook::builtin().unwrap(); + let v = saving( + &p, + "claude-sonnet-4-5", + &Usage { + cache_write: 200_000, + ..Default::default() + }, + ) + .unwrap(); assert_eq!(v, -150_000, "写二十万、一次没读到,多花 $0.15"); } /// 回本线:读量到写量的约 28% 就打平。 #[test] fn reading_back_a_third_of_what_was_written_already_pays_for_it() { - let p = Prices::builtin().unwrap(); - let v = p - .cache_saving( - "claude-sonnet-4-5", - &Usage { - cache_write: 100_000, - cache_read: 33_000, - ..Default::default() - }, - ) - .unwrap(); + let p = PriceBook::builtin().unwrap(); + let v = saving( + &p, + "claude-sonnet-4-5", + &Usage { + cache_write: 100_000, + cache_read: 33_000, + ..Default::default() + }, + ) + .unwrap(); assert!(v > 0, "读回三分之一就该是赚的,实际 {v}"); } #[test] fn an_unpriced_model_cannot_say_how_much_was_saved() { // **「省了 0 元」和「算不出来省了多少」是两句不同的话**。 - let p = Prices::builtin().unwrap(); + let p = PriceBook::builtin().unwrap(); let u = Usage { cache_read: 1000, ..Default::default() }; - assert_eq!(p.cache_saving("某个中转站的模型", &u), None); + assert_eq!(saving(&p, "某个中转站的模型", &u), None); } #[test] fn a_long_context_cache_hit_saves_more_because_the_full_rate_is_higher() { // 超过 200k 之后输入单价翻倍,那时缓存命中省下的也更多。 - let p = Prices::builtin().unwrap(); - let short = p - .cache_saving( - "claude-sonnet-4-5", - &Usage { - cache_read: 100_000, - ..Default::default() - }, - ) - .unwrap(); - let long = p - .cache_saving( - "claude-sonnet-4-5", - &Usage { - input: 150_000, - cache_read: 100_000, - ..Default::default() - }, - ) - .unwrap(); - assert!( - long > short, - "长上下文的缓存命中省得更多:{short} vs {long}" - ); - } - #[test] - fn a_relay_can_have_its_own_price_for_the_same_model() { - // **没有这一层,同一个模型在官方和中转站算出来是同一个价, - // 而 `cheapest` 就没有任何判据** - let d = tempfile::tempdir().unwrap(); - let f = d.path().join("pricing.yaml"); - std::fs::write( - &f, - "providers:\n relay-cn:\n claude-sonnet-4-5:\n input: 0.0000018\n output: 0.000009\n", + let p = PriceBook::builtin().unwrap(); + let short = saving( + &p, + "claude-sonnet-4-5", + &Usage { + cache_read: 100_000, + ..Default::default() + }, + ) + .unwrap(); + let long = saving( + &p, + "claude-sonnet-4-5", + &Usage { + input: 150_000, + cache_read: 100_000, + ..Default::default() + }, ) .unwrap(); - let p = Prices::builtin().unwrap().with_overrides(&f).unwrap(); - let (relay_in, _) = p.unit_micros("relay-cn", "claude-sonnet-4-5").unwrap(); - let (official_in, _) = p.unit_micros("anthropic", "claude-sonnet-4-5").unwrap(); assert!( - relay_in < official_in, - "中转站的价没生效:{relay_in} vs {official_in}" - ); - // 没写进 providers 的那家走通用表 - assert_eq!( - p.unit_micros("别的家", "claude-sonnet-4-5"), - p.unit_micros("anthropic", "claude-sonnet-4-5") + long > short, + "长上下文的缓存命中省得更多:{short} vs {long}" ); } - #[test] fn an_unknown_model_has_no_unit_price_rather_than_a_made_up_one() { - let p = Prices::builtin().unwrap(); + let p = PriceBook::builtin().unwrap(); assert_eq!(p.unit_micros("x", "完全没见过的模型"), None); } } diff --git a/crates/tw-pricing/src/sheet.rs b/crates/tw-pricing/src/sheet.rs new file mode 100644 index 00000000..692bae04 --- /dev/null +++ b/crates/tw-pricing/src/sheet.rs @@ -0,0 +1,355 @@ +//! 自定义价目表:写在 config.yaml 的 `pricing` 段里。 +//! +//! ```yaml +//! pricing: +//! auto_update: false # 不写就是开 +//! sheets: +//! - name: 中转协议价 +//! multiplier: 0.8 # 作用于默认价目表的全部单价 +//! models: # 单独覆盖的模型,不受倍率影响 +//! claude-sonnet-4-5-thinking: +//! input: 3 +//! output: 15 +//! cache_read: 0.3 +//! cache_write_5m: 3.75 +//! cache_write_1h: 6 +//! +//! providers: +//! - name: relay-hk +//! pricing: 中转协议价 # 不写就按默认价目表 +//! ``` +//! +//! **单位是每百万 tokens 的美元**,和厂商定价页上印的一样。让用户写 +//! `0.000003` 是在要求他做一次换算,而换算是会错的 —— 差一个数量级的 +//! 价格,比没有价格更糟,因为它看起来是个确定的数字。 +//! +//! **覆盖价的每个字段都写明数值,计算时不推算。**只写输入输出、其余按 +//! 默认价目表的比例补全的做法有两个问题:默认价目表会定期刷新,一次刷新 +//! 就能让用户亲手设的覆盖价悄悄变掉;而文件里写着的数字也不再是实际计费 +//! 的数字。按比例预填是界面在新建覆盖时做的一次性的事,写进文件的是结果。 + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use crate::ModelPrice; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PricingConfig { + /// 定期联网刷新默认价目表。**默认开**,和应用自己的更新检查一样 + #[serde(default = "yes", skip_serializing_if = "is_yes")] + pub auto_update: bool, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub sheets: Vec, +} + +impl Default for PricingConfig { + fn default() -> Self { + Self { + auto_update: true, + sheets: Vec::new(), + } + } +} + +fn yes() -> bool { + true +} + +fn is_yes(v: &bool) -> bool { + *v +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SheetDef { + pub name: String, + /// 作用于默认价目表的**全部**单价,包括缓存与长上下文单价 + #[serde(default = "one", skip_serializing_if = "is_one")] + pub multiplier: f64, + /// 单独覆盖的模型。**覆盖价不受倍率影响** —— 它就是那个价 + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub models: BTreeMap, +} + +fn one() -> f64 { + 1.0 +} + +fn is_one(v: &f64) -> bool { + *v == 1.0 +} + +/// 一个模型的单价,**每百万 tokens 的美元**。 +/// +/// 输入、输出和三档缓存单价必填。长上下文单价**成对**写或者都不写 —— +/// 不写就是不分档,多长的请求都按上面那组单价算。 +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PerMillion { + pub input: f64, + pub output: f64, + pub cache_read: f64, + pub cache_write_5m: f64, + pub cache_write_1h: f64, + /// 单次请求输入超过 200K tokens 之后的单价 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub input_above_200k: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub output_above_200k: Option, +} + +#[derive(Debug, thiserror::Error, PartialEq)] +pub enum SheetError { + #[error("有一张价目表没有名字")] + EmptyName, + #[error("价目表名称「{0}」首尾不能有空白")] + PaddedName(String), + #[error("价目表名字重复:{0}")] + DuplicateName(String), + #[error("价目表「{sheet}」的倍率 {value} 不对:要是一个大于 0 的数")] + BadMultiplier { sheet: String, value: f64 }, + #[error("价目表「{sheet}」里有一个模型没写名字")] + EmptyModel { sheet: String }, + #[error("价目表「{sheet}」里 `{model}` 的{field}是 {value}:单价不能是负数")] + BadPrice { + sheet: String, + model: String, + field: &'static str, + value: f64, + }, + #[error("价目表「{sheet}」里 `{model}` 的长上下文单价要输入、输出一起写")] + HalfLongContext { sheet: String, model: String }, +} + +impl PricingConfig { + /// **负价不是「便宜」,是写错了。**让它进去的话,`cheapest` 会永远 + /// 选中那一家,而费用栏会往下走。 + pub fn validate(&self) -> Result<(), SheetError> { + let mut seen = std::collections::HashSet::new(); + for s in &self.sheets { + s.validate()?; + if !seen.insert(s.name.as_str()) { + return Err(SheetError::DuplicateName(s.name.clone())); + } + } + Ok(()) + } + + pub fn sheet(&self, name: &str) -> Option<&SheetDef> { + self.sheets.iter().find(|s| s.name == name) + } +} + +impl SheetDef { + /// 这一张本身写得对不对。**名字重不重复要看整份配置**,不在这里查。 + pub fn validate(&self) -> Result<(), SheetError> { + if self.name.trim().is_empty() { + return Err(SheetError::EmptyName); + } + if self.name.trim() != self.name { + return Err(SheetError::PaddedName(self.name.clone())); + } + if !(self.multiplier.is_finite() && self.multiplier > 0.0) { + return Err(SheetError::BadMultiplier { + sheet: self.name.clone(), + value: self.multiplier, + }); + } + for (model, p) in &self.models { + if model.trim().is_empty() { + return Err(SheetError::EmptyModel { + sheet: self.name.clone(), + }); + } + for (field, value) in p.fields() { + if !(value.is_finite() && value >= 0.0) { + return Err(SheetError::BadPrice { + sheet: self.name.clone(), + model: model.clone(), + field, + value, + }); + } + } + if p.input_above_200k.is_some() != p.output_above_200k.is_some() { + return Err(SheetError::HalfLongContext { + sheet: self.name.clone(), + model: model.clone(), + }); + } + } + Ok(()) + } +} + +impl PerMillion { + fn fields(&self) -> Vec<(&'static str, f64)> { + let mut out = vec![ + ("输入单价", self.input), + ("输出单价", self.output), + ("缓存读取单价", self.cache_read), + ("缓存写入(5 分钟)单价", self.cache_write_5m), + ("缓存写入(1 小时)单价", self.cache_write_1h), + ]; + for (name, v) in [ + ("长上下文输入单价", self.input_above_200k), + ("长上下文输出单价", self.output_above_200k), + ] { + if let Some(v) = v { + out.push((name, v)); + } + } + out + } + + /// 换成每 token 的价格。**按写的算,一个字段都不推** —— 见模块注释。 + /// + /// 上下文窗口不是价格,从默认价目表里这个模型那儿取。 + pub(crate) fn to_price(&self, max_input_tokens: Option) -> ModelPrice { + const M: f64 = 1e-6; + ModelPrice { + input: self.input * M, + output: self.output * M, + cache_read: Some(self.cache_read * M), + cache_write_5m: Some(self.cache_write_5m * M), + cache_write_1h: Some(self.cache_write_1h * M), + input_above_200k: self.input_above_200k.map(|v| v * M), + output_above_200k: self.output_above_200k.map(|v| v * M), + max_input_tokens, + } + } + + /// 一个价格**实际按什么单价计费**,换成每百万 tokens。 + /// + /// 数据集里没单独定价的缓存档按计费时的同一套规则补上(见 + /// [`ModelPrice::rates`])—— 显示出来的数字和记账用的必须是同一个。 + pub fn of(p: &ModelPrice) -> Self { + const M: f64 = 1e6; + // 浮点换算会带出 `2.9999999999999996` 这种尾巴 —— 这个数要显示给人看, + // 也可能被写回配置。十位小数足够表示任何真实的单价 + let r = |v: f64| (v * M * 1e10).round() / 1e10; + let rates = p.rates(false); + Self { + input: r(rates.input), + output: r(rates.output), + cache_read: r(rates.cache_read), + cache_write_5m: r(rates.cache_write_5m), + cache_write_1h: r(rates.cache_write_1h), + input_above_200k: p.input_above_200k.map(r), + output_above_200k: p.output_above_200k.map(r), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn cfg(y: &str) -> PricingConfig { + serde_yaml_ng::from_str(y).unwrap() + } + + const FULL: &str = + "input: 3, output: 15, cache_read: 0.3, cache_write_5m: 3.75, cache_write_1h: 6"; + + #[test] + fn nothing_written_means_auto_update_on_and_no_sheets() { + let c = cfg("{}"); + assert!(c.auto_update); + assert!(c.sheets.is_empty()); + // 默认值不写回文件 + assert_eq!(serde_yaml_ng::to_string(&c).unwrap().trim(), "{}"); + } + + #[test] + fn a_misspelled_price_field_is_an_error_not_a_silent_zero() { + let e = serde_yaml_ng::from_str::( + "sheets:\n - name: a\n models:\n m: { inptu: 1, output: 2 }\n", + ) + .unwrap_err(); + assert!(e.to_string().contains("inptu"), "{e}"); + } + + #[test] + fn an_override_has_to_spell_out_the_cache_prices() { + // 只写输入输出的话,缓存读按什么算就成了一个隐藏的决定 + let e = serde_yaml_ng::from_str::( + "sheets:\n - name: a\n models:\n m: { input: 1, output: 2 }\n", + ) + .unwrap_err(); + assert!(e.to_string().contains("cache_read"), "{e}"); + } + + #[test] + fn a_negative_price_a_zero_multiplier_and_half_a_long_context_tier_are_refused() { + let e = cfg( + "sheets:\n - name: a\n models:\n m: { input: 3, output: 15, cache_read: -0.3, cache_write_5m: 3.75, cache_write_1h: 6 }\n", + ) + .validate() + .unwrap_err(); + assert!( + matches!( + e, + SheetError::BadPrice { + field: "缓存读取单价", + .. + } + ), + "{e}" + ); + let e = cfg("sheets:\n - name: a\n multiplier: 0\n") + .validate() + .unwrap_err(); + assert!(matches!(e, SheetError::BadMultiplier { .. }), "{e}"); + let e = cfg("sheets:\n - name: a\n - name: a\n") + .validate() + .unwrap_err(); + assert_eq!(e, SheetError::DuplicateName("a".into())); + let e = cfg(&format!( + "sheets:\n - name: a\n models:\n m: {{ {FULL}, input_above_200k: 6 }}\n" + )) + .validate() + .unwrap_err(); + assert!(matches!(e, SheetError::HalfLongContext { .. }), "{e}"); + } + + #[test] + fn an_override_is_taken_exactly_as_written() { + let p = PerMillion { + input: 2.0, + output: 10.0, + cache_read: 0.25, + cache_write_5m: 2.0, + cache_write_1h: 2.0, + input_above_200k: None, + output_above_200k: None, + } + .to_price(Some(200_000)); + let per_m = |v: Option| v.map(|x| (x * 1e6 * 1e6).round() / 1e6); + assert_eq!(per_m(p.cache_read), Some(0.25)); + assert_eq!(per_m(p.cache_write_5m), Some(2.0)); + // 没写长上下文单价就是不分档 + assert_eq!(p.input_above_200k, None); + assert_eq!(p.max_input_tokens, Some(200_000)); + } + + #[test] + fn the_displayed_rates_are_the_rates_that_get_charged() { + // 数据集里没单独定价的缓存档:按输入价计费,也就按输入价显示 + let p = ModelPrice { + input: 1e-6, + output: 2e-6, + cache_write_5m: Some(1.25e-6), + ..Default::default() + }; + let v = PerMillion::of(&p); + assert_eq!(v.cache_read, 1.0); + assert_eq!(v.cache_write_5m, 1.25); + // 1 小时档没有就按 5 分钟档 + assert_eq!(v.cache_write_1h, 1.25); + // 显示的和写回去的是同一组数:换算一个来回不变 + assert_eq!(PerMillion::of(&v.to_price(None)), v); + } +} diff --git a/crates/tw-pricing/src/table.rs b/crates/tw-pricing/src/table.rs new file mode 100644 index 00000000..21fd48e7 --- /dev/null +++ b/crates/tw-pricing/src/table.rs @@ -0,0 +1,226 @@ +//! 默认价目表:公开价格数据集。 +//! +//! 随版本内置一份(离线、首次启动时用),之后联网定期刷新。 + +use std::collections::HashMap; + +use crate::{ModelPrice, PricingError, name}; + +/// 内置快照。**pin 在一个具体的 commit 上**,来历见 `data/PROVENANCE.md`。 +const SNAPSHOT: &[u8] = include_bytes!("../data/model_prices.json.gz"); + +/// 快照对应的上游 commit 日期。 +pub const SNAPSHOT_DATE: &str = "2026-09-09"; + +/// 刷新去哪儿拉。 +/// +/// **写死在代码里,不从配置读。**一个「价目表源」配置项等于给了任何能 +/// 改 config.yaml 的人一个往这个进程里喂 JSON 的入口,而那份 JSON 会 +/// 决定用户看到的每一个金额。 +pub const UPDATE_URL: &str = + "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"; + +/// 这份表是从哪儿来的。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TableSource { + /// 随版本内置的快照 + Builtin, + /// 联网拉回来的 + Fetched, + /// 什么都没加载成 —— 每个模型都会是「价格未知」 + Empty, +} + +impl TableSource { + pub fn slug(&self) -> &'static str { + match self { + TableSource::Builtin => "builtin", + TableSource::Fetched => "fetched", + TableSource::Empty => "empty", + } + } +} + +#[derive(Debug, Clone)] +pub struct Table { + prices: HashMap, + /// **这份表自己的日期**。成本旁边要标它:一个两个月前的价目表算出来的 + /// 数字,和一个昨天的,可信度完全不同 + pub date: String, + pub source: TableSource, +} + +impl Table { + /// 随版本内置的那份。 + pub fn builtin() -> Result { + let raw = decompress(SNAPSHOT)?; + let prices = parse_dataset(&raw)?; + Ok(Self { + prices, + date: SNAPSHOT_DATE.to_string(), + source: TableSource::Builtin, + }) + } + + /// 联网拉回来的数据集。`date` 是拉取那天。 + pub fn fetched(raw: &[u8], date: String) -> Result { + Ok(Self { + prices: parse_dataset(raw)?, + date, + source: TableSource::Fetched, + }) + } + + /// 一张空表。**每个模型都会是「价格未知」** —— 那是价目表读不了时 + /// 唯一诚实的答案。 + pub fn empty() -> Self { + Self { + prices: HashMap::new(), + date: String::new(), + source: TableSource::Empty, + } + } + + pub fn len(&self) -> usize { + self.prices.len() + } + + pub fn is_empty(&self) -> bool { + self.prices.is_empty() + } + + /// 查一个模型的价格,**并且说清是不是跨平台借来的**(第二个值为真时, + /// 算出来的钱一律标成估算)。 + pub fn lookup(&self, model: &str) -> Option<(&ModelPrice, bool)> { + for c in name::candidates(model) { + if let Some(p) = self.prices.get(&c) { + return Some((p, false)); + } + } + // 跨平台的最后一招。**它不精确**,见 name::cross_platform_fallback + let c = name::cross_platform_fallback(model)?; + self.prices.get(&c).map(|p| (p, true)) + } + + pub fn get(&self, model: &str) -> Option<&ModelPrice> { + self.lookup(model).map(|(p, _)| p) + } + + /// 按原样查一个键,**不做任何名字归一化**。给核对数据集本身的测试用。 + pub fn exact(&self, key: &str) -> Option<&ModelPrice> { + self.prices.get(key) + } + + /// 表里所有的模型名。 + pub fn models(&self) -> impl Iterator { + self.prices.keys().map(String::as_str) + } + + /// 和 `old` 比,有几个模型的价格变了、是新增的、或者不在了。 + pub fn changed_from(&self, old: &Table) -> usize { + let changed_or_new = self + .prices + .iter() + .filter(|(m, p)| old.prices.get(*m) != Some(p)) + .count(); + let gone = old + .prices + .keys() + .filter(|m| !self.prices.contains_key(*m)) + .count(); + changed_or_new + gone + } +} + +/// 解析 LiteLLM 那份 JSON。**一个带价格的模型都没有就是失败** —— 那多半 +/// 不是那份数据集(被劫持的响应、一个错误页)。 +fn parse_dataset(raw: &[u8]) -> Result, PricingError> { + let parsed: HashMap = + serde_json::from_slice(raw).map_err(|e| PricingError::Dataset(e.to_string()))?; + let prices: HashMap = parsed + .into_iter() + // `sample_spec` 那种说明用的伪条目没有价格,自然会被滤掉 + .filter_map(|(k, v)| price_from(&v).map(|p| (k, p))) + .collect(); + if prices.is_empty() { + return Err(PricingError::Dataset( + "里面一个带价格的模型都没有 —— 多半不是那份数据集".into(), + )); + } + Ok(prices) +} + +fn decompress(gz: &[u8]) -> Result, PricingError> { + use std::io::Read; + let mut d = flate2::read::GzDecoder::new(gz); + let mut out = Vec::with_capacity(2_500_000); + d.read_to_end(&mut out) + .map_err(|e| PricingError::Snapshot(e.to_string()))?; + Ok(out) +} + +fn price_from(v: &serde_json::Value) -> Option { + let f = |k: &str| v.get(k).and_then(|x| x.as_f64()); + // 没有输入或输出单价的条目不是一个能算钱的模型(嵌入、审核、以及 + // 数据集里那条 `sample_spec` 说明)。 + let input = f("input_cost_per_token")?; + let output = f("output_cost_per_token").unwrap_or(0.0); + Some(ModelPrice { + input, + output, + cache_read: f("cache_read_input_token_cost"), + cache_write_5m: f("cache_creation_input_token_cost"), + cache_write_1h: f("cache_creation_input_token_cost_above_1hr"), + input_above_200k: f("input_cost_per_token_above_200k_tokens"), + output_above_200k: f("output_cost_per_token_above_200k_tokens"), + max_input_tokens: v.get("max_input_tokens").and_then(|x| x.as_u64()), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_builtin_snapshot_loads_and_has_the_models_people_actually_use() { + let t = Table::builtin().unwrap(); + assert!(t.len() > 1000, "只有 {} 个模型,快照像是坏的", t.len()); + assert_eq!(t.source, TableSource::Builtin); + assert_eq!(t.date, SNAPSHOT_DATE); + for m in [ + "claude-sonnet-4-5", + "claude-opus-4-20250514", + "claude-haiku-4-5", + "claude-3-5-haiku-20241022", + "gpt-4o", + ] { + assert!(t.get(m).is_some(), "查不到 {m}"); + } + } + + #[test] + fn a_response_that_is_not_the_dataset_is_refused() { + // 被劫持的响应、一个错误页:解析得了的 JSON,但一个价格都没有 + assert!(Table::fetched(b"{\"error\": \"rate limited\"}", "x".into()).is_err()); + assert!(Table::fetched(b"", "x".into()).is_err()); + } + + #[test] + fn the_snapshot_date_is_a_real_date_because_it_has_to_be_shown() { + assert_eq!(SNAPSHOT_DATE.len(), 10, "日期得是 YYYY-MM-DD"); + } + + #[test] + fn a_refresh_counts_changed_new_and_removed_models() { + let mk = |json: &str| Table::fetched(json.as_bytes(), "d".into()).unwrap(); + let old = mk( + r#"{"a":{"input_cost_per_token":1e-6,"output_cost_per_token":2e-6},"b":{"input_cost_per_token":1e-6,"output_cost_per_token":2e-6},"gone":{"input_cost_per_token":1e-6}}"#, + ); + let new = mk( + r#"{"a":{"input_cost_per_token":1e-6,"output_cost_per_token":2e-6},"b":{"input_cost_per_token":3e-6,"output_cost_per_token":2e-6},"c":{"input_cost_per_token":1e-6,"output_cost_per_token":2e-6}}"#, + ); + // b 改价、c 新增、gone 不在了;a 没变 + assert_eq!(new.changed_from(&old), 3); + assert_eq!(new.changed_from(&new), 0); + } +} diff --git a/crates/tw-scan/src/rules.rs b/crates/tw-scan/src/rules.rs index 948cc0ea..170b29ab 100644 --- a/crates/tw-scan/src/rules.rs +++ b/crates/tw-scan/src/rules.rs @@ -20,8 +20,9 @@ //! 不是数据 —— 而住在 `config.yaml` 里还白捡了变更历史和一键回滚, //! 单独一个文件那两样都没有。 //! -//! (`pricing.yaml` 是另一回事:那是个十万条的厂商数据集,用户改的是 -//! 其中几行数据。目录表里把它单列了出来。) +//! (联网刷新下来的 `model_prices.json` 是另一回事:那是几千个模型的公开 +//! 价格数据集,是数据不是策略,不进版本历史。用户自己的价目表照样住在 +//! `config.yaml` 里。) use regex::Regex; use serde::{Deserialize, Serialize}; diff --git a/crates/tw-store/src/db.rs b/crates/tw-store/src/db.rs index a5db3372..61100eb4 100644 --- a/crates/tw-store/src/db.rs +++ b/crates/tw-store/src/db.rs @@ -16,7 +16,7 @@ use std::path::Path; use rusqlite::{Connection, OptionalExtension, params}; /// 当前 schema 版本。**加字段就加一,并在 `migrate` 里补一步。** -const SCHEMA: i64 = 10; +const SCHEMA: i64 = 11; /// 这一行算不出钱,**因为价目表里没有这个模型**:用量是有的,缺的是单价。 /// @@ -113,6 +113,9 @@ pub struct RequestRow { pub billing: String, /// 缓存命中省下了多少微分。`None` = 算不出来 pub cache_saved_micros: Option, + /// 金额按什么价格算的,JSON(`tw_api::PriceSourceView`)。没算出金额的、 + /// 老记录是 None + pub price_source: Option, } #[derive(Debug)] @@ -307,6 +310,17 @@ impl Db { "ALTER TABLE requests ADD COLUMN cancelled INTEGER NOT NULL DEFAULT 0;", )?; } + if from < 11 { + // 金额按什么价格算的:默认价目表(哪天的)、乘了哪张价目表的倍率、 + // 还是哪张价目表的覆盖价。 + // + // **记在行上。**价目表会刷新、会被改,事后按现在的配置去推当时用的 + // 是哪个价,推出来的是错的。 + // + // 老记录是 NULL:那时只有一份价目表,而它的日期没有记下来。 + self.conn + .execute_batch("ALTER TABLE requests ADD COLUMN price_source TEXT;")?; + } self.conn.pragma_update(None, "user_version", SCHEMA)?; Ok(()) } @@ -318,8 +332,8 @@ impl Db { (id, at_ms, client, provider, model, path, status, ttfb_ms, duration_ms, bytes, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost_micros, cost_estimated, error, local, routing, billing, cache_saved_micros, - client_hint, session, tool_calls, flagged, redacted, cancelled) - VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17,?18,?19,?20,?21,?22,?23,?24,?25,?26,?27)", + client_hint, session, tool_calls, flagged, redacted, cancelled, price_source) + VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17,?18,?19,?20,?21,?22,?23,?24,?25,?26,?27,?28)", params![ r.id, r.at_ms, @@ -348,6 +362,7 @@ impl Db { r.flagged, r.redacted, r.cancelled as i64, + r.price_source, ], )?; Ok(()) @@ -617,7 +632,7 @@ impl Db { /// **这是价格页存在的理由。**用户不会主动想起要配价格 —— 只有 /// 「有 37 条请求算不出钱,用的是这两个模型」这种具体证据才会 /// (高级功能的触发条件要绑在「这个问题存不存在」上)。 - pub fn unpriced_recent(&self, days: i64) -> Result<(i64, Vec), DbError> { + pub fn unpriced_recent(&self, days: i64) -> Result<(i64, Vec), DbError> { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_millis() as i64) @@ -627,23 +642,29 @@ impl Db { // 本来就没有成本),订阅制不算(它的成本不在这个维度上);失败的、 // 没有用量的也不算 —— 给那个模型配价格,那几行照样算不出钱,而这一页 // 让人去配的正是价格。 + let filter = format!( + "at_ms >= ?1 AND local = 0 AND {NO_PRICE} AND model IS NOT NULL AND model <> ''" + ); + // 总数单独数:下面那个列表有上限,拿它加出来的总数会偏低 + let total: i64 = self.conn.query_row( + &format!("SELECT COUNT(*) FROM requests WHERE {filter}"), + [since], + |r| r.get(0), + )?; + // **按 (上游, 模型) 分。**同一个模型在不同上游按不同的价目表计价, + // 该在哪张表里补价格取决于它走的是哪家 let mut st = self.conn.prepare(&format!( - "SELECT model, COUNT(*) FROM requests \ - WHERE at_ms >= ?1 AND local = 0 AND {NO_PRICE} \ - AND model IS NOT NULL AND model <> '' \ - GROUP BY model ORDER BY COUNT(*) DESC LIMIT 20" + "SELECT provider, model, COUNT(*) AS n FROM requests WHERE {filter} \ + GROUP BY provider, model ORDER BY n DESC, provider, model LIMIT 20" ))?; let rows = st.query_map([since], |r| { - Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)) + Ok(tw_api::UnpricedModel { + provider: r.get(0)?, + model: r.get(1)?, + requests: r.get(2)?, + }) })?; - let mut total = 0i64; - let mut models = Vec::new(); - for row in rows { - let (m, n) = row?; - total += n; - models.push(m); - } - Ok((total, models)) + Ok((total, rows.collect::>()?)) } pub fn summary(&self, since_ms: i64, until_ms: i64) -> Result { @@ -1053,6 +1074,7 @@ fn row_from(r: &rusqlite::Row) -> rusqlite::Result { routing: r.get("routing")?, billing: r.get("billing")?, cache_saved_micros: r.get("cache_saved_micros")?, + price_source: r.get("price_source")?, }) } @@ -1157,6 +1179,7 @@ mod tests { routing: None, billing: "per-token".into(), cache_saved_micros: None, + price_source: None, } } @@ -1670,6 +1693,7 @@ mod tests { db.conn .execute_batch( "DROP INDEX requests_session; + ALTER TABLE requests DROP COLUMN price_source; ALTER TABLE requests DROP COLUMN cancelled; ALTER TABLE requests DROP COLUMN redacted; ALTER TABLE requests DROP COLUMN flagged; @@ -1687,6 +1711,8 @@ mod tests { assert!(got.iter().all(|r| r.client_hint.is_none())); // 升级之前取消的请求根本不落库,所以老记录一条都不该是「已取消」 assert!(got.iter().all(|r| !r.cancelled)); + // 老记录不知道当时用的是哪份价目表,那就是不知道 + assert!(got.iter().all(|r| r.price_source.is_none())); let mut fresh = row(3, 300); fresh.client_hint = Some("codex".into()); fresh.session = Some("abc-100".into()); @@ -1908,7 +1934,32 @@ mod cost_state_tests { let (n, models) = db.unpriced_recent(7).unwrap(); assert_eq!(n, 1); - assert_eq!(models, vec!["中转站自己起的名字".to_string()]); + assert_eq!( + models, + vec![tw_api::UnpricedModel { + provider: "官方".into(), + model: "中转站自己起的名字".into(), + requests: 1, + }] + ); + } + + /// 列表有上限,总数没有。 + #[test] + fn the_unpriced_total_counts_every_request_not_just_the_listed_models() { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis() as i64; + let db = Db::in_memory().unwrap(); + for i in 0..25 { + let mut r = unknown_model(i + 1, now); + r.model = format!("m{i}"); + db.insert(&r).unwrap(); + } + let (n, models) = db.unpriced_recent(7).unwrap(); + assert_eq!(models.len(), 20); + assert_eq!(n, 25); } /// 会话的合计里有估算,**就得说出来**;每一轮也带着自己的记号。 diff --git a/crates/tw-store/src/lib.rs b/crates/tw-store/src/lib.rs index 350437b3..a1c28f62 100644 --- a/crates/tw-store/src/lib.rs +++ b/crates/tw-store/src/lib.rs @@ -18,5 +18,5 @@ pub mod task; pub use blobs::{Blobs, Which}; pub use db::{Db, DbError, Latency, RequestRow, Summary}; pub use disk::{DiskLevel, free_bytes, level_for}; -pub use recorder::Recorder; +pub use recorder::{Recorder, price_source}; pub use task::StoredBody; diff --git a/crates/tw-store/src/recorder.rs b/crates/tw-store/src/recorder.rs index 2d7b4827..92fdd335 100644 --- a/crates/tw-store/src/recorder.rs +++ b/crates/tw-store/src/recorder.rs @@ -9,7 +9,7 @@ use std::collections::HashMap; use tw_api::Event; -use tw_pricing::{Cost, Prices, Usage}; +use tw_pricing::{Cost, Usage}; use crate::blobs::{Blobs, Which}; use crate::db::{Db, RequestRow}; @@ -58,7 +58,9 @@ enum Ending<'a> { pub struct Recorder { db: Db, blobs: Blobs, - prices: Prices, + /// 和网关共用的那一份价格簿。**不是一份副本** —— 改了价目表,下一个 + /// 结束的请求就按新价算,不用重启 + pricing: tw_pricing::Shared, inflight: HashMap, level: DiskLevel, /// 上次查磁盘的时间。**不是每次写都查** —— statvfs 在每个请求上跑 @@ -90,12 +92,29 @@ const DISK_CHECK_EVERY_MS: i64 = 30_000; /// 代价是对称的(并多了或分多了),所以取一个人能理解的整数。 const SESSION_GAP_MS: i64 = 30 * 60 * 1000; +/// 一个价格的来源,给界面看的样子。`date`:当时默认价目表的数据日期。 +pub fn price_source(source: &tw_pricing::Source, date: &str) -> tw_api::PriceSourceView { + match source { + tw_pricing::Source::Default => tw_api::PriceSourceView::Default { + date: date.to_string(), + }, + tw_pricing::Source::Scaled { sheet, multiplier } => tw_api::PriceSourceView::Scaled { + sheet: sheet.clone(), + multiplier: *multiplier, + date: date.to_string(), + }, + tw_pricing::Source::Override { sheet } => tw_api::PriceSourceView::Override { + sheet: sheet.clone(), + }, + } +} + impl Recorder { - pub fn new(db: Db, blobs: Blobs, prices: Prices) -> Self { + pub fn new(db: Db, blobs: Blobs, pricing: tw_pricing::Shared) -> Self { Self { db, blobs, - prices, + pricing, inflight: HashMap::new(), sessions: HashMap::new(), level: DiskLevel::Ok, @@ -354,6 +373,7 @@ impl Recorder { routing: None, billing: String::new(), cache_saved_micros: None, + price_source: None, }); } Event::LeakSeen { @@ -442,11 +462,17 @@ impl Recorder { // Anthropic 在流的末尾才报累计输出 —— 断在中间时手里那个数是个 // 占位。按它算出来的钱只会偏低,当成实测会让「今日花费」悄悄少一截。 let partial = !matches!(how, Ending::Finished); - let cost = if counts_toward_money { - u.map(|u| self.prices.cost(&p.model, &u, partial)) + let book = self.pricing.load(); + // **按这个请求实际走的上游查价** —— 同一个模型在不同上游不是同一个价 + let resolved = if counts_toward_money { + book.resolve_for(&p.provider, &p.model) } else { None }; + let cost = match (&u, &resolved) { + (Some(u), Some(r)) => Some(r.cost(u, partial)), + _ => None, + }; let (cost_micros, estimated) = match cost { Some(Cost::Known(m)) => (Some(m), false), Some(Cost::Estimated(m)) => (Some(m), true), @@ -457,10 +483,16 @@ impl Recorder { // 缓存命中省下了多少。**在这里算,不在查询时算** // —— 查询时算意味着要把价目表带进 SQL,而价目表会变, // 那样「上周省了多少」会随着一次价格更新悄悄改变。 - let cache_saved_micros = if counts_toward_money { - u.and_then(|u| self.prices.cache_saving(&p.model, &u)) - } else { - None + let cache_saved_micros = match (&u, &resolved) { + (Some(u), Some(r)) => Some(r.cache_saving(u)), + _ => None, + }; + // 同一个道理:**按什么价算的也在这里记下**,事后推不回来 + let price_source = match (&resolved, cost_micros) { + (Some(r), Some(_)) => { + serde_json::to_string(&price_source(&r.source, &book.table().date)).ok() + } + _ => None, }; // **算完就报,不等人来问。**这是整条链上唯一知道价钱的 // 地方,而界面上那一列金额在它到达之前只能是「—」。 @@ -504,6 +536,7 @@ impl Recorder { routing: p.routing, billing: p.billing, cache_saved_micros, + price_source, }); } @@ -571,7 +604,7 @@ mod tests { let r = Recorder::new( Db::in_memory().unwrap(), Blobs::new(d.path().join("blobs")), - Prices::builtin().unwrap(), + tw_pricing::shared(tw_pricing::PriceBook::builtin().unwrap()), ); (d, r) } @@ -728,6 +761,68 @@ mod tests { ); } + /// **按上游选的价目表记账,而且改了价不用重启。** + /// + /// 以前按上游设的价格只给 `cheapest` 排序用,记账永远按通用价 —— 界面 + /// 上说「这家按这个价算」,而落库的金额不是;记账这一层还攥着启动时的 + /// 一份价目表副本,改了价格要重启才生效。 + #[test] + fn a_request_is_priced_by_its_upstreams_sheet_and_a_change_applies_without_a_restart() { + let d = tempfile::tempdir().unwrap(); + let pricing = tw_pricing::shared(tw_pricing::PriceBook::builtin().unwrap()); + let mut r = Recorder::new( + Db::in_memory().unwrap(), + Blobs::new(d.path().join("blobs")), + pricing.clone(), + ); + let usage = || { + Some(tw_api::UsageView { + input: 100_000, + ..Default::default() + }) + }; + r.on_event(&started(1, "claude-sonnet-4-5")); // provider = 官方 + r.on_event(&finished(1, usage())); + assert_eq!(r.db().get(1).unwrap().unwrap().cost_micros, Some(300_000)); + + // 给「官方」选一张半价的价目表 —— 同一个 Recorder,没有重启 + let half = tw_pricing::PricingConfig { + auto_update: true, + sheets: vec![tw_pricing::SheetDef { + name: "半价".into(), + multiplier: 0.5, + models: Default::default(), + }], + }; + let next = pricing + .load() + .with_config(half, [("官方".to_string(), "半价".to_string())]); + pricing.store(std::sync::Arc::new(next)); + r.on_event(&started(2, "claude-sonnet-4-5")); + r.on_event(&finished(2, usage())); + let row = r.db().get(2).unwrap().unwrap(); + assert_eq!(row.cost_micros, Some(150_000)); + + // 两条各自记着当时按什么价算的 + let source = |row: &RequestRow| -> tw_api::PriceSourceView { + serde_json::from_str(row.price_source.as_deref().unwrap()).unwrap() + }; + assert_eq!( + source(&r.db().get(1).unwrap().unwrap()), + tw_api::PriceSourceView::Default { + date: tw_pricing::SNAPSHOT_DATE.into() + } + ); + assert_eq!( + source(&row), + tw_api::PriceSourceView::Scaled { + sheet: "半价".into(), + multiplier: 0.5, + date: tw_pricing::SNAPSHOT_DATE.into() + } + ); + } + #[test] fn a_model_with_no_price_gets_no_cost_rather_than_zero() { // **成本三态的第三态。**记成 0 会让总额悄悄偏低。 diff --git a/crates/tw-store/tests/m3_acceptance.rs b/crates/tw-store/tests/m3_acceptance.rs index d478f5d1..4ef7cf0b 100644 --- a/crates/tw-store/tests/m3_acceptance.rs +++ b/crates/tw-store/tests/m3_acceptance.rs @@ -51,6 +51,7 @@ fn req(id: i64, at_ms: i64) -> RequestRow { routing: None, billing: "per-token".into(), cache_saved_micros: Some(1_500), + price_source: None, } } diff --git a/scripts/smoke.sh b/scripts/smoke.sh index 94f97e74..bd8dd8cd 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -360,9 +360,9 @@ fi step "配置目录里只有一份配置文件" # **策略类的东西一律进 config.yaml。**这一条会被慢慢侵蚀 —— 每加一个 # 功能都有一个「顺手开个文件放它的设置」的诱惑,而每一个单独看都很合理。 -STRAY=$(find "$THINKWATCH_HOME" -maxdepth 1 -name '*.yaml' ! -name 'config.yaml' ! -name 'pricing.yaml' 2>/dev/null) +STRAY=$(find "$THINKWATCH_HOME" -maxdepth 1 -name '*.yaml' ! -name 'config.yaml' 2>/dev/null) if [ -z "$STRAY" ]; then - ok "除了 config.yaml(和 pricing.yaml)没有别的配置文件" + ok "除了 config.yaml 没有别的配置文件" else bad "冒出了别的配置文件" "$STRAY" fi