diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 0e2ddfc6..694682ce 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -1274,6 +1274,12 @@ slug_enum! { #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct AttemptView { pub provider: String, + /// 规则改写了模型名:这一跳发给(没发出去的,要发给)上游的是哪个。没改写的 + /// 没有 —— 发出去的就是客户端要的那个(`RequestStarted::model`)。 + /// + /// **费用按它算**:请求改写成另一个模型发出去,上游按那个模型收钱。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model: Option, /// WebSocket 的那一跳是一次握手:上游同意升级(101)是 `served`,回了别的 /// 状态码是 `status`,连不上是 `error`。 pub outcome: AttemptOutcome, @@ -2295,7 +2301,9 @@ pub struct PriceFields { pub cache_read: f64, pub cache_write_5m: f64, pub cache_write_1h: f64, - /// 单次请求输入超过 200K tokens 之后的单价。**成对出现**;没有 = 不分档 + /// 单次请求的输入(连同缓存读写)超过 200K tokens 之后的单价。**成对出现**; + /// 没有 = 没有 200K 这一档(门槛是别的数的档不在这里,见 + /// `tw_pricing::PerMillion::of`) #[serde(default, skip_serializing_if = "Option::is_none")] pub input_above_200k: Option, #[serde(default, skip_serializing_if = "Option::is_none")] diff --git a/crates/tw-config/tests/manual/schema.rs b/crates/tw-config/tests/manual/schema.rs index 32f8a9d5..6b691808 100644 --- a/crates/tw-config/tests/manual/schema.rs +++ b/crates/tw-config/tests/manual/schema.rs @@ -820,8 +820,8 @@ pub fn sections() -> Vec
{ Kind::Num, Def::Unset, t( - "Input price once a request's input exceeds 200K tokens. Written together with `output_above_200k`, or neither.", - "单次请求输入超过 200K token 后的输入单价。与 `output_above_200k` 同时写或都不写。", + "Input price once a request's input, cache reads and writes included, exceeds 200K tokens. Written together with `output_above_200k`, or neither. Cache prices stay the ones above.", + "单次请求的输入(连同缓存读写)超过 200K token 后的输入单价。与 `output_above_200k` 同时写或都不写;缓存单价仍按上面写的算。", ), ), row( @@ -829,8 +829,8 @@ pub fn sections() -> Vec
{ Kind::Num, Def::Unset, t( - "Output price once a request's input exceeds 200K tokens.", - "单次请求输入超过 200K token 后的输出单价。", + "Output price once a request's input, cache reads and writes included, exceeds 200K tokens.", + "单次请求的输入(连同缓存读写)超过 200K token 后的输出单价。", ), ), ], diff --git a/crates/tw-control/tests/in_flight.rs b/crates/tw-control/tests/in_flight.rs index 87c323fa..51125c58 100644 --- a/crates/tw-control/tests/in_flight.rs +++ b/crates/tw-control/tests/in_flight.rs @@ -90,6 +90,7 @@ async fn it_gives_every_running_request_with_what_has_happened_to_it_so_far() { denied_by: None, attempts: vec![tw_api::AttemptView { provider: "官方".into(), + model: None, outcome: tw_api::AttemptOutcome::Served, status: Some(200), error: None, diff --git a/crates/tw-control/tests/live_state.rs b/crates/tw-control/tests/live_state.rs index a1b399ac..3df6d5c7 100644 --- a/crates/tw-control/tests/live_state.rs +++ b/crates/tw-control/tests/live_state.rs @@ -147,6 +147,7 @@ async fn a_request_still_running_can_be_opened_and_becomes_whole_when_it_ends() denied_by: None, attempts: vec![tw_api::AttemptView { provider: "官方".into(), + model: None, outcome: tw_api::AttemptOutcome::Served, status: Some(200), error: None, diff --git a/crates/tw-gateway/src/server.rs b/crates/tw-gateway/src/server.rs index 2727a916..a4bf0a59 100644 --- a/crates/tw-gateway/src/server.rs +++ b/crates/tw-gateway/src/server.rs @@ -301,15 +301,18 @@ pub(crate) fn routed_nowhere(id: u64, choice: Choice) -> tw_api::Event { } } -/// 上游回了话的一跳:`served` 或者 `status`。 +/// 上游回了话的一跳:`served` 或者 `status`。`model`:改写过的模型名(见 +/// `AttemptView::model`) pub(crate) fn hop( provider: &str, + model: Option, outcome: tw_api::AttemptOutcome, status: u16, started: std::time::Instant, ) -> tw_api::AttemptView { tw_api::AttemptView { provider: provider.to_string(), + model, outcome, status: Some(status), error: None, @@ -320,11 +323,13 @@ pub(crate) fn hop( /// 没有收到响应的一跳。`error` 和这一跳报给客户端的那条错误是同一句。 pub(crate) fn hop_failed( provider: &str, + model: Option, error: tw_types::Msg, started: std::time::Instant, ) -> tw_api::AttemptView { tw_api::AttemptView { provider: provider.to_string(), + model, outcome: tw_api::AttemptOutcome::Error, status: None, error: Some(error), diff --git a/crates/tw-gateway/src/server/pipeline/hop.rs b/crates/tw-gateway/src/server/pipeline/hop.rs index 5f1fe643..07cff23e 100644 --- a/crates/tw-gateway/src/server/pipeline/hop.rs +++ b/crates/tw-gateway/src/server/pipeline/hop.rs @@ -82,7 +82,12 @@ pub(super) async fn try_upstreams<'a>( let hop_started = std::time::Instant::now(); if let Some(err) = protocol_mismatch(req, reading.generates, provider) { - chain.push(hop_failed(&provider.name, err.detail.clone(), hop_started)); + chain.push(hop_failed( + &provider.name, + None, + err.detail.clone(), + hop_started, + )); last_err = Some(err); continue; } @@ -115,7 +120,12 @@ pub(super) async fn try_upstreams<'a>( )); // 被拒的这一跳没有发出去。**它在尝试链上**,原因就是那条拒绝 —— // 链上看得出请求本来要去哪家、在哪一步停下的 - chain.push(hop_failed(&provider.name, err.detail.clone(), hop_started)); + chain.push(hop_failed( + &provider.name, + None, + err.detail.clone(), + hop_started, + )); denied_by = Some(rule); halt = Some(err); break; @@ -128,10 +138,21 @@ pub(super) async fn try_upstreams<'a>( } }; + // 这一跳要发的模型名:规则改写过、和客户端要的不一样的才记(见 `AttemptView::model`) + let model = effective_set + .model + .clone() + .filter(|m| *m != reading.facts.model); + let out = match prepare(state, req, reading, provider, &effective_set, id) { Ok(out) => out, Err(err) => { - chain.push(hop_failed(&provider.name, err.detail.clone(), hop_started)); + chain.push(hop_failed( + &provider.name, + model.clone(), + err.detail.clone(), + hop_started, + )); last_err = Some(err); continue; } @@ -158,7 +179,12 @@ pub(super) async fn try_upstreams<'a>( state.health.record_failure(&provider.name), ); let err = GatewayError::config(crate::state::credential_failed(e, &provider.name)); - chain.push(hop_failed(&provider.name, err.detail.clone(), hop_started)); + chain.push(hop_failed( + &provider.name, + model.clone(), + err.detail.clone(), + hop_started, + )); last_err = Some(err); continue; } @@ -177,7 +203,12 @@ pub(super) async fn try_upstreams<'a>( ); let err = GatewayError::config(crate::state::credential_failed(e.msg(), &provider.name)); - chain.push(hop_failed(&provider.name, err.detail.clone(), hop_started)); + chain.push(hop_failed( + &provider.name, + model.clone(), + err.detail.clone(), + hop_started, + )); last_err = Some(err); continue; } @@ -221,6 +252,7 @@ pub(super) async fn try_upstreams<'a>( ); chain.push(hop( &provider.name, + model.clone(), tw_api::AttemptOutcome::Status, r.status().as_u16(), hop_started, @@ -260,6 +292,7 @@ pub(super) async fn try_upstreams<'a>( ); chain.push(hop( &provider.name, + model.clone(), tw_api::AttemptOutcome::Served, r.status().as_u16(), hop_started, @@ -292,7 +325,12 @@ pub(super) async fn try_upstreams<'a>( access keys: {detail}" )), }; - chain.push(hop_failed(&provider.name, err.detail.clone(), hop_started)); + chain.push(hop_failed( + &provider.name, + model.clone(), + err.detail.clone(), + hop_started, + )); last_err = Some(err); continue; } diff --git a/crates/tw-gateway/src/ws.rs b/crates/tw-gateway/src/ws.rs index 5ee2c1a2..a7f3432e 100644 --- a/crates/tw-gateway/src/ws.rs +++ b/crates/tw-gateway/src/ws.rs @@ -161,11 +161,12 @@ pub async fn proxy( // 报在结局之前,存储层落库时手上才有它 let name = &upstream.provider.name; let attempt = match &connected { - Ok(_) => crate::server::hop(name, tw_api::AttemptOutcome::Served, 101, hop_started), + // WebSocket 不改写模型名:升级请求没有正文可改 + Ok(_) => crate::server::hop(name, None, tw_api::AttemptOutcome::Served, 101, hop_started), Err(NotConnected { status: Some(s), .. - }) => crate::server::hop(name, tw_api::AttemptOutcome::Status, *s, hop_started), - Err(e) => crate::server::hop_failed(name, e.why.clone(), hop_started), + }) => crate::server::hop(name, None, tw_api::AttemptOutcome::Status, *s, hop_started), + Err(e) => crate::server::hop_failed(name, None, e.why.clone(), hop_started), }; // 和 HTTP 那条路同一个规矩:没接下的不按那一家记账 let billing = match &connected { diff --git a/crates/tw-gateway/tests/routing_facts.rs b/crates/tw-gateway/tests/routing_facts.rs index 8c407184..3be83eca 100644 --- a/crates/tw-gateway/tests/routing_facts.rs +++ b/crates/tw-gateway/tests/routing_facts.rs @@ -415,3 +415,57 @@ async fn phase_two_rewrites_join_the_routed_record() { "{evs:?}" ); } + +/// 规则改写了模型名:**尝试链上记着发出去的是哪个** —— 费用按它算,价格未知时 +/// 该补的也是它。没改写的不记,发出去的就是客户端要的那个 +#[tokio::test] +async fn the_attempt_names_the_model_a_rule_rewrote_the_request_to() { + const BEDROCK: &str = "us.anthropic.claude-sonnet-4-5-20250929-v1:0"; + let up = upstream().await; + let (gw, mut events) = serve(cfg( + vec![provider("up", up)], + vec![ + rule( + "换成 Bedrock 的名字", + "{ model: claude-sonnet-* }", + None, + Some(SetAction { + model: Some(BEDROCK.into()), + ..Default::default() + }), + None, + ), + rule( + "原样", + "{ model: claude-haiku-* }", + None, + Some(SetAction { + model: Some("claude-haiku-4-5".into()), + ..Default::default() + }), + None, + ), + rule("走池子", "{}", Some("池"), None, None), + ], + )) + .await; + let attempts = |evs: &[Event]| { + evs.iter() + .find_map(|e| match e { + Event::RequestRouted { attempts, .. } => Some(attempts.clone()), + _ => None, + }) + .unwrap_or_else(|| panic!("{evs:?}")) + }; + + assert_eq!(ask(gw, &chat("claude-sonnet-4-5", "hi")).await, 200); + let evs = one_request(&mut events).await; + assert_eq!(attempts(&evs)[0].model.as_deref(), Some(BEDROCK)); + + // 改写成同一个名字等于没改写 + assert_eq!(ask(gw, &chat("claude-haiku-4-5", "hi")).await, 200); + assert_eq!(attempts(&one_request(&mut events).await)[0].model, None); + + assert_eq!(ask(gw, &chat("claude-opus-4-1", "hi")).await, 200); + assert_eq!(attempts(&one_request(&mut events).await)[0].model, None); +} diff --git a/crates/tw-observe/src/bus.rs b/crates/tw-observe/src/bus.rs index 7807cec8..78214959 100644 --- a/crates/tw-observe/src/bus.rs +++ b/crates/tw-observe/src/bus.rs @@ -423,6 +423,7 @@ mod tests { attempts: vec![ tw_api::AttemptView { provider: "p".into(), + model: None, outcome: tw_api::AttemptOutcome::Status, status: Some(503), error: None, @@ -430,6 +431,7 @@ mod tests { }, tw_api::AttemptView { provider: served_by.into(), + model: None, outcome: tw_api::AttemptOutcome::Served, status: Some(200), error: None, diff --git a/crates/tw-pricing/src/book.rs b/crates/tw-pricing/src/book.rs index 0673fd29..12bd7eb0 100644 --- a/crates/tw-pricing/src/book.rs +++ b/crates/tw-pricing/src/book.rs @@ -13,7 +13,9 @@ use std::collections::HashMap; use std::sync::Arc; -use crate::{Cost, Micros, ModelPrice, PricingConfig, SheetDef, Table, Usage, name, to_micros}; +use crate::{ + Cost, LongTier, Micros, ModelPrice, PricingConfig, SheetDef, Table, Usage, name, to_micros, +}; /// 全进程共用的那一份,可以原子地整份换掉。 pub type Shared = Arc>; @@ -220,7 +222,7 @@ impl PriceBook { } impl ModelPrice { - /// 所有单价乘上同一个倍率。上下文窗口不变。 + /// 所有单价乘上同一个倍率,长上下文那一档也乘。门槛和上下文窗口不变。 pub fn scaled(&self, m: f64) -> ModelPrice { ModelPrice { input: self.input * m, @@ -228,34 +230,72 @@ impl ModelPrice { 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), + long: self.long.as_ref().map(|t| LongTier { + above: t.above, + input: t.input * m, + output: t.output * m, + cache_read: t.cache_read.map(|v| v * m), + cache_write_5m: t.cache_write_5m.map(|v| v * m), + cache_write_1h: t.cache_write_1h.map(|v| v * m), + }), max_input_tokens: self.max_input_tokens, max_output_tokens: self.max_output_tokens, reasoning: self.reasoning, } } - /// 实际计费用的每 token 单价。`long`:这次请求落在长上下文那一档。 + /// 实际计费用的每 token 单价。`prompt`:这次请求的输入一共多少(见 + /// [`Usage::prompt`]),超过长上下文的门槛就按那一档算。 /// - /// **计费和显示都走这里**,数据集里没单独定价的档在这里按它的约定补上: - /// 缓存读写没有单独价 = 按输入价算(那是「这家不区分」,不是「免费」); - /// 1 小时写入没有 = 按 5 分钟写入算(**退回时只会低估**)。 - pub fn rates(&self, long: bool) -> Rates { - let input = match self.input_above_200k { - Some(v) if long => v, - _ => self.input, + /// **计费和显示都走这里**,价目表上没写的单价在这里按下面的规则补上。补出来 + /// 的记在 [`Rates::guessed`] 里,用到它们的费用标成估算: + /// + /// - 缓存读写一个单价都没写:按输入价算。那是「这家不区分」,不是「免费」, + /// 也不是猜的 + /// - 1 小时写入没写、5 分钟的写了:按输入价的 2 倍算。1 小时缓存只有 Claude + /// 有,这是 Anthropic 公布的倍率 —— 以前退回 5 分钟档的价,会少算三成多 + /// - 长上下文那一档没写缓存价:平档的缓存价按这一档输入价涨的比例放大。各家 + /// 的长上下文都是这么涨的(Claude、Gemini、GPT-5.x 在数据集里都是) + pub fn rates(&self, prompt: u64) -> Rates { + let tier = self.long.as_ref().filter(|t| prompt > t.above); + let (input, output) = match tier { + Some(t) => (t.input, t.output), + None => (self.input, self.output), + }; + // 平档的缓存价放大到这一档:输入价涨了多少倍就涨多少倍 + let grow = |v: f64| { + if self.input > 0.0 { + v * input / self.input + } else { + v + } }; - let output = match self.output_above_200k { - Some(v) if long => v, - _ => self.output, + // 这一档写了的就用,没写的从平档推 + let pick = |flat: Option, long: Option>| match long { + None => (flat, false), + Some(Some(v)) => (Some(v), false), + Some(None) => (flat.map(grow), flat.is_some()), }; + let (read, read_guessed) = pick(self.cache_read, tier.map(|t| t.cache_read)); + let (write_5m, write_5m_guessed) = + pick(self.cache_write_5m, tier.map(|t| t.cache_write_5m)); + let (write_1h, write_1h_guessed) = + match pick(self.cache_write_1h, tier.map(|t| t.cache_write_1h)) { + (Some(v), guessed) => (v, guessed), + (None, _) if write_5m.is_some() => (2.0 * input, true), + (None, _) => (input, false), + }; 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), + cache_read: read.unwrap_or(input), + cache_write_5m: write_5m.unwrap_or(input), + cache_write_1h: write_1h, + guessed: Guessed { + cache_read: read_guessed, + cache_write_5m: write_5m_guessed, + cache_write_1h: write_1h_guessed, + }, } } } @@ -268,6 +308,16 @@ pub struct Rates { pub cache_read: f64, pub cache_write_5m: f64, pub cache_write_1h: f64, + /// 哪几项是推出来的、不是价目表上写的。**用到了它们的费用标成估算** + pub guessed: Guessed, +} + +/// 推出来的缓存单价。输入输出价从来不推:没有它们就没有这个模型的价格。 +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct Guessed { + pub cache_read: bool, + pub cache_write_5m: bool, + pub cache_write_1h: bool, } impl Rates { @@ -278,18 +328,29 @@ impl Rates { self.cache_write_5m } } + + /// 这些用量用到了推出来的单价吗 + fn guessed_for(&self, u: &Usage) -> bool { + let g = self.guessed; + let write = if u.cache_1h { + g.cache_write_1h + } else { + g.cache_write_5m + }; + (u.cache_read > 0 && g.cache_read) || (u.cache_write > 0 && write) + } } /// 按一个单价算一次调用的成本。 pub(crate) fn cost_of(p: &ModelPrice, u: &Usage, estimated: bool) -> Cost { - // 长上下文分层:**按这次请求的输入量选档**,不是按模型的窗口。 - let r = p.rates(u.input > 200_000); + // 长上下文分层:**按这次请求的输入量选档**(连同缓存读写),不是按模型的窗口。 + let r = p.rates(u.prompt()); 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 { + if estimated || r.guessed_for(u) { Cost::Estimated(m) } else { Cost::Known(m) @@ -302,9 +363,11 @@ pub(crate) fn cost_of(p: &ModelPrice, u: &Usage, estimated: bool) -> Cost { /// 省下的(读是 0.1 倍单价),以及写入多花的(**写是 1.25 倍单价,不是 /// 免费的**)。所以它可以是负数,而负数是一条结论:这个用法上缓存在亏钱。 /// +/// 不用缓存的话这些 token 全是输入,**输入总量不变**,落在哪一档也不变。 +/// /// 没有单独的缓存价时没有节省或溢价 —— 那时它本来就按输入价算。 pub(crate) fn saving_of(p: &ModelPrice, u: &Usage) -> Micros { - let r = p.rates(u.input + u.cache_read > 200_000); + let r = p.rates(u.prompt()); 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) @@ -400,17 +463,127 @@ sheets: } #[test] - fn a_long_request_is_charged_at_the_long_context_rates_including_its_cache_reads() { - // 数据集里 Sonnet 4.5 有长上下文档、但没有单独的长上下文缓存价 + fn a_long_request_is_charged_at_the_long_context_rates_including_its_cache() { + // 数据集里 Sonnet 4.5 的长上下文档连缓存读写都有单独的价 let b = book("{}", &[]); let r = b.resolve(None, "claude-sonnet-4-5").unwrap(); - let long = r.price.rates(true); + let long = r.price.rates(200_001); 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(long.cache_read), 0.6); + assert_eq!(per_m(long.cache_write_5m), 7.5); + assert_eq!(per_m(long.cache_write_1h), 12.0); + assert_eq!(long.guessed, Guessed::default()); + // 正好 200K 还是平档:「超过」才换档 + let short = r.price.rates(200_000); + assert_eq!(per_m(short.input), 3.0); assert_eq!(per_m(short.cache_read), 0.3); } + #[test] + fn the_threshold_counts_cache_reads_and_writes_too() { + // 一个缓存暖好的长请求:没走缓存的只有几千 token,加上缓存读写过了 200K。 + // **只数没走缓存的那部分,它会被当成短请求按半价记** + let b = book("{}", &[]); + let u = Usage { + input: 5_000, + cache_read: 190_000, + cache_write: 10_000, + output: 1_000, + cache_1h: false, + }; + let Cost::Known(m) = b.cost_for("anthropic", "claude-sonnet-4-5", &u, false) else { + panic!() + }; + // 5000×6 + 190000×0.6 + 10000×7.5 + 1000×22.5,每百万 token 的美元 + assert_eq!(m, 30_000 + 114_000 + 75_000 + 22_500); + } + + #[test] + fn a_one_hour_write_without_its_own_price_is_twice_the_input_and_an_estimate() { + // Bedrock 上的 Sonnet 4 在数据集里没有 1 小时写入的价 + let b = book("{}", &[]); + let r = b + .resolve(None, "us.anthropic.claude-sonnet-4-20250514-v1:0") + .unwrap(); + assert!(!r.cross_platform, "本名就在数据集里"); + assert_eq!(r.price.cache_write_1h, None); + assert_eq!(per_m(r.price.rates(0).cache_write_1h), 6.0); + let one_hour = Usage { + input: 1_000, + cache_write: 1_000, + cache_1h: true, + ..Default::default() + }; + assert!(matches!(r.cost(&one_hour, false), Cost::Estimated(_))); + // 5 分钟的写入有价,照样是精确的 + let five_minutes = Usage { + cache_1h: false, + ..one_hour + }; + assert!(matches!(r.cost(&five_minutes, false), Cost::Known(_))); + } + + #[test] + fn a_long_tier_without_cache_prices_grows_the_flat_ones_and_says_so() { + let t = Table::fetched( + br#"{"m": {"input_cost_per_token": 1e-6, "output_cost_per_token": 4e-6, + "cache_read_input_token_cost": 1e-7, + "input_cost_per_token_above_128k_tokens": 2e-6, + "output_cost_per_token_above_128k_tokens": 6e-6}}"#, + "d".into(), + ) + .unwrap(); + let b = PriceBook::new(Arc::new(t), PricingConfig::default(), []); + let r = b.resolve(None, "m").unwrap(); + let long = r.price.rates(128_001); + assert_eq!(per_m(long.cache_read), 0.2, "输入价翻倍,缓存读也翻倍"); + assert!(long.guessed.cache_read); + // 没用到缓存读的长请求:推出来的那一项没用上,照样精确 + let u = Usage { + input: 130_000, + ..Default::default() + }; + assert!(matches!(r.cost(&u, false), Cost::Known(_))); + let u = Usage { cache_read: 1, ..u }; + assert!(matches!(r.cost(&u, false), Cost::Estimated(_))); + } + + #[test] + fn a_sheet_scales_the_long_context_tier_but_not_its_threshold() { + let b = book(SHEETS, &[("relay-hk", "中转协议价")]); + let r = b.resolve_for("relay-hk", "claude-sonnet-4-5").unwrap(); + let long = r.price.long.unwrap(); + assert_eq!(long.above, 200_000); + assert_eq!(per_m(long.input), 4.8); + assert_eq!(long.cache_read.map(per_m), Some(0.48)); + } + + #[test] + fn a_bedrock_profile_missing_from_the_table_borrows_and_is_marked_estimated() { + let b = book("{}", &[]); + // 数据集里有这个配置文件自己的键:按它的价,精确 + let r = b + .resolve(None, "us.anthropic.claude-sonnet-4-5-20250929-v1:0") + .unwrap(); + assert!(!r.cross_platform); + assert_eq!(per_m(r.price.input), 3.3, "地域配置文件比全球的贵 10%"); + // 数据集里没有 APAC 的 Sonnet 4.5:借模型本身的价,标成估算 + let r = b + .resolve(None, "apac.anthropic.claude-sonnet-4-5-20250929-v1:0") + .unwrap(); + assert!(r.cross_platform); + assert_eq!(per_m(r.price.input), 3.0); + // 应用推理配置文件的 ARN 看不出是哪个模型:查不到就说查不到 + assert!( + b.resolve( + None, + "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/a1b2c3" + ) + .is_none() + ); + } + #[test] fn the_same_request_costs_what_each_upstreams_sheet_says() { // 这是整件事的目的:按上游设的价格真的进了记账 diff --git a/crates/tw-pricing/src/lib.rs b/crates/tw-pricing/src/lib.rs index 70555cc9..d9faf92c 100644 --- a/crates/tw-pricing/src/lib.rs +++ b/crates/tw-pricing/src/lib.rs @@ -24,7 +24,7 @@ mod table; use serde::{Deserialize, Serialize}; -pub use book::{PriceBook, Rates, Resolved, Shared, Source, shared}; +pub use book::{Guessed, PriceBook, Rates, Resolved, Shared, Source, shared}; pub use sheet::{PerMillion, PricingConfig, SheetDef, SheetError}; pub use table::{SNAPSHOT_DATE, Table, TableSource, UPDATE_URL}; @@ -43,11 +43,9 @@ pub struct ModelPrice { pub cache_write_5m: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub cache_write_1h: Option, - /// 长上下文分层。超过 200k 之后单价不同 + /// 长上下文那一档。没有 = 不分档,多长的请求都按上面那组单价算 #[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, + pub long: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub max_input_tokens: Option, /// 一次最多输出多少。转换到必须写 `max_tokens` 的格式(Anthropic)、而客户端 @@ -61,7 +59,28 @@ pub struct ModelPrice { pub reasoning: bool, } +/// 长上下文那一档:一次请求的输入超过 `above` 个 token,**整个请求**改按这一档的 +/// 单价算,输出也是。 +/// +/// 门槛因模型而异(Claude Sonnet 4/4.5 是 200K,GPT-5.4 起是 272K),数据集把它写在 +/// 键名里。缓存价这一档没写的是 `None`:计费时怎么补见 [`ModelPrice::rates`]。 +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct LongTier { + pub above: u64, + pub input: f64, + pub output: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache_read: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache_write_5m: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache_write_1h: Option, +} + /// 一次调用用掉了什么。 +/// +/// `input` 是**没走缓存的**那部分:各家报的用量在进来时已经拆好,OpenAI 这类把 +/// 缓存命中算在输入里的,命中的那部分已经挪到了 `cache_read`。 #[derive(Debug, Clone, Copy, Default, PartialEq)] pub struct Usage { pub input: u64, @@ -72,6 +91,17 @@ pub struct Usage { pub cache_1h: bool, } +impl Usage { + /// 这次请求的输入一共多少:没走缓存的、从缓存读的、写进缓存的。 + /// + /// **长上下文的门槛按它判断。**缓存读写一样占上下文窗口,Anthropic 的 200K + /// 门槛数的是这三项之和 —— 只数没走缓存的那部分,一个缓存暖好的 50 万 token + /// 的请求会被当成几千 token 的短请求计价。 + pub fn prompt(&self) -> u64 { + self.input + self.cache_read + self.cache_write + } +} + /// 成本三态。 #[derive(Debug, Clone, PartialEq)] pub enum Cost { @@ -107,16 +137,16 @@ pub enum PricingError { mod snapshot_invariants { use super::*; - /// **这条测试是一条别名规则的全部依据。** + /// **这条测试是跨平台借价的全部依据。** /// - /// `name::candidates` 最后会试一次 `anthropic.<名字>-v1:0`,因为数据 - /// 集里有些模型(比如 `claude-3-5-haiku-20241022`)只有那个键。那一 - /// 步成立的前提是「Bedrock 的单价和直连一样」—— 而那不是我们能假设 - /// 的事,只能是观察到的事实。 + /// 查不到本名时,`name::cross_platform` 会在 Anthropic 的名字和 Bedrock 的 + /// id 之间互相借价,因为数据集里有些模型(比如 `claude-3-5-haiku-20241022`) + /// 只有其中一种键。借来的价能用,前提是两边的输入输出价一样 —— 而那不是 + /// 我们能假设的事,只能是观察到的事实。 /// - /// 所以这里把它变成一条覆盖整份快照的检查:**凡是两种写法都在的模 - /// 型,四个价格必须逐个相等**。哪天上游的数据不再满足它,这条会先响, - /// 而不是等用户发现账单对不上。 + /// 所以这里把它变成一条覆盖整份快照的检查:**凡是两种写法都在的模型,输入 + /// 输出价必须相等**;缓存价不一定,所以借来的价一律标成估算。哪天上游的数据 + /// 不再满足它,这条会先响,而不是等用户发现账单对不上。 #[test] fn bedrock_and_direct_prices_agree_on_the_headline_rates_but_not_on_cache() { let t = Table::builtin().unwrap(); @@ -242,11 +272,11 @@ mod cross_platform_tests { fn the_fallback_does_not_fire_for_non_anthropic_models() { // 按名字根本分不出用户走的是哪条路,而 Vertex 的价格差 25% —— // 分不出的时候就别猜。 - assert!(name::cross_platform_fallback("gpt-4o").is_none()); - assert!(name::cross_platform_fallback("gemini-2.5-pro").is_none()); + assert!(name::cross_platform("gpt-4o").is_empty()); + assert!(name::cross_platform("gemini-2.5-pro").is_empty()); assert_eq!( - name::cross_platform_fallback("claude-x"), - Some("anthropic.claude-x-v1:0".to_string()) + name::cross_platform("claude-x"), + ["anthropic.claude-x-v1:0"] ); } diff --git a/crates/tw-pricing/src/name.rs b/crates/tw-pricing/src/name.rs index 8598836e..f2978c5b 100644 --- a/crates/tw-pricing/src/name.rs +++ b/crates/tw-pricing/src/name.rs @@ -55,26 +55,93 @@ fn zai_key(bare: &str) -> Option { bare.starts_with("glm-").then(|| format!("zai/{bare}")) } -/// 跨平台的最后一招:Bedrock 的写法。 +/// 跨平台借价:本名查不到时,同一个模型在别的平台上的写法。按「越接近越靠前」排, +/// 调用方依次查表,第一个命中的算数。 /// -/// 数据集里有些模型只有 `anthropic.<名字>-v1:0` 这个键,没有裸名字 —— -/// `claude-3-5-haiku-20241022` 就是一个,而那是 Claude Code 真的会发的 -/// 模型。查不到它意味着那部分流量的成本整个是空的。 -/// -/// **但这不是等价替换。**本来以为「Bedrock 的单价和直连一样」,一条覆盖 +/// **借来的价格都不是精确的。**本来以为「Bedrock 的单价和直连一样」,一条覆盖 /// 整份快照的测试当场证伪了:`claude-3-haiku-20240307` 的输入输出价一样, -/// **缓存价差 17%**(读 3e-8 vs 2.5e-8,写 3e-7 vs 3.125e-7)。 +/// **缓存价差 17%**(读 3e-8 vs 2.5e-8,写 3e-7 vs 3.125e-7);Claude 4.5 起 +/// Bedrock 的地域推理配置文件(`us.`、`eu.`……)还比全球的贵 10%。 +/// +/// 所以它和 [`candidates`] 分开、单独返回:用它算出来的成本一律标成**估算** +/// (估算值必须在界面上明确标记)。给一个带波浪号的数字,比给一个空白有用; +/// 而假装它精确,就是那种「看起来很确定的错数字」。 +/// +/// 三种借法,都只对能证明是同一个模型的写法: +/// +/// 1. Bedrock 推理配置文件 → 它以之命名的那个模型 id:`us.anthropic.claude-…` → +/// `anthropic.claude-…` +/// 2. Bedrock 上 Anthropic 模型的 id → Anthropic 自己的名字: +/// `anthropic.claude-sonnet-4-5-20250929-v1:0` → `claude-sonnet-4-5-20250929` +/// 3. Anthropic 的名字 → Bedrock 的 id。数据集里有些模型只有 Bedrock 的键 —— +/// `claude-3-5-haiku-20241022` 就是一个,而那是 Claude Code 真的会发的模型 +/// +/// 只对 Anthropic 的模型做 2 和 3。Vertex 的价格差得更多(`vertex_ai/claude-3-5-haiku` +/// 比 Bedrock 贵 25%),别家的模型在 Bedrock 上和直连的名字也对不上 —— 分不出的 +/// 时候就别猜。 +pub fn cross_platform(model: &str) -> Vec { + let mut out = Vec::new(); + // ARN 的最后一段就是模型 id 或推理配置文件 id + let Some(bare) = model.trim().rsplit('/').next().filter(|b| !b.is_empty()) else { + return out; + }; + let mut push = |s: String| { + if !out.contains(&s) { + out.push(s); + } + }; + let id = strip_geo(bare); + if let Some(id) = id { + push(id.to_string()); + } + if let Some(direct) = anthropic_on_bedrock(id.unwrap_or(bare)) { + for c in candidates(direct) { + push(c); + } + } + if bare.starts_with("claude-") { + push(format!("anthropic.{bare}-v1:0")); + } + out +} + +/// Bedrock 跨区域推理配置文件的地域前缀。配置文件以它支持的模型命名,前面加 +/// 一段地域:`us.anthropic.claude-…` 就是 `anthropic.claude-…` 在美国几个区域 +/// 之间调度。 /// -/// 所以它单独成一个函数、单独返回:用它算出来的成本一律标成**估算** -/// (估算值必须在界面上明确标记)。给一个带波浪号的数字,比给一个 -/// 空白有用;而假装它精确,就是那种「看起来很确定的错数字」。 -pub fn cross_platform_fallback(model: &str) -> Option { - let bare = model.trim().rsplit('/').next()?; - // 只对 Anthropic 的模型。Vertex 的价格差得更多 - // (`vertex_ai/claude-3-5-haiku` 比 Bedrock 贵 25%),而按名字根本 - // 分不出用户走的是哪条路 —— 分不出的时候就别猜。 - bare.starts_with("claude-") - .then(|| format!("anthropic.{bare}-v1:0")) +/// **只认这几个**,取自价格数据集里 Bedrock 的键。认不出的前缀不剥 —— 查不到价 +/// 就说查不到。 +const BEDROCK_GEOS: &[&str] = &["us", "eu", "apac", "jp", "au", "us-gov", "global"]; + +/// 剥掉推理配置文件的地域前缀,剩下的是模型 id。不是配置文件的 `None`。 +fn strip_geo(id: &str) -> Option<&str> { + let (geo, rest) = id.split_once('.')?; + // 剩下的得还是一个 `厂商.模型` 的 id:`us.x` 这种不是 + (BEDROCK_GEOS.contains(&geo) && rest.contains('.')).then_some(rest) +} + +/// Bedrock 上 Anthropic 模型的 id 去掉厂商和版本,剩下 Anthropic 自己的名字。 +/// +/// 版本后缀有三种写法:`-v1:0`、`-v1`(`claude-opus-4-6-v1`)、没有(`claude-opus-4-7`)。 +fn anthropic_on_bedrock(id: &str) -> Option<&str> { + let name = id.strip_prefix("anthropic.")?; + if !name.starts_with("claude-") { + return None; + } + // `rfind` 落在 ASCII 的 `-` 上,是字符边界;版本号只认 ASCII 数字和冒号 + let Some(i) = name.rfind("-v") else { + return Some(name); + }; + let (major, minor) = match name[i + 2..].split_once(':') { + Some((a, b)) => (a, Some(b)), + None => (&name[i + 2..], None), + }; + let digits = |s: &str| !s.is_empty() && s.bytes().all(|c| c.is_ascii_digit()); + if digits(major) && minor.is_none_or(digits) { + Some(&name[..i]) + } else { + Some(name) + } } /// 结尾是不是一个日期版本号,是就剥掉。 @@ -187,6 +254,66 @@ mod tests { fn an_empty_or_whitespace_model_yields_nothing() { assert!(candidates("").is_empty()); assert!(candidates(" ").is_empty()); + assert!(cross_platform("").is_empty()); + assert!(cross_platform("arn:aws:bedrock:us-east-1:1:inference-profile/").is_empty()); + } + + #[test] + fn an_inference_profile_borrows_from_its_model_then_from_anthropic() { + assert_eq!( + cross_platform("us.anthropic.claude-sonnet-4-5-20250929-v1:0"), + [ + "anthropic.claude-sonnet-4-5-20250929-v1:0", + "claude-sonnet-4-5-20250929", + "claude-sonnet-4-5", + ] + ); + // 系统定义的配置文件的 ARN:最后一段就是它的 id + assert_eq!( + cross_platform( + "arn:aws:bedrock:us-east-1:123456789012:inference-profile/global.anthropic.claude-opus-4-6-v1" + )[..2], + ["anthropic.claude-opus-4-6-v1", "claude-opus-4-6"] + ); + } + + #[test] + fn every_way_bedrock_writes_a_version_comes_off() { + for (id, name) in [ + ( + "anthropic.claude-sonnet-4-5-20250929-v1:0", + "claude-sonnet-4-5-20250929", + ), + ( + "anthropic.claude-3-5-sonnet-20241022-v2:0", + "claude-3-5-sonnet-20241022", + ), + ("anthropic.claude-opus-4-6-v1", "claude-opus-4-6"), + ("anthropic.claude-opus-4-7", "claude-opus-4-7"), + ] { + assert_eq!(cross_platform(id)[0], name, "{id}"); + } + } + + #[test] + fn only_known_geographies_and_only_anthropic_models_are_translated() { + // 认不出的前缀不剥 + assert!(cross_platform("xx.anthropic.claude-opus-4-7").is_empty()); + // 别家的模型:剥得掉地域,但不换成直连的名字 + assert_eq!( + cross_platform("us.amazon.nova-pro-v1:0"), + ["amazon.nova-pro-v1:0"] + ); + assert!(cross_platform("amazon.nova-pro-v1:0").is_empty()); + assert!(cross_platform("gpt-4o").is_empty()); + assert!(cross_platform("gemini-2.5-pro").is_empty()); + // 厂商不是地域:`anthropic.` 不剥成别的 id,只换成直连的名字 + assert_eq!( + cross_platform("anthropic.claude-opus-4-7"), + ["claude-opus-4-7"] + ); + // 直连的名字 → Bedrock 的键 + assert_eq!(cross_platform("claude-x"), ["anthropic.claude-x-v1:0"]); } } @@ -212,6 +339,10 @@ mod multibyte_tests { let c = candidates(m); assert!(!c.is_empty(), "{m}"); assert_eq!(c[0], m); + // 跨平台借价也会被每个查不到价的模型名调到 + cross_platform(m); + cross_platform(&format!("us.anthropic.{m}-v中")); + cross_platform(&format!("anthropic.claude-{m}-v1:中")); } } diff --git a/crates/tw-pricing/src/sheet.rs b/crates/tw-pricing/src/sheet.rs index 30dcb11e..8e349728 100644 --- a/crates/tw-pricing/src/sheet.rs +++ b/crates/tw-pricing/src/sheet.rs @@ -33,7 +33,7 @@ use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; use tw_types::{Msg, msg}; -use crate::ModelPrice; +use crate::{LongTier, ModelPrice}; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -94,7 +94,7 @@ pub struct PerMillion { pub cache_read: f64, pub cache_write_5m: f64, pub cache_write_1h: f64, - /// 单次请求输入超过 200K tokens 之后的单价 + /// 单次请求的输入(连同缓存读写)超过 200K tokens 之后的单价 #[serde(default, skip_serializing_if = "Option::is_none")] pub input_above_200k: Option, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -264,8 +264,19 @@ impl PerMillion { 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), + long: self + .input_above_200k + .zip(self.output_above_200k) + .map(|(input, output)| LongTier { + above: 200_000, + input: input * M, + output: 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), + }), max_input_tokens: base.and_then(|b| b.max_input_tokens), max_output_tokens: base.and_then(|b| b.max_output_tokens), // 覆盖价只改单价:模型会不会推理不是价格的一部分 @@ -277,20 +288,24 @@ impl PerMillion { /// /// 数据集里没单独定价的缓存档按计费时的同一套规则补上(见 /// [`ModelPrice::rates`])—— 显示出来的数字和记账用的必须是同一个。 + /// + /// 长上下文只给 200K 那一档:这两个字段说的就是 200K。门槛是别的数的(GPT-5.4 + /// 起是 272K)照样按它计费,只是不在这里显示 —— 显示成 200K 就是错的。 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); + let rates = p.rates(0); + let long = p.long.as_ref().filter(|t| t.above == 200_000); 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), + input_above_200k: long.map(|t| r(t.input)), + output_above_200k: long.map(|t| r(t.output)), } } } @@ -386,10 +401,46 @@ mod tests { 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.long, None); assert_eq!(p.max_input_tokens, Some(200_000)); } + #[test] + fn an_override_with_a_long_tier_charges_its_cache_as_written() { + let p = PerMillion { + input: 3.0, + output: 15.0, + cache_read: 0.3, + cache_write_5m: 3.75, + cache_write_1h: 6.0, + input_above_200k: Some(6.0), + output_above_200k: Some(22.5), + } + .to_price(None); + let long = p.rates(300_000); + let per_m = |v: f64| (v * 1e6 * 1e6).round() / 1e6; + assert_eq!(per_m(long.input), 6.0); + // 写的是 0.3 就是 0.3:覆盖价不按比例推 + assert_eq!(per_m(long.cache_read), 0.3); + assert_eq!(long.guessed, crate::Guessed::default()); + } + + #[test] + fn a_tier_that_is_not_200k_is_not_shown_as_200k() { + let p = ModelPrice { + input: 5e-6, + output: 3e-5, + long: Some(LongTier { + above: 272_000, + input: 1e-5, + output: 4.5e-5, + ..Default::default() + }), + ..Default::default() + }; + assert_eq!(PerMillion::of(&p).input_above_200k, None); + } + #[test] fn the_displayed_rates_are_the_rates_that_get_charged() { // 数据集里没单独定价的缓存档:按输入价计费,也就按输入价显示 @@ -402,8 +453,8 @@ mod tests { 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); + // 1 小时档没有:按输入价的 2 倍(Anthropic 公布的倍率) + assert_eq!(v.cache_write_1h, 2.0); // 显示的和写回去的是同一组数:换算一个来回不变 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 index f85532e5..cb8f2e98 100644 --- a/crates/tw-pricing/src/table.rs +++ b/crates/tw-pricing/src/table.rs @@ -4,7 +4,7 @@ use std::collections::HashMap; -use crate::{ModelPrice, PricingError, name}; +use crate::{LongTier, ModelPrice, PricingError, name}; /// 内置快照。**pin 在一个具体的 commit 上**,来历见 `data/PROVENANCE.md`。 const SNAPSHOT: &[u8] = include_bytes!("../data/model_prices.json.gz"); @@ -97,9 +97,11 @@ impl Table { return Some((p, false)); } } - // 跨平台的最后一招。**它不精确**,见 name::cross_platform_fallback - let c = name::cross_platform_fallback(model)?; - self.prices.get(&c).map(|p| (p, true)) + // 跨平台借价。**它不精确**,见 name::cross_platform + name::cross_platform(model) + .iter() + .find_map(|c| self.prices.get(c)) + .map(|p| (p, true)) } pub fn get(&self, model: &str) -> Option<&ModelPrice> { @@ -171,8 +173,7 @@ fn price_from(v: &serde_json::Value) -> Option { 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"), + long: long_tier(v, output), max_input_tokens: v.get("max_input_tokens").and_then(|x| x.as_u64()), max_output_tokens: v.get("max_output_tokens").and_then(|x| x.as_u64()), reasoning: v @@ -182,6 +183,36 @@ fn price_from(v: &serde_json::Value) -> Option { }) } +/// 长上下文那一档。数据集把门槛写在键名里:`input_cost_per_token_above_200k_tokens`、 +/// `…_above_272k_tokens`。 +/// +/// **有输入单价才算有这一档**;输出没单独写的按平档的算。数据集里一个模型最多 +/// 一档,真有两档的话取门槛低的那一档 —— 多出来的那档不认,比认错了强。服务等级 +/// 的变体(`…_priority`、`…_flex`)不是这一档,不认。 +fn long_tier(v: &serde_json::Value, output: f64) -> Option { + let obj = v.as_object()?; + let k = obj + .keys() + .filter_map(|key| { + key.strip_prefix("input_cost_per_token_above_")? + .strip_suffix("k_tokens")? + .parse::() + .ok() + }) + .min()?; + let f = |key: String| obj.get(&key).and_then(|x| x.as_f64()); + Some(LongTier { + above: k * 1000, + input: f(format!("input_cost_per_token_above_{k}k_tokens"))?, + output: f(format!("output_cost_per_token_above_{k}k_tokens")).unwrap_or(output), + cache_read: f(format!("cache_read_input_token_cost_above_{k}k_tokens")), + cache_write_5m: f(format!("cache_creation_input_token_cost_above_{k}k_tokens")), + cache_write_1h: f(format!( + "cache_creation_input_token_cost_above_1hr_above_{k}k_tokens" + )), + }) +} + #[cfg(test)] mod tests { use super::*; @@ -237,4 +268,44 @@ mod tests { assert_eq!(new.changed_from(&old), 3); assert_eq!(new.changed_from(&new), 0); } + + #[test] + fn the_long_context_tier_is_read_with_its_threshold_and_cache_prices() { + let t = Table::builtin().unwrap(); + let per_m = |v: f64| (v * 1e6 * 1e6).round() / 1e6; + // Claude Sonnet 4.5:200K 一档,缓存读写也有这一档的价 + let long = t + .exact("claude-sonnet-4-5-20250929") + .and_then(|p| p.long.clone()) + .unwrap(); + assert_eq!(long.above, 200_000); + assert_eq!((per_m(long.input), per_m(long.output)), (6.0, 22.5)); + assert_eq!(long.cache_read.map(per_m), Some(0.6)); + assert_eq!(long.cache_write_5m.map(per_m), Some(7.5)); + assert_eq!(long.cache_write_1h.map(per_m), Some(12.0)); + // GPT-5.5:门槛是 272K,不是 200K + let long = t.exact("gpt-5.5").and_then(|p| p.long.clone()).unwrap(); + assert_eq!(long.above, 272_000); + assert_eq!(per_m(long.input), 10.0); + // 服务等级的变体不是长上下文那一档 + assert!(t.exact("gpt-4o").unwrap().long.is_none()); + } + + #[test] + fn a_tier_without_an_input_price_is_no_tier_and_a_missing_output_price_stays_flat() { + let t = Table::fetched( + br#"{ + "a": {"input_cost_per_token": 1e-6, "output_cost_per_token": 2e-6, + "output_cost_per_token_above_200k_tokens": 4e-6}, + "b": {"input_cost_per_token": 1e-6, "output_cost_per_token": 2e-6, + "input_cost_per_token_above_128k_tokens": 2e-6, + "input_cost_per_token_above_128k_tokens_priority": 9e-6} + }"#, + "d".into(), + ) + .unwrap(); + assert!(t.exact("a").unwrap().long.is_none()); + let b = t.exact("b").unwrap().long.clone().unwrap(); + assert_eq!((b.above, b.input, b.output), (128_000, 2e-6, 2e-6)); + } } diff --git a/crates/tw-store/src/db.rs b/crates/tw-store/src/db.rs index 375992e2..aee39a15 100644 --- a/crates/tw-store/src/db.rs +++ b/crates/tw-store/src/db.rs @@ -35,6 +35,10 @@ const SCHEMA: i64 = 22; const NO_PRICE: &str = "(cost_micros IS NULL AND input_tokens IS NOT NULL \ AND billing = 'per-token')"; +/// 这一行按哪个模型名查的价:改写过的是发给上游的那个,没改写的是客户端要的那个 +/// (见 `tw_store::recorder` 里的算钱那一段) +const PRICED_AS: &str = "COALESCE(json_extract(routing, '$.attempts[#-1].model'), model)"; + /// 这一行算不出钱,**因为没有拿到用量**:上游没报,或者连接在它报之前就 /// 结束了(客户端取消、WebSocket 会话)。配价格解决不了它,而它多半花了钱, /// 合计里缺着它 —— 所以要单独数出来,不能混进「没有价格」,也不能不数。 @@ -599,10 +603,15 @@ impl Db { |r| r.get(0), )?; // **按 (上游, 模型) 分。**同一个模型在不同上游按不同的价目表计价, - // 该在哪张表里补价格取决于它走的是哪家 + // 该在哪张表里补价格取决于它走的是哪家。 + // + // **模型是查价用的那个名字**:规则改写过的,是发给上游的那个(记在尝试链 + // 最后一跳上,见 `tw_api::AttemptView::model`)—— 该补价格的是它,照着 + // 客户端要的名字补,补了也还是算不出钱 let mut st = self.conn.prepare(&format!( - "SELECT provider, model, COUNT(*) AS n FROM requests WHERE {filter} \ - GROUP BY provider, model ORDER BY n DESC, provider, model LIMIT 20" + "SELECT provider, {PRICED_AS} AS priced_as, COUNT(*) AS n FROM requests \ + WHERE {filter} GROUP BY provider, priced_as \ + ORDER BY n DESC, provider, priced_as LIMIT 20" ))?; let rows = st.query_map([since], |r| { Ok(tw_api::UnpricedModel { @@ -2377,6 +2386,42 @@ mod cost_state_tests { ); } + /// 改写过模型名的请求按发出去的那个名字查价,**列出来的也得是那个名字** —— + /// 照着客户端要的名字补价格,那几行照样算不出钱 + #[test] + fn the_pricing_page_names_the_model_that_was_sent() { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis() as i64; + let db = Db::in_memory().unwrap(); + let arn = "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/a1b2c3"; + let mut r = unknown_model(1, now); + r.model = "claude-sonnet-4-5".into(); + r.routing = Some( + serde_json::to_string(&tw_api::RoutingView { + attempts: vec![tw_api::AttemptView { + provider: "官方".into(), + model: Some(arn.into()), + outcome: tw_api::AttemptOutcome::Served, + status: Some(200), + error: None, + ms: 1, + }], + ..Default::default() + }) + .unwrap(), + ); + db.insert(&r).unwrap(); + // 没改写的照旧是客户端要的名字 + db.insert(&unknown_model(2, now)).unwrap(); + let (n, models) = db.unpriced_recent(7).unwrap(); + assert_eq!(n, 2); + let mut names: Vec<_> = models.into_iter().map(|m| m.model).collect(); + names.sort(); + assert_eq!(names, [arn, "中转站自己起的名字"]); + } + /// 列表有上限,总数没有。 #[test] fn the_unpriced_total_counts_every_request_not_just_the_listed_models() { diff --git a/crates/tw-store/src/recorder.rs b/crates/tw-store/src/recorder.rs index 23022bff..8e1b4ff9 100644 --- a/crates/tw-store/src/recorder.rs +++ b/crates/tw-store/src/recorder.rs @@ -637,11 +637,19 @@ impl Recorder { // 占位。按它算出来的钱只会偏低,当成实测会让「今日花费」悄悄少一截。 let partial = !matches!(how, Ending::Finished { .. }); let book = self.pricing.load(); - // **按这个请求实际走的上游查价** —— 同一个模型在不同上游不是同一个价 + // **按这个请求实际走的上游查价** —— 同一个模型在不同上游不是同一个价。 + // **按发给它的那个模型名查**:规则把请求改写成另一个模型发出去的,上游 + // 按那个模型收钱。改写记在服务它的那一跳上(尝试链的最后一跳,见路由事件) + let priced_as = p + .routing + .attempts + .last() + .and_then(|a| a.model.as_deref()) + .unwrap_or(&p.model); let resolved = if free { None } else { - book.resolve_for(&p.provider, &p.model) + book.resolve_for(&p.provider, priced_as) }; let cost = match (&u, &resolved) { _ if free => Some(Cost::Known(0)), @@ -818,6 +826,7 @@ mod tests { attempts: vec![ tw_api::AttemptView { provider: "官方".into(), + model: None, outcome: tw_api::AttemptOutcome::Error, status: None, error: Some(tw_api::Msg { @@ -829,6 +838,7 @@ mod tests { }, tw_api::AttemptView { provider: "中转".into(), + model: None, outcome: tw_api::AttemptOutcome::Served, status: Some(200), error: None, @@ -871,6 +881,7 @@ mod tests { denied_by: None, attempts: vec![tw_api::AttemptView { provider: "官方".into(), + model: None, outcome: tw_api::AttemptOutcome::Served, status: Some(200), error: None, @@ -882,6 +893,54 @@ mod tests { assert_eq!(r.db().get(2).unwrap().unwrap().provider, "官方"); } + /// 规则把请求改写成另一个模型发出去:**上游按发出去的那个收钱**,这一行的 + /// 模型仍是客户端要的那个(按模型的统计看的是客户端要了什么) + #[test] + fn a_rewritten_request_is_priced_as_the_model_that_was_sent() { + let (_d, mut r) = rec(); + r.on_event(&started(3, "claude-opus-4-20250514")); + r.on_event(&Event::RequestRouted { + id: 3, + route: "default".into(), + rule: "默认".into(), + group: None, + rewritten_by: vec!["换成 Haiku".into()], + denied_by: None, + attempts: vec![ + tw_api::AttemptView { + provider: "官方".into(), + model: Some("claude-sonnet-4-5".into()), + outcome: tw_api::AttemptOutcome::Status, + status: Some(529), + error: None, + ms: 100, + }, + tw_api::AttemptView { + provider: "中转".into(), + model: Some("claude-haiku-4-5".into()), + outcome: tw_api::AttemptOutcome::Served, + status: Some(200), + error: None, + ms: 300, + }, + ], + billing: tw_api::Billing::PerToken, + }); + r.on_event(&finished( + 3, + Some(tw_api::UsageView { + input: 1000, + ..Default::default() + }), + )); + let row = r.db().get(3).unwrap().unwrap(); + assert_eq!(row.model, "claude-opus-4-20250514"); + // Haiku 4.5 的输入 $1/百万:一千 token 是 $0.001。按客户端要的 Opus 4 算是 + // $0.015,按第一跳改写成的 Sonnet 4.5 算是 $0.003 + assert_eq!(row.cost_micros, Some(1_000)); + assert!(!row.cost_estimated); + } + /// **会话由网关在开始时定,这里照记**:落库的和开始事件里说的是同一个值, /// 不在这一层再算一遍(以前在这里按指纹和时间现算,于是在跑的那一轮说不出 /// 自己属于哪次会话) @@ -928,6 +987,7 @@ mod tests { denied_by: Some("中转不收密钥".into()), attempts: vec![tw_api::AttemptView { provider: "中转".into(), + model: None, outcome: tw_api::AttemptOutcome::Error, status: None, error: None, @@ -1271,6 +1331,7 @@ mod billing_tests { denied_by: None, attempts: vec![tw_api::AttemptView { provider: "订阅账号".into(), + model: None, outcome: tw_api::AttemptOutcome::Served, status: Some(200), error: None, @@ -1355,6 +1416,7 @@ mod billing_tests { denied_by: None, attempts: vec![tw_api::AttemptView { provider: "订阅账号".into(), + model: None, outcome: tw_api::AttemptOutcome::Served, status: Some(101), error: None, @@ -1732,6 +1794,7 @@ mod translation_tests { .iter() .map(|p| tw_api::AttemptView { provider: p.to_string(), + model: None, outcome: tw_api::AttemptOutcome::Served, status: Some(200), error: None, diff --git a/docs/config.md b/docs/config.md index 5078d92c..cbab399b 100644 --- a/docs/config.md +++ b/docs/config.md @@ -523,8 +523,8 @@ pages. Every field is written out; nothing is inferred when pricing. | `cache_read` | number | **required** | US dollars per million tokens read from the prompt cache. | | `cache_write_5m` | number | **required** | US dollars per million tokens written to a 5-minute cache. | | `cache_write_1h` | number | **required** | US dollars per million tokens written to a 1-hour cache. | -| `input_above_200k` | number | — | Input price once a request's input exceeds 200K tokens. Written together with `output_above_200k`, or neither. | -| `output_above_200k` | number | — | Output price once a request's input exceeds 200K tokens. | +| `input_above_200k` | number | — | Input price once a request's input, cache reads and writes included, exceeds 200K tokens. Written together with `output_above_200k`, or neither. Cache prices stay the ones above. | +| `output_above_200k` | number | — | Output price once a request's input, cache reads and writes included, exceeds 200K tokens. | ```yaml diff --git a/docs/config.zh-CN.md b/docs/config.zh-CN.md index ca05423b..553b8e29 100644 --- a/docs/config.zh-CN.md +++ b/docs/config.zh-CN.md @@ -411,8 +411,8 @@ proxies: | `cache_read` | 数字 | **必填** | 每百万缓存读取 token 的美元价格。 | | `cache_write_5m` | 数字 | **必填** | 每百万写入 5 分钟缓存 token 的美元价格。 | | `cache_write_1h` | 数字 | **必填** | 每百万写入 1 小时缓存 token 的美元价格。 | -| `input_above_200k` | 数字 | — | 单次请求输入超过 200K token 后的输入单价。与 `output_above_200k` 同时写或都不写。 | -| `output_above_200k` | 数字 | — | 单次请求输入超过 200K token 后的输出单价。 | +| `input_above_200k` | 数字 | — | 单次请求的输入(连同缓存读写)超过 200K token 后的输入单价。与 `output_above_200k` 同时写或都不写;缓存单价仍按上面写的算。 | +| `output_above_200k` | 数字 | — | 单次请求的输入(连同缓存读写)超过 200K token 后的输出单价。 | ```yaml