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
40 changes: 20 additions & 20 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ repository = "https://github.com/ThinkWatchProject/ThinkWatch-Core"

# 二进制走 CalVer,crate 走 SemVer —— 两者是两回事,卖给不同的人。
# 这里是 crate 的版本。
version = "0.2.0"
version = "0.2.1"

[workspace.dependencies]
# ── 内部 crate ───────────────────────────────────────────
Expand Down
36 changes: 33 additions & 3 deletions crates/tw-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -579,6 +579,9 @@ pub struct ProviderView {
/// 空 = 自动识别
#[serde(default)]
pub billing: Option<String>,
/// 实际按什么计费。没写明时自动识别:报过订阅额度的是 `subscription`,
/// 否则 `per-token`
pub billing_effective: String,
/// 判完的信任级别:`official` / `untrusted`
pub trust: String,
/// 用户有没有在配置里显式写过 `trust`。
Expand Down Expand Up @@ -950,6 +953,11 @@ pub struct PriceSheetSave {
pub sheet: PriceSheetInput,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub base_version: Option<String>,
/// 保存之后使用这张价目表的上游。给了就**恰好是这几家**:列表里的改用
/// 它,原来用它、不在列表里的改回默认价目表,和价目表本身在同一个版本
/// 里写入。不给就不动上游的选择
#[serde(default, skip_serializing_if = "Option::is_none")]
pub used_by: Option<Vec<String>>,
}

/// 按哪张价目表查价。
Expand Down Expand Up @@ -1077,6 +1085,24 @@ pub struct ProviderInput {
pub disabled: bool,
}

/// 按接口地址自动识别的结果。给编辑中、还没保存的上游显示「自动识别」
/// 会选成什么。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProviderPreviewRequest {
pub base_url: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProviderPreview {
/// 按地址推断的接口协议。推断不出是空(转发时按 Anthropic 处理)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub protocol: Option<String>,
/// 是厂商官方端点:自动识别的信任级别是 `official`,否则 `untrusted`
pub official: bool,
/// 自动识别时发送前脱敏的类别
pub redact: Vec<String>,
}

/// 一个上游的模型清单。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProviderModelsView {
Expand Down Expand Up @@ -1456,6 +1482,10 @@ pub struct SpeedEstimate {
pub billing: String,
/// 给人看的那一句
pub note: String,
/// 这家服务不了这个模型:`out_of_scope`(不在启用范围里)/
/// `not_offered`(模型清单里没有)。有值时不进合计,也不会被测
#[serde(default, skip_serializing_if = "Option::is_none")]
pub skipped: Option<String>,
}

/// 一批测速的账。
Expand All @@ -1472,9 +1502,9 @@ pub struct SpeedQuote {

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct SpeedRunRequest {
/// 不给就是所有上游
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
/// 测哪几家。空 = 所有上游
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub providers: Vec<String>,
/// **必填。**同一个 provider 的 Opus 和 Haiku 是两条完全不同的曲线,
/// 不指定模型的测速结果没有意义
pub model: String,
Expand Down
68 changes: 48 additions & 20 deletions crates/tw-control/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,7 @@ fn provider_view(
tw_gateway::health::State::Open => "open".into(),
},
billing: p.billing.map(|b| b.slug().to_string()),
billing_effective: s.gateway.billing_of(p).slug().to_string(),
// **给判完的结果,不是配置里那个 Option。**界面要显示的是
// 「这家现在算不算受信任」,而那件事在没写的时候由 base_url 决定
trust: tw_gateway::guard::effective_trust(p, &tw_engine::Guard::default())
Expand Down Expand Up @@ -681,16 +682,29 @@ async fn speed_quote(
) -> Result<Json<tw_api::SpeedQuote>, Fail> {
let cfg = s.config();
let book = s.gateway.pricing.load();
let items: Vec<tw_gateway::Estimate> = targets(&cfg, req.provider.as_deref())?
.iter()
.map(|p| {
// 计费方式和记账同一个口径:配置里写明了,或者最近一次响应里报过额度
tw_gateway::l3::estimate(&book, &p.name, &req.model, s.gateway.billing_of(p))
})
.collect();
let catalog = s.gateway.catalog.load();
let items: Vec<(tw_gateway::Estimate, Option<tw_gateway::models::Skip>)> =
targets(&cfg, &req.providers)?
.into_iter()
.map(|p| {
// 计费方式和记账同一个口径:配置里写明了,或者最近一次响应里报过额度
let e =
tw_gateway::l3::estimate(&book, &p.name, &req.model, s.gateway.billing_of(p));
(e, tw_gateway::models::fit(&catalog, p, &req.model))
})
.collect();
Ok(Json(tw_api::SpeedQuote {
total_micros: tw_gateway::quote::total(items.iter().map(|e| &e.quote)),
items: items.into_iter().map(quote_item).collect(),
// 服务不了这个模型的那几家不会被测,也就不进合计
total_micros: tw_gateway::quote::total(
items
.iter()
.filter(|(_, skip)| skip.is_none())
.map(|(e, _)| &e.quote),
),
items: items
.into_iter()
.map(|(e, skip)| quote_item(e, skip))
.collect(),
pricing_date: book.table().date.clone(),
}))
}
Expand All @@ -701,10 +715,16 @@ async fn speed_run(
Json(req): Json<tw_api::SpeedRunRequest>,
) -> Result<Json<Vec<tw_api::SpeedResult>>, Fail> {
let cfg = s.config();
let catalog = s.gateway.catalog.load();
let mut out = Vec::new();
// **逐个跑,不并发。**几家一起打,测出来的 TTFT 互相干扰,而这一层
// 存在的全部意义就是那几个数字准不准(和 L1 同一个理由)。
for p in targets(&cfg, req.provider.as_deref())? {
for p in targets(&cfg, &req.providers)? {
// 服务不了这个模型的不发:报价里已经说了它不会被测,发出去只会得到
// 一个 4xx,还可能被计费
if tw_gateway::models::fit(&catalog, p, &req.model).is_some() {
continue;
}
// OAuth 那类要联网换 token,所以走网关那条 async 的路。
// **用这一家自己的 client** —— 换 token 要走它的代理。
let pk_http = s.gateway.client_for(&p.name);
Expand All @@ -720,7 +740,7 @@ async fn speed_run(
total_ms: 0,
input_tokens: None,
output_tokens: None,
error: Some(format!("密钥取不到:{e}")),
error: Some(format!("取不到凭据:{e}")),
});
continue;
}
Expand Down Expand Up @@ -751,7 +771,10 @@ async fn speed_run(
Ok(Json(out))
}

fn quote_item(e: tw_gateway::Estimate) -> tw_api::SpeedEstimate {
fn quote_item(
e: tw_gateway::Estimate,
skip: Option<tw_gateway::models::Skip>,
) -> tw_api::SpeedEstimate {
tw_api::SpeedEstimate {
provider: e.provider,
model: e.model,
Expand All @@ -760,22 +783,27 @@ fn quote_item(e: tw_gateway::Estimate) -> tw_api::SpeedEstimate {
cost_micros: e.quote.cost_micros,
billing: e.quote.billing.slug().to_string(),
note: e.quote.note,
skipped: skip.map(|s| s.slug().to_string()),
}
}

/// 要测的那几家。**空 = 全部**;点名了一家不存在的就是 404,不悄悄跳过。
fn targets<'a>(
cfg: &'a tw_config::Config,
provider: Option<&str>,
names: &[String],
) -> Result<Vec<&'a tw_config::Provider>, Fail> {
match provider {
Some(n) => Ok(vec![
if names.is_empty() {
return Ok(cfg.providers.iter().collect());
}
names
.iter()
.map(|n| {
cfg.providers
.iter()
.find(|p| p.name == n)
.ok_or_else(|| (StatusCode::NOT_FOUND, format!("没有叫 `{n}` 的上游")))?,
]),
None => Ok(cfg.providers.iter().collect()),
}
.find(|p| &p.name == n)
.ok_or_else(|| (StatusCode::NOT_FOUND, format!("没有叫「{n}」的上游")))
})
.collect()
}

/// 出站密钥检测攒下的证据。
Expand Down
Loading
Loading