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
10 changes: 9 additions & 1 deletion crates/tw-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>,
/// WebSocket 的那一跳是一次握手:上游同意升级(101)是 `served`,回了别的
/// 状态码是 `status`,连不上是 `error`。
pub outcome: AttemptOutcome,
Expand Down Expand Up @@ -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<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
Expand Down
8 changes: 4 additions & 4 deletions crates/tw-config/tests/manual/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -820,17 +820,17 @@ pub fn sections() -> Vec<Section> {
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(
"output_above_200k",
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 后的输出单价。",
),
),
],
Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/tests/in_flight.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/tests/live_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
7 changes: 6 additions & 1 deletion crates/tw-gateway/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>,
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,
Expand All @@ -320,11 +323,13 @@ pub(crate) fn hop(
/// 没有收到响应的一跳。`error` 和这一跳报给客户端的那条错误是同一句。
pub(crate) fn hop_failed(
provider: &str,
model: Option<String>,
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),
Expand Down
50 changes: 44 additions & 6 deletions crates/tw-gateway/src/server/pipeline/hop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
Expand All @@ -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;
}
Expand All @@ -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;
}
Expand All @@ -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;
}
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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;
}
Expand Down
7 changes: 4 additions & 3 deletions crates/tw-gateway/src/ws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
54 changes: 54 additions & 0 deletions crates/tw-gateway/tests/routing_facts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
2 changes: 2 additions & 0 deletions crates/tw-observe/src/bus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -423,13 +423,15 @@ mod tests {
attempts: vec![
tw_api::AttemptView {
provider: "p".into(),
model: None,
outcome: tw_api::AttemptOutcome::Status,
status: Some(503),
error: None,
ms: 10,
},
tw_api::AttemptView {
provider: served_by.into(),
model: None,
outcome: tw_api::AttemptOutcome::Served,
status: Some(200),
error: None,
Expand Down
Loading
Loading