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
2 changes: 2 additions & 0 deletions crates/tw-api/msg-codes.txt
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,9 @@ gw.listen.no_such_nic
gw.listen.port_taken
gw.model.no_upstream
gw.model.no_upstream_available
gw.model.no_upstream_rewritten
gw.model.not_allowed
gw.model.not_allowed_rewritten
gw.model.unknown
gw.models.check_failed
gw.models.empty
Expand Down
19 changes: 8 additions & 11 deletions crates/tw-control/src/dryrun.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ fn order_like_the_data_plane(
s: &crate::ControlState,
engine: &tw_engine::Engine,
d: &tw_engine::Decision,
f: &tw_engine::RequestFacts,
asked: &[(String, String)],
) -> Vec<String> {
let Some(gname) = d.via_group.clone() else {
return d.candidates.clone();
Expand All @@ -38,9 +38,7 @@ fn order_like_the_data_plane(
session: None,
seq: s.gateway.bus.peek_id(),
ttfb_ms: s.gateway.latency.snapshot(&d.candidates),
price: s
.gateway
.unit_prices(&cfg.providers, &d.candidates, &f.model),
price: s.gateway.unit_prices(&cfg.providers, asked, &d.candidates),
};
engine.order(Some(&gname), &d.candidates, &facts)
}
Expand Down Expand Up @@ -237,12 +235,11 @@ pub async fn dry_run(
// 和数据面同一步:去掉服务不了这个请求的候选(停用的、范围外的、
// 清单里没有这个模型的)。**被跳过的要列出来** —— 「规则明明写的
// 是 A」正是用户会来试算的原因
let serving = tw_gateway::models::serving(
&rt.config,
&s.gateway.catalog.load(),
&d.candidates,
&f.model,
);
//
// 每一家按它实际要的模型看:规则改写过的按改写后的算,和数据面一样
let asked = engine.models_asked(rules, &f, &d);
let serving =
tw_gateway::models::serving(&rt.config, &s.gateway.catalog.load(), &asked);
out.skipped = serving
.skipped
.iter()
Expand Down Expand Up @@ -274,7 +271,7 @@ pub async fn dry_run(
// 而它属于哪次会话取决于请求正文,试算没有那个东西。
// 于是它显示的是轮转序列里的当前位置 —— 而那正是一个没有
// 会话指纹的请求真的会走的路。
out.candidates = order_like_the_data_plane(&s, engine, &d, &f);
out.candidates = order_like_the_data_plane(&s, engine, &d, &asked);
// 哪些候选要转换格式。**试算里要说出来**:转换可能丢掉请求里的字段,
// 而「规则把我分到了一个别的格式的上游」本身就是用户来试算想知道的事。
// 协议认不出来的上游直通,不算
Expand Down
38 changes: 38 additions & 0 deletions crates/tw-control/tests/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,44 @@ routes:
assert!(v["reason"].is_null(), "{v}");
}

#[tokio::test]
async fn the_dry_run_judges_each_upstream_by_the_model_a_rule_rewrites_to() {
// 官方只开了 sonnet。一条规则把 opus 改成 sonnet 交给它:按请求里的名字,
// 试算会说它在范围外,而真的转发时发出去的是 sonnet
let yaml = "version: 1
listen:
control:
key: c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00
clients:
- name: c
key: tw-k
providers:
- name: 官方
base_url: https://api.anthropic.com
key: sk-a
models_only: [claude-sonnet-*]
routes:
- name: default
rules:
- name: opus 换成 sonnet
to: 官方
set: { model: claude-sonnet-4-5 }
";
let b = bed(yaml);
let (st, v) = call(
&b.app,
"POST",
"/dryrun",
serde_json::json!({ "model": "claude-opus-4-1", "client": "c" }),
)
.await;
assert_eq!(st, StatusCode::OK, "{v}");
assert_eq!(v["outcome"], "route", "{v}");
assert_eq!(v["rule"], "opus 换成 sonnet", "{v}");
assert_eq!(v["candidates"], serde_json::json!(["官方"]));
assert_eq!(v["skipped"], serde_json::json!([]));
}

#[tokio::test]
async fn an_address_being_typed_previews_what_automatic_detection_will_pick() {
let b = bed(&config(upstream().await, "sk-good", ""));
Expand Down
45 changes: 44 additions & 1 deletion crates/tw-engine/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -806,10 +806,21 @@ impl Engine {
facts: &RequestFacts,
provider: &str,
base: &SetAction,
) -> Result<Outcome2, RouteError> {
self.phase_two_with(self.rules_for(&facts.client), facts, provider, base)
}

/// 按给定的规则表走阶段二。试算按草稿求值时走这里,理由和 [`Self::route_with`] 一样。
pub fn phase_two_with(
&self,
rules: &[Rule],
facts: &RequestFacts,
provider: &str,
base: &SetAction,
) -> Result<Outcome2, RouteError> {
let mut set = base.clone();
let mut rewritten_by = Vec::new();
for r in self.rules_for(&facts.client) {
for r in rules {
if !r.when.is_phase_two() || !r.when.matches_with_provider(facts, provider)? {
continue;
}
Expand All @@ -829,6 +840,38 @@ impl Engine {
Ok(Outcome2::Proceed { set, rewritten_by })
}

/// 每个候选实际会被要哪个模型,按候选的顺序。
///
/// **规则改写过模型的,按改写后的算**:阶段二的盖过阶段一的,都没改写才是
/// 请求里写的那个。准入、跳过服务不了的候选、比价,看的都得是发出去的那个
/// 名字 —— 按客户端写的名字看,一条把 `claude-*` 改成 `glm-*` 的规则永远
/// 用不上:智谱的清单里没有 `claude-*`。
///
/// 阶段二拒绝或求不了值时按阶段一算:那一跳本来就发不出去,尝试那一步会
/// 报出来。请求里读不出模型时一律是空的 —— 请求体都解不开,改写也写不进去。
pub fn models_asked(
&self,
rules: &[Rule],
facts: &RequestFacts,
d: &Decision,
) -> Vec<(String, String)> {
d.candidates
.iter()
.map(|c| {
let model = if facts.model.is_empty() {
String::new()
} else {
let set = match self.phase_two_with(rules, facts, c, &d.set) {
Ok(Outcome2::Proceed { set, .. }) => set.model,
_ => d.set.model.clone(),
};
set.unwrap_or_else(|| facts.model.clone())
};
(c.clone(), model)
})
.collect()
}

fn resolve_target(&self, r: &Rule) -> Result<(Vec<String>, Option<String>), RouteError> {
let Some(to) = &r.to else {
return Ok((Vec::new(), None));
Expand Down
41 changes: 31 additions & 10 deletions crates/tw-gateway/src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -572,15 +572,23 @@ impl Skip {
pub struct Serving {
pub usable: Vec<String>,
pub skipped: Vec<(String, Skip)>,
/// 每个候选要的模型,给 [`Self::explain`] 那句话用
asked: Vec<(String, String)>,
}

impl Serving {
/// 一个都不剩时给客户端的那句话。
/// 一个都不剩时给客户端的那句话。`model` 是阶段一之后要的模型;哪一家要的
/// 不是它(阶段二按上游改写过),就在那一家后面写出它要的那个。
pub fn explain(&self, model: &str) -> crate::GatewayError {
let why = self
.skipped
.iter()
.map(|(p, s)| format!("{p} {}", s.label()))
.map(
|(p, s)| match self.asked.iter().find(|(c, _)| c == p).map(|(_, m)| m) {
Some(m) if !m.is_empty() && m != model => format!("{p} {} ({m})", s.label()),
_ => format!("{p} {}", s.label()),
},
)
.collect::<Vec<_>>()
.join("; ");
// 全是停用:请求没问题,是配置里能用的上游都关掉了
Expand Down Expand Up @@ -615,16 +623,21 @@ pub fn fit(catalog: &tw_engine::Catalog, p: &tw_config::Provider, model: &str) -

/// 在路由选出的候选里去掉服务不了这个请求的上游。
///
/// **没有模型清单的上游不跳过**:不知道它有什么,不等于它没有。`model`
/// 是空的(请求体解析不了)时只看停用。
/// `asked` 是每个候选和它要的模型([`tw_engine::Engine::models_asked`]):
/// **每一家按它实际要的那个模型看**,规则改写过的就是改写后的。
///
/// **没有模型清单的上游不跳过**:不知道它有什么,不等于它没有。模型是空的
/// (请求体解析不了)时只看停用。
pub fn serving(
cfg: &tw_config::Config,
catalog: &tw_engine::Catalog,
candidates: &[String],
model: &str,
asked: &[(String, String)],
) -> Serving {
let mut out = Serving::default();
for name in candidates {
let mut out = Serving {
asked: asked.to_vec(),
..Serving::default()
};
for (name, model) in asked {
let Some(p) = cfg.providers.iter().find(|p| &p.name == name) else {
// 配置里没有这一家:留给尝试那一步报出来
out.usable.push(name.clone());
Expand Down Expand Up @@ -667,6 +680,14 @@ mod tests {
}
}

/// 每个候选都要同一个模型:没有规则改写时的样子
fn asked(candidates: &[&str], model: &str) -> Vec<(String, String)> {
candidates
.iter()
.map(|c| (c.to_string(), model.to_string()))
.collect()
}

fn cfg(providers: Vec<tw_config::Provider>) -> tw_config::Config {
tw_config::Config {
providers,
Expand Down Expand Up @@ -740,7 +761,7 @@ mod tests {
c.providers[2].models_only = Some(vec!["c-1".into()]);
let cat = published(&d, &c);
assert_eq!(cat.all(), ["a-1", "a-2", "c-1"]);
let s = serving(&c, &cat, &["a".into(), "b".into(), "c".into()], "c-2");
let s = serving(&c, &cat, &asked(&["a", "b", "c"], "c-2"));
assert_eq!(
s.skipped,
[
Expand Down Expand Up @@ -771,7 +792,7 @@ mod tests {
);
let cat = published(&d, &c);
// 不知道它们有什么:不跳过
let s = serving(&c, &cat, &["a".into(), "b".into()], "m");
let s = serving(&c, &cat, &asked(&["a", "b"], "m"));
assert_eq!(s.usable, ["a", "b"]);
// 失败的一小时后重问,没有接口的一天后
let hour = RETRY_AFTER.as_millis() as u64;
Expand Down
73 changes: 52 additions & 21 deletions crates/tw-gateway/src/server/pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,6 @@ pub(super) async fn pipeline(
}

let (reading, fp) = read(&req, intent);
admit(&state, &rt, &req, &reading)?;
let (choice, decision) = match route(&state, &rt, &req, &reading, fp.as_deref())? {
Routed::Go(choice, decision) => (choice, decision),
// 规则做了决定,请求却一家上游都不会去。**照样开始、照样报路由**,失败由
Expand Down Expand Up @@ -204,8 +203,13 @@ fn read(req: &Inbound, intent: String) -> (crate::client_api::Reading, Option<St
(reading, fp)
}

/// 管线第 1.5 步:模型准入。**和 `GET /v1/models` 共用同一个函数**
/// —— 列出来的一定能用,能用的一定列了出来。
/// 管线第 2 步的中段:模型准入。**和 `GET /v1/models` 共用同一个函数**
/// —— 列出来的一定能用。
///
/// **看的是发出去的模型,不是客户端写的那个**,所以放在规则做完决定之后:
/// 一条把 `claude-*` 改成 `glm-*` 的规则,请求里的名字哪一家的清单里都没有,
/// 改写后的才有。`asked` 里有一个过得去就放行 —— 哪一家服务不了,由下一步
/// 把它跳过。
///
/// 目录空着时不拦:那说明探测还没回来或者上游都不给列表,这时候拦
/// 等于把整个网关关掉。
Expand All @@ -214,6 +218,8 @@ fn admit(
rt: &Runtime,
req: &Inbound,
reading: &crate::client_api::Reading,
decision: &tw_engine::Decision,
asked: &[(String, String)],
) -> Result<(), GatewayError> {
let facts = &reading.facts;
let catalog = state.catalog.load();
Expand All @@ -229,23 +235,44 @@ fn admit(
let servable = req
.api
.map(|a| crate::client_api::slugs(a.servable_by(reading.generates)));
if catalog.admits(&facts.model, servable.as_deref(), allow.as_deref()) {
// 阶段一之后要的模型。规则一家候选都没给时就看它
let model = decision.set.model.as_deref().unwrap_or(&facts.model);
let mut models: Vec<&str> = asked.iter().map(|(_, m)| m.as_str()).collect();
if models.is_empty() {
models.push(model);
}
if models
.iter()
.any(|m| catalog.admits(m, servable.as_deref(), allow.as_deref()))
{
return Ok(());
}
// 错误信息要说清是哪一种:没有上游提供它,和这个客户端不让用它,
// 该去改的地方不一样
let why = if catalog.providers_for(&facts.model).is_empty() {
msg!(
// 该去改的地方不一样。**改写过的两个名字都要说**:客户端写的是一个,
// 报错里说的是另一个,不说清楚像是网关认错了模型
let offered = models.iter().any(|m| !catalog.providers_for(m).is_empty());
let why = match (offered, model != facts.model) {
(false, false) => msg!(
"gw.model.no_upstream", model = facts.model.clone() =>
"No upstream serves model {model}. GET /v1/models lists the models that \
are available."
)
} else {
msg!(
),
(true, false) => msg!(
"gw.model.not_allowed", key = req.client_name.clone(), model = facts.model.clone() =>
"Gateway key `{key}` may not use model {model}. GET /v1/models lists the \
models that are available."
)
),
(false, true) => msg!(
"gw.model.no_upstream_rewritten", from = facts.model.clone(), model = model =>
"A routing rule rewrote model {from} to {model}, and no upstream serves {model}. \
GET /v1/models lists the models that are available."
),
(true, true) => msg!(
"gw.model.not_allowed_rewritten", from = facts.model.clone(), model = model,
key = req.client_name.clone() =>
"A routing rule rewrote model {from} to {model}, which gateway key `{key}` may not \
use. GET /v1/models lists the models that are available."
),
};
Err(GatewayError::new(crate::error::Source::Request, why))
}
Expand All @@ -266,7 +293,8 @@ enum Routed {
/// 闸门之后(见 [`start`])。
///
/// 返回的错误是**规则还没做出决定**的那些(没有一条规则命中、规则求不了值):
/// 那时说不出这个请求算在哪条规则上,不留这一行,和鉴权没过一样。
/// 那时说不出这个请求算在哪条规则上,不留这一行,和鉴权没过一样。模型准入没过
/// ([`admit`])也从这里返回,同样不留这一行 —— 和准入放在路由之前时一样。
fn route(
state: &AppState,
rt: &Runtime,
Expand Down Expand Up @@ -304,22 +332,25 @@ fn route(
group: decision.via_group.clone(),
rewritten_by: decision.rewritten_by.clone(),
};
// 每个候选实际要的模型:规则改写过的按改写后的算。准入、跳过、比价都看它
let asked = rt.engine.models_asked(
rt.engine.rules_for_client(&req.client_name),
facts,
&decision,
);
admit(state, rt, req, reading, &decision, &asked)?;
// 去掉服务不了这个请求的候选:停用的、范围外的、清单里没有这个模型的。
// **在排序之前** —— `cheapest` 和 `url-test` 要在能服务的上游里挑。
//
// 不跳过的话,一家没有这个模型的上游排在前面,它回的 404 不触发故障
// 转移,请求就在一家能服务它的上游旁边失败了。
let serving = crate::models::serving(
&rt.config,
&state.catalog.load(),
&decision.candidates,
&facts.model,
);
let serving = crate::models::serving(&rt.config, &state.catalog.load(), &asked);
let model = decision.set.model.as_deref().unwrap_or(&facts.model);
if serving.usable.is_empty() {
return Ok(Routed::Refused(choice, serving.explain(&facts.model)));
return Ok(Routed::Refused(choice, serving.explain(model)));
}
if !serving.skipped.is_empty() {
tracing::debug!(skipped = ?serving.skipped, model = %facts.model, "skipping the candidates that cannot serve this request");
tracing::debug!(skipped = ?serving.skipped, %model, "skipping the candidates that cannot serve this request");
}
decision.candidates = serving.usable;
// 策略组排序。**引擎给的是集合,顺序在这儿定** ——
Expand All @@ -345,7 +376,7 @@ fn route(
},
price: match kind {
tw_engine::GroupType::Cheapest => {
state.unit_prices(&rt.config.providers, &decision.candidates, &facts.model)
state.unit_prices(&rt.config.providers, &asked, &decision.candidates)
}
_ => Default::default(),
},
Expand Down
Loading
Loading