Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 20 additions & 33 deletions crates/tw-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,12 @@ pub use tw_types::Msg;
/// `overloaded`)。放行网段不再有「空 = 私网段」:不写是默认名单、空就是
/// 只有本机,`ListenView` 带上了默认名单;`GET /interfaces` 每张网卡一行。
/// 照 8 写的界面会画出一节改了也不起作用的并发设置。
pub const CONTROL_API_VERSION: u32 = 9;
///
/// **10 计费只剩两档**:`billing` 只有 `per-token` / `free`,订阅账号也按
/// 价目表算费用。上游视图的 `billing` 必有,`billing_effective` 没了;汇总的
/// `subscription_requests` / `subscription_tokens` 和会话的 `subscription_turns`
/// 没了。照 9 写的界面会去读已经不存在的字段。
pub const CONTROL_API_VERSION: u32 = 10;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Status {
Expand Down Expand Up @@ -226,8 +231,7 @@ pub enum Event {
/// **必须跟着这次请求走,不能事后查配置** —— 配置随时会被热重载,
/// 而一条三天前的记录该按它当时那家的计费方式算。
///
/// 一家都没接下时是 `per-token`:那一行没有用量、没有金额,记成订阅
/// 的话会被数进订阅额度的次数里。
/// 一家都没接下时是 `per-token`:没有哪一家的计费方式可以跟着走。
billing: String,
},
/// 一个请求发出前,按出站脱敏的规则找到了东西。
Expand Down Expand Up @@ -823,12 +827,8 @@ pub struct ProviderView {
/// 上游永远不会熔断。和 `AuthChanged` 说的是同一件事:一个是现状,一个是变化
#[serde(default, skip_serializing_if = "Option::is_none")]
pub auth_rejected: Option<u16>,
/// 配置里写明的计费方式:`per-token` / `subscription` / `free` / `unknown`。
/// 空 = 自动识别
pub billing: Option<String>,
/// 实际按什么计费。没写明时自动识别:报过订阅额度的是 `subscription`,
/// 否则 `per-token`
pub billing_effective: String,
/// 计费方式:`per-token`(按价目表算,订阅账号也是)/ `free`(记 $0)
pub billing: String,
/// 谁在引用它。**删之前要知道**,改名时它们会跟着改
pub references: Vec<ReferenceView>,
/// 选的价目表。空 = 默认价目表
Expand Down Expand Up @@ -1527,7 +1527,7 @@ pub struct ProviderInput {
/// 启用范围:只用这些模型(ID 或 glob)。不给就是它提供的全部
#[serde(default, skip_serializing_if = "Option::is_none")]
pub models_only: Option<Vec<String>>,
/// `per-token` / `subscription` / `free` / `unknown`。不给就自动识别
/// `per-token` / `free`。不给就是按量计费
#[serde(default, skip_serializing_if = "Option::is_none")]
pub billing: Option<String>,
/// 按哪张价目表计价。不给就是默认价目表
Expand Down Expand Up @@ -1922,7 +1922,7 @@ pub struct Summary {
/// 有多少条请求**价目表里没有它的模型**:用量是有的,缺的是单价。
/// **不是 0,是「不知道」。**给那个模型配一个价格就能解决。
///
/// 失败的、没有用量的、订阅制的都不在这里 —— 配价格对它们没用。
/// 失败的、没有用量的、不计费的都不在这里 —— 配价格对它们没用。
pub unpriced_requests: i64,
/// 有多少条请求**没有拿到用量**,所以同样算不出钱:上游没报,或者连接
/// 在它报之前就结束了(客户端取消、WebSocket 会话)。
Expand All @@ -1931,11 +1931,6 @@ pub struct Summary {
/// 界面上是两句不同的话。上游确实接下了的才算:成功的响应和客户端
/// 取消的,失败的和上游回了 4xx 的不算。
pub no_usage_requests: i64,
/// 走订阅型上游的请求数。**不参与金额合计** ——
/// 订阅制的边际成本是零,按价目表算出来的数字是纯虚构的
pub subscription_requests: i64,
/// 那些请求用掉的 token。**它才是订阅用户该看的量**
pub subscription_tokens: i64,
/// 用了缓存之后净省下多少微分。
///
/// **净额:命中节省的部分,减去写入产生的溢价。**用户想知道的是
Expand Down Expand Up @@ -1986,8 +1981,8 @@ pub struct HistoryRow {
/// 客户端没等到响应结束就走了。**不是失败**(`error` 是空的);用量
/// 只算到断开那一刻,所以有金额的话一定是估算
pub cancelled: bool,
/// 服务它的那家怎么收钱:`per-token` / `subscription` / `free` / `unknown`。
/// 本地应答的是 `free`:网关自己答的,费用确实是零
/// 服务它的那家怎么收钱:`per-token` / `free`。本地应答的是 `free`:网关
/// 自己答的,费用确实是零
pub billing: String,
/// 缓存命中省下了多少微分。`None` = 算不出来
#[serde(default, skip_serializing_if = "Option::is_none")]
Expand Down Expand Up @@ -2204,12 +2199,10 @@ pub struct SpeedEstimate {
/// 输入 token。**精确值** —— 请求是固定的
pub input_tokens: u64,
pub max_output_tokens: u64,
/// 微分。按量计费算得出来时是那个数,不计费时是 0。订阅制、计费方式
/// 未知、无法计价时是空
/// 微分。按量计费算得出来时是那个数,不计费时是 0,无法计价时是空
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cost_micros: Option<i64>,
/// 这家的计费方式:`per-token` / `subscription` / `free` / `unknown`。
/// **订阅制那几项没有金额,但不让合计变成空**
/// 这家的计费方式:`per-token` / `free`
pub billing: String,
/// 这家服务不了这个模型:`out_of_scope`(不在启用范围里)/
/// `not_offered`(模型清单里没有)。有值时不进合计,也不会被测
Expand All @@ -2221,9 +2214,8 @@ pub struct SpeedEstimate {
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpeedQuote {
pub items: Vec<SpeedEstimate>,
/// 总计,**不含订阅制那几项**(它们消耗额度,单独说)。按量计费的
/// 有一项算不出来就是 None —— 给一个看起来完整的数字,用户会以为
/// 那就是全部代价
/// 总计。有一项算不出来就是 None —— 给一个看起来完整的数字,用户会
/// 以为那就是全部代价
#[serde(default, skip_serializing_if = "Option::is_none")]
pub total_micros: Option<i64>,
pub pricing_date: String,
Expand Down Expand Up @@ -2299,10 +2291,6 @@ pub struct SessionView {
pub unpriced_turns: u64,
/// 没有拿到用量、所以算不出钱的轮数
pub no_usage_turns: u64,
/// 由订阅制上游服务的轮数:计入订阅额度,**没有金额,也不是「无法计价」**。
/// 和上面三个数互不相交,和概览的 `subscription_requests` 数的是同一类请求。
/// 少了它,全走订阅的会话和一轮都算不出钱的会话在这里长得一模一样
pub subscription_turns: u64,
pub input_tokens: i64,
pub output_tokens: i64,
pub cache_read_tokens: i64,
Expand Down Expand Up @@ -2335,8 +2323,7 @@ pub struct TurnView {
/// 估算的金额在瀑布图上和实测的长得一模一样
pub cost_estimated: bool,
/// 服务它的那家怎么收钱,和 `HistoryRow::billing` 同一套词:`per-token` /
/// `subscription` / `free` / `unknown`。**订阅制那一轮的 `cost_micros` 也是
/// None**,只看金额分不出它和「无法计价」
/// `free`
pub billing: String,
}

Expand All @@ -2362,9 +2349,9 @@ pub struct ReplayQuote {
pub provider: String,
pub body_bytes: i64,
pub input_tokens: i64,
/// `None` = 订阅制、计费方式未知,或者这个模型无法计价。**不是 0**
/// `None` = 这个模型无法计价。**不是 0**
pub cost_micros: Option<i64>,
/// 要重放到的那家的计费方式:`per-token` / `subscription` / `free` / `unknown`
/// 要重放到的那家的计费方式:`per-token` / `free`
pub billing: String,
/// 发出去之前会不会脱敏。用户有权在按下去之前知道
pub will_redact: bool,
Expand Down
2 changes: 1 addition & 1 deletion crates/tw-config/src/edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@ providers:
CFG,
PROVIDERS,
Some("官方"),
&map("name: 官方\nbase_url: https://api.anthropic.com\nkey: sk-a\nbilling: subscription\n"),
&map("name: 官方\nbase_url: https://api.anthropic.com\nkey: sk-a\nbilling: free\n"),
)
.unwrap();
let without = upsert(
Expand Down
60 changes: 38 additions & 22 deletions crates/tw-config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ impl Default for Provider {
on_proxy_fail: OnProxyFail::default(),
models: Vec::new(),
models_only: None,
billing: None,
billing: Billing::PerToken,
pricing: None,
disabled: false,
}
Expand Down Expand Up @@ -608,12 +608,13 @@ pub struct Provider {
/// 它们的请求交给这家。
#[serde(default, skip_serializing_if = "Option::is_none")]
pub models_only: Option<Vec<String>>,
/// 这家怎么收钱。
/// 这家怎么收钱:按量计费(默认,按价目表算)或不计费。
///
/// **不写就自动判**:响应头里报过订阅额度的就是订阅型。
/// 那个信号一直在我们手上,不该变成一个用户要填的字段。
#[serde(default, skip_serializing_if = "Option::is_none")]
pub billing: Option<Billing>,
/// **订阅账号也按量计费。**费用一律是「用量 × 这家所选价目表里该模型的
/// 单价」,订阅账号算出来的就是按 API 价格折算的费用;额度另从响应头读,
/// 和计费无关。想让它的费用记 0,写 `free`。
#[serde(default, skip_serializing_if = "is_default")]
pub billing: Billing,
/// 按哪张价目表计价。不写就是默认价目表。
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pricing: Option<String>,
Expand All @@ -638,42 +639,29 @@ impl Provider {

/// 上游怎么收钱。
///
/// **接入订阅型网关之后,「按价目表乘 token 数」这个假设就不成立了** ——
/// 订阅制的边际成本是零,按 API 价目表算出来的数字是纯虚构的。
/// **只有两档。**费用只取决于用量和价目表:按量计费的按价目表算,不计费的
/// 记 $0。上游是不是订阅账号不影响费用 —— 那件事由它报的额度说。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Billing {
/// 按价目表计价。默认
#[default]
PerToken,
/// 订阅制,边际成本为零。
///
/// **成本栏显示「订阅」而不是 `$0.00`** —— 后者看起来像一个算出来的
/// 结果,会让人误以为这次调用真的免费;「订阅」表达的是「这笔账不在
/// 这个维度上」。
Subscription,
/// 不计费:本地模型、免费额度。**费用记 $0,是一个确定的数** ——
/// 和订阅制不同,这里的钱确实是零
/// 不计费:本地模型、免费额度。**费用记 $0,是一个确定的数**
Free,
/// 上游价格未知。成本栏标「未知」,**不参与合计**
Unknown,
}

impl Billing {
pub fn label(&self) -> &'static str {
match self {
Billing::PerToken => "per token",
Billing::Subscription => "subscription",
Billing::Free => "free",
Billing::Unknown => "billing unknown",
}
}
pub fn slug(&self) -> &'static str {
match self {
Billing::PerToken => "per-token",
Billing::Subscription => "subscription",
Billing::Free => "free",
Billing::Unknown => "unknown",
}
}
}
Expand Down Expand Up @@ -1040,6 +1028,34 @@ providers:
assert_eq!(cfg.listen.gateway.allow_from, default_allow_from());
}

#[test]
fn billing_is_per_token_or_free_and_nothing_else() {
let parse = |billing: &str| {
serde_yaml_ng::from_str::<Config>(&format!(
"version: 1\nproviders:\n - {{ name: p, base_url: https://api.example.com{billing} }}\n"
))
};
// 不写就是按量计费,写回去也不多出这一行
let unset = parse("").unwrap();
assert_eq!(unset.providers[0].billing, Billing::PerToken);
assert!(
!serde_yaml_ng::to_string(&unset)
.unwrap()
.contains("billing")
);
assert_eq!(
parse(", billing: free").unwrap().providers[0].billing,
Billing::Free
);
// 订阅账号也按价目表算费用,「订阅」和「未知」不再是计费方式
for gone in ["subscription", "unknown"] {
assert!(
parse(&format!(", billing: {gone}")).is_err(),
"{gone} 还被接受"
);
}
}

#[test]
fn the_allow_list_is_exactly_what_is_written() {
// 不写是私网段;写成空的就是空的(只有本机),不会被悄悄填回默认名单
Expand Down
1 change: 0 additions & 1 deletion crates/tw-control/src/chatgpt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -714,7 +714,6 @@ async fn exchange_and_save(
base_url: backend.clone(),
protocol: Some(Protocol::Chatgpt),
proxy: proxy.clone(),
billing: Some(tw_config::Billing::Subscription),
..Default::default()
});
// 重新登录:换掉凭据和账户 ID,其余设置(出站方式、模型范围、停用…)不动
Expand Down
11 changes: 3 additions & 8 deletions crates/tw-control/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -427,8 +427,7 @@ fn provider_view(
tw_gateway::health::State::Open => "open".into(),
},
auth_rejected: s.gateway.auth_rejected(&p.name),
billing: p.billing.map(|b| b.slug().to_string()),
billing_effective: s.gateway.billing_of(p).slug().to_string(),
billing: p.billing.slug().to_string(),
references: tw_config::refs::provider_refs(cfg, &p.name)
.iter()
.map(resources::reference_view)
Expand Down Expand Up @@ -669,8 +668,6 @@ async fn summary(
cost_micros_estimated: x.cost_micros_estimated,
unpriced_requests: x.unpriced_requests,
no_usage_requests: x.no_usage_requests,
subscription_requests: x.subscription_requests,
subscription_tokens: x.subscription_tokens,
cache_saved_micros: x.cache_saved_micros,
// **和安全日志数的是同一批**:概览上点开这个数,落到的日志就是这么多条
security: g.db().security_counts(from, to).map_err(internal)?,
Expand Down Expand Up @@ -740,9 +737,8 @@ async fn speed_quote(
targets(&cfg, &req.providers)?
.into_iter()
.map(|p| {
// 计费方式和记账同一个口径:配置里写明了,或者最近一次响应里报过额度
let e =
tw_gateway::l3::estimate(&book, &p.name, &req.model, s.gateway.billing_of(p));
// 和记账同一个口径:按这家的计费方式和价目表
let e = tw_gateway::l3::estimate(&book, &p.name, &req.model, p.billing);
(e, tw_gateway::models::fit(&catalog, p, &req.model))
})
.collect();
Expand Down Expand Up @@ -1307,7 +1303,6 @@ fn session_view(s: &tw_store::db::SessionRow) -> tw_api::SessionView {
priced_turns: s.priced_turns as u64,
unpriced_turns: s.unpriced_turns as u64,
no_usage_turns: s.no_usage_turns as u64,
subscription_turns: s.subscription_turns as u64,
input_tokens: s.input_tokens,
output_tokens: s.output_tokens,
cache_read_tokens: s.cache_read_tokens,
Expand Down
10 changes: 2 additions & 8 deletions crates/tw-control/src/replay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,14 +131,8 @@ pub async fn quote(
..Default::default()
};
// **按要重放到的那个上游报价**,不是原来那条走的上游。计费方式和记账
// 同一个口径:配置里写明了,或者最近一次响应里报过额度
let quote = tw_gateway::quote::quote(
&book,
&provider.name,
&row.model,
&usage,
s.gateway.billing_of(provider),
);
let quote =
tw_gateway::quote::quote(&book, &provider.name, &row.model, &usage, provider.billing);
Ok(Json(tw_api::ReplayQuote {
model: row.model.clone(),
provider: provider.name.clone(),
Expand Down
3 changes: 2 additions & 1 deletion crates/tw-control/src/resources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,8 @@ fn to_provider(
.billing
.as_deref()
.map(|v| slug("billing mode", v))
.transpose()?,
.transpose()?
.unwrap_or_default(),
proxy: input.proxy.trim().to_string(),
on_proxy_fail: slug("setting for an unusable proxy", &input.on_proxy_fail)?,
models_only: input
Expand Down
14 changes: 10 additions & 4 deletions crates/tw-control/tests/chatgpt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,6 @@ fn logged_in(name: &str, e: &Endpoints, refresh: &str) -> String {
" - name: {name}
base_url: {backend}
protocol: chatgpt
billing: subscription
oauth:
access: at-cfg
expires_at: 2099-01-01T00:00:00Z
Expand Down Expand Up @@ -477,7 +476,9 @@ async fn a_browser_login_writes_the_account_into_the_config_and_hands_back_to_th
let p = b.provider("chatgpt").expect("登录之后配置里应当有这个上游");
assert_eq!(p.effective_protocol(), Some(tw_config::Protocol::Chatgpt));
assert_eq!(p.base_url, b.endpoints.backend);
assert_eq!(p.billing, Some(tw_config::Billing::Subscription));
// 订阅账号也按价目表算费用:登录建的上游不写计费方式,就是按量计费
assert_eq!(p.billing, tw_config::Billing::PerToken);
assert!(!b.file().contains("billing"), "{}", b.file());
let o = p.oauth.as_ref().unwrap();
assert_eq!(o.refresh, "rt-login");
assert_eq!(o.access.as_deref(), Some("at-login"));
Expand Down Expand Up @@ -612,8 +613,8 @@ async fn a_rejected_code_fails_the_login_and_leaves_the_config_alone() {
async fn logging_in_again_replaces_the_credentials_and_keeps_the_settings() {
let b = bed(|e| {
logged_in("chatgpt", e, "rt-old").replace(
" billing: subscription\n",
" billing: subscription\n models_only: [gpt-5.5]\n",
" protocol: chatgpt\n",
" protocol: chatgpt\n billing: free\n models_only: [gpt-5.5]\n",
)
})
.await;
Expand All @@ -627,6 +628,11 @@ async fn logging_in_again_replaces_the_credentials_and_keeps_the_settings() {
("rt-login", Some("at-login"))
);
assert_eq!(p.models_only.as_deref(), Some(&["gpt-5.5".to_string()][..]));
assert_eq!(
p.billing,
tw_config::Billing::Free,
"重新登录改掉了计费方式"
);
assert_eq!(p.headers.len(), 1, "账户 ID 只留一个");
assert_eq!(
p.headers.get("chatgpt-account-id").unwrap().value.raw(),
Expand Down
6 changes: 3 additions & 3 deletions crates/tw-control/tests/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -398,8 +398,8 @@ async fn an_address_being_typed_previews_what_automatic_detection_will_pick() {
.await;
assert!(v.get("protocol").is_none(), "{v}");

// 没写计费方式时,概览说出它实际按什么计费
// 没写计费方式就是按量计费,概览照实说
let (_, ov) = call(&b.app, "GET", "/overview", serde_json::json!(null)).await;
assert!(ov["providers"][0].get("billing").unwrap().is_null());
assert_eq!(ov["providers"][0]["billing_effective"], "per-token");
assert_eq!(ov["providers"][0]["billing"], "per-token");
assert!(ov["providers"][0].get("billing_effective").is_none());
}
Loading
Loading