From a3fe268653748c071f8ce62a1778d62774048625 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Fri, 9 Oct 2026 11:24:20 +0800 Subject: [PATCH] feat(models): models added by hand count as offered next to the upstream's list An upstream's `models` used to be a fallback, used only when `/v1/models` could not be fetched. Once the upstream answered, a model missing from its answer was skipped for that upstream (`Skip::NotOffered`), even for a rule that pins it. Real upstreams leave out models they serve: the ChatGPT account backend hides new models from older client versions, and relays list only part of what they carry. There was no way to say "this upstream has it anyway". `providers[].models` now means "models added by hand": always offered by that upstream, merged after the models it lists, and still the whole list when it lists none. The union is made once, in the gateway's listing, so the catalog, `/v1/models`, admission, aliases, pinned models, key `allow`, the dry run and the speed test all see a manual model exactly like a listed one. `models_only` still applies on top. No new field and no migration: an old fallback list keeps meaning the same thing. The control plane says which rows are manual and which the upstream lists (`ModelRow.manual`, `ModelRow.listed`), and sets the list through `PUT /provider-manual-models` (`ManualModelsSave` -> `ConfigWritten`), which writes only that upstream's `models` like the model-spec endpoint does. Entries are trimmed, then checked by the same rules the config validation now applies: not blank, no surrounding whitespace, no `*` or `?`, at most 256 characters, no duplicates (`config.manual_model_*`). Protocol 42. Co-Authored-By: Claude Opus 5.5 --- crates/tw-api/msg-codes.txt | 5 + crates/tw-api/src/ep.rs | 3 + crates/tw-api/src/lib.rs | 50 ++- crates/tw-config/src/edit.rs | 143 +++++++++ crates/tw-config/src/lib.rs | 16 +- crates/tw-config/src/validate.rs | 109 +++++++ crates/tw-config/tests/manual/schema.rs | 4 +- crates/tw-control/src/diagnostics.rs | 10 +- crates/tw-control/src/resources.rs | 30 ++ crates/tw-control/tests/manual_models.rs | 377 +++++++++++++++++++++++ crates/tw-gateway/src/models.rs | 118 ++++++- crates/tw-gateway/tests/models.rs | 80 ++++- docs/config.md | 12 +- docs/config.zh-CN.md | 4 +- 14 files changed, 934 insertions(+), 27 deletions(-) create mode 100644 crates/tw-control/tests/manual_models.rs diff --git a/crates/tw-api/msg-codes.txt b/crates/tw-api/msg-codes.txt index 7c6dbac9..f1960fac 100644 --- a/crates/tw-api/msg-codes.txt +++ b/crates/tw-api/msg-codes.txt @@ -74,6 +74,11 @@ config.key_limit_empty config.key_limit_not_positive config.key_limit_retention config.key_limit_two_measures +config.manual_model_blank +config.manual_model_duplicate +config.manual_model_padded +config.manual_model_too_long +config.manual_model_wildcard config.model_spec_blank_model config.model_spec_nothing_set config.model_spec_wildcard diff --git a/crates/tw-api/src/ep.rs b/crates/tw-api/src/ep.rs index aaf98bfa..11543588 100644 --- a/crates/tw-api/src/ep.rs +++ b/crates/tw-api/src/ep.rs @@ -99,6 +99,9 @@ endpoints! { /// 手写一家上游的一个模型的上下文窗口、输出上限,优先于价目表;两项都空就删掉。 /// **不在 `/providers/` 底下**:写死的一段会盖住 `/providers/{name}` SetModelSpec: PUT "/provider-model-spec", api::ModelSpecSave => api::ConfigWritten; + /// 换掉一家上游手动添加的模型(整份清单,空的就是清掉):上游能服务、却没列进清单的 + /// 模型,和列出的一样算这家提供。**不在 `/providers/` 底下**,同上 + SetManualModels: PUT "/provider-manual-models", api::ManualModelsSave => api::ConfigWritten; RefreshProviderModels: POST "/providers/{name}/models/refresh" [name], () => api::ProviderModelsView; RefreshStaleModels: POST "/models/refresh", () => api::ModelsRefreshing; CreateProxy: POST "/proxies", api::ProxySave => api::ConfigWritten; diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index db1a1903..ec1f5830 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -156,9 +156,9 @@ slug_enum! { slug_enum! { /// 一个上游的模型清单从哪儿来。 pub enum ModelSource { - /// 上游列出的 + /// 上游列出的(手动添加的接在后面) Discovered = "discovered", - /// 配置里手写的 + /// 上游没给出清单,只有手动添加的 Manual = "manual", /// 都没有:不知道它有什么 None = "none", @@ -805,7 +805,16 @@ pub const MSG_CODES: &str = include_str!("../msg-codes.txt"); /// 不会再变,下次从这里取);[`DryRunCandidate`] 多了 `share`(负载均衡组里这一家按 /// 当前权重和系数分到的份额,别的组和这一轮不参与的是 None)。照 40 写的界面取对话视图 /// 时传 `null` 会被拒。 -pub const CONTROL_API_VERSION: u32 = 41; +/// +/// **42 起上游的模型可以手动添加**:配置里一家上游的 `models` 不再只是取不到清单时的 +/// 兜底,而是一律算这家提供、和上游列出的合在一起(上游不提供清单时就是全部),列表、 +/// 准入、别名、指定模型、密钥范围、试算都把它当作列出的模型。[`ModelRow`] 多了 `manual` +/// (手动添加的)和 `listed`(上游自己的清单里有);新端点 `PUT /provider-manual-models` +/// ([`ManualModelsSave`] → [`ConfigWritten`])交一家的整份手动清单,写法不对时是 +/// `config.manual_model_blank`、`_padded`、`_wildcard`、`_duplicate`、`_too_long`(400), +/// 整份配置的校验也查这几条。`source` 是 `discovered` 时 `models` 里也有手动添加的那些。 +/// 照 41 写的界面分不出哪些模型是手动添加的。 +pub const CONTROL_API_VERSION: u32 = 42; #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] @@ -2039,13 +2048,14 @@ pub struct ProviderView { pub proxy: String, /// `fail` / `direct` pub on_proxy_fail: OnProxyFail, - /// 服务不提供模型列表时用的手动清单 + /// 手动添加的模型,按写的顺序:和上游列出的一起算这家提供(上游不提供清单时就是 + /// 全部) pub models: Vec, /// 启用范围:只用这些模型(ID 或 glob)。空 = 它提供的全部 #[serde(default, skip_serializing_if = "Option::is_none")] pub models_only: Option>, - /// 模型清单从哪儿来:`discovered`(上游列出的)/ `manual`(手动清单)/ - /// `none`(不知道它有什么) + /// 模型清单从哪儿来:`discovered`(上游列出的,手动添加的接在后面)/ `manual`(上游 + /// 没给出清单,只有手动添加的)/ `none`(不知道它有什么) pub model_source: ModelSource, /// 最近一次向上游获取清单的结果 pub model_status: ModelListStatus, @@ -3003,7 +3013,9 @@ pub struct ProviderInput { /// `fail` / `direct` #[serde(default = "fail_closed")] pub on_proxy_fail: OnProxyFail, - /// 服务不提供模型列表时的手动清单 + /// 手动添加的模型:和上游列出的一起算这家提供(上游不提供清单时就是全部)。 + /// **编辑对话框保存时原样交回**,不然手动添加的模型会被清掉;单改这份清单用 + /// `PUT /provider-manual-models`([`ManualModelsSave`]) #[serde(default, skip_serializing_if = "Vec::is_empty")] pub models: Vec, /// 启用范围:只用这些模型(ID 或 glob)。不给就是它提供的全部 @@ -3068,7 +3080,8 @@ slug_enum! { #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ProviderModelsView { pub provider: String, - /// `discovered`(上游列出的)/ `manual`(手动清单)/ `none` + /// `discovered`(上游列出的,手动添加的接在后面)/ `manual`(上游没给出清单,只有 + /// 手动添加的)/ `none` pub source: ModelSource, /// 最近一次获取的结果,同 [`ProviderView::model_status`] pub status: ModelListStatus, @@ -3131,6 +3144,12 @@ pub struct ModelRow { /// 列出了这个模型名的别名,按别名表的顺序。**不论这家发不发它**:别名在这家按列表 /// 顺序取它有的第一个,排在后面的名字也算列进了这个别名 pub aliases: Vec, + /// 手动添加的(配置里这一家的 `models`)。和上游列出的一样算这家提供;删得掉的只有 + /// 这些(`PUT /provider-manual-models`) + pub manual: bool, + /// 上游自己的清单里有它。手动添加的模型上游也列了时两项都是 true;上游没给出清单时 + /// 一律是 false + pub listed: bool, } fn direct() -> String { @@ -3209,6 +3228,21 @@ pub struct ModelSpecSave { pub base_version: Option, } +/// 设一家上游手动添加的模型(`PUT /provider-manual-models`):上游能服务、却没列进 +/// 清单的模型。**交的是整份清单**,按给的顺序换掉原来的;空的就是一个都不留。 +/// +/// 每一项去掉首尾空白之后是一个确切的模型 ID:不空、不带 `*` `?`、不超过 256 个字符, +/// 而且不重复(`config.manual_model_*`)。上游也列了的模型可以加,不算重复。 +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct ManualModelsSave { + pub provider: String, + pub models: Vec, + /// 你基于哪一版。**对不上就是 409** + #[serde(default, skip_serializing_if = "Option::is_none")] + pub base_version: Option, +} + /// 检测一个上游,**不保存**。 #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] diff --git a/crates/tw-config/src/edit.rs b/crates/tw-config/src/edit.rs index ee9f944a..a1ae2847 100644 --- a/crates/tw-config/src/edit.rs +++ b/crates/tw-config/src/edit.rs @@ -719,6 +719,71 @@ pub fn set_model_spec( /// 上游里手写的模型规格那一项的键 const MODEL_SPECS: &str = "model_specs"; +/// 上游里手动添加的模型那一项的键 +const MODELS: &str = "models"; + +/// 把一家上游手动添加的模型(`models`)换成 `models`,按给的顺序。**空的就删掉这个键** +/// —— 默认值不写进文件。 +/// +/// **只动这一家的 `models`**,和 [`set_model_spec`] 一样不走编辑上游那条路:那条路按读进来 +/// 的结构把整项写回去。模型 ID 的毛病由调用方先查([`crate::check_manual_models`]),这里 +/// 只拦换行。 +pub fn set_models(text: &str, provider: &str, models: &[String]) -> Result { + let value = Value::Sequence(models.iter().cloned().map(Value::String).collect()); + reject_multiline(&value)?; + let doc = parse(text)?; + let index = PROVIDERS + .index_of(&doc, provider) + .ok_or_else(|| EditError::NotFound { + what: PROVIDERS.what, + name: provider.to_string(), + })?; + let item = PROVIDERS.items(&doc)[index] + .as_mapping() + .cloned() + .unwrap_or_default(); + let key = Value::String(MODELS.into()); + let mut new_item = item.clone(); + if models.is_empty() { + if !item.contains_key(&key) { + return Ok(text.to_string()); + } + new_item.remove(&key); + } else { + if item.get(&key) == Some(&value) { + return Ok(text.to_string()); + } + new_item.insert(key, value.clone()); + } + + let steps = PROVIDERS.steps(); + let mut at = steps.clone(); + at.push(Step::Index(index)); + let mut field = at.clone(); + field.push(Step::key(MODELS)); + let out = if tw_yaml::is_flow_at(text, &at)? { + // 行内写法里的键删不了、嵌套值塞不进去 —— 整项换成块式 + let block = render_block(&Value::Mapping(new_item.clone()))?; + tw_yaml::replace_item(text, &steps, index, &block)? + } else if models.is_empty() { + tw_yaml::remove_key(text, &field)? + } else { + put_value(text, &field, &value)? + }; + + // ── 语义核对 ───────────────────────────────────────────────────── + let mut expected = doc; + put_item(&mut expected, PROVIDERS, index, Value::Mapping(new_item)); + let got = parse(&out).map_err(|e| EditError::SelfCheck(e.to_string()))?; + if got != expected { + return Err(EditError::SelfCheck(format!( + "{} `{provider}` models", + PROVIDERS.what + ))); + } + Ok(out) +} + /// 文件里的别名表,按书写顺序。键一律当字符串(配置读进来时就是这么读的) fn alias_table(doc: &Value) -> Vec<(String, Value)> { let Some(Value::Mapping(m)) = doc.get(ALIASES) else { @@ -1426,4 +1491,82 @@ routes: [] let e = set_model_spec(CFG, "官方", "a\nb", Some(&spec(Some(1), None))).unwrap_err(); assert!(matches!(e, EditError::Multiline), "{e}"); } + + // ── 手动添加的模型 ─────────────────────────────────────────────── + + fn models_of(text: &str, provider: &str) -> Vec { + let cfg: crate::Config = serde_yaml_ng::from_str(text).unwrap(); + cfg.providers + .into_iter() + .find(|p| p.name == provider) + .unwrap() + .models + } + + fn owned(models: &[&str]) -> Vec { + models.iter().map(|m| m.to_string()).collect() + } + + /// 设、换、清空:这一家的其余字段和旁边的注释原样,清空之后文件回到原样 + #[test] + fn manual_models_are_set_replaced_and_cleared_without_touching_the_rest() { + // 要加引号的模型 ID 读回来还是它 + let odd = "us.anthropic.claude-fable-5-v1:0"; + let out = set_models(CFG, "官方", &owned(&["gpt-6-luna", odd])).unwrap(); + assert!( + out.contains("base_url: https://api.anthropic.com # 直连"), + "{out}" + ); + assert!(out.contains("# 两家上游"), "{out}"); + assert_eq!( + models_of(&out, "官方"), + [String::from("gpt-6-luna"), odd.into()] + ); + // 一样的清单:原样 + assert_eq!( + set_models(&out, "官方", &owned(&["gpt-6-luna", odd])).unwrap(), + out + ); + let out = set_models(&out, "官方", &owned(&[odd])).unwrap(); + assert_eq!(models_of(&out, "官方"), [odd]); + // 清空:`models` 整个不写;本来就没有的清空是原样 + let out = set_models(&out, "官方", &[]).unwrap(); + assert_eq!(out, CFG); + assert_eq!(set_models(CFG, "官方", &[]).unwrap(), CFG); + } + + /// 写成行内的上游整项换成块式,位置不变;行内的清单整个换掉 + #[test] + fn manual_models_go_into_an_inline_upstream_or_list_too() { + let out = set_models(CFG, "relay", &owned(&["m"])).unwrap(); + assert_eq!(models_of(&out, "relay"), ["m"]); + let cfg: crate::Config = serde_yaml_ng::from_str(&out).unwrap(); + assert_eq!(cfg.providers[1].base_url, "https://relay.example"); + assert_eq!(cfg.providers[0].name, "官方", "位置变了:{out}"); + let out = set_models(&out, "relay", &[]).unwrap(); + assert!(!out.contains("models"), "{out}"); + + let inline = CFG.replace(" key: sk-a\n", " key: sk-a\n models: [a, b]\n"); + let out = set_models(&inline, "官方", &owned(&["b", "c"])).unwrap(); + assert_eq!(models_of(&out, "官方"), ["b", "c"]); + let out = set_models(&inline, "官方", &[]).unwrap(); + assert_eq!(out, CFG); + } + + #[test] + fn manual_models_for_a_missing_upstream_or_with_a_line_break_are_refused() { + let e = set_models(CFG, "ghost", &owned(&["m"])).unwrap_err(); + assert!( + matches!( + e, + EditError::NotFound { + what: "upstream", + .. + } + ), + "{e}" + ); + let e = set_models(CFG, "官方", &owned(&["a\nb"])).unwrap_err(); + assert!(matches!(e, EditError::Multiline), "{e}"); + } } diff --git a/crates/tw-config/src/lib.rs b/crates/tw-config/src/lib.rs index 60fa46b5..a4042271 100644 --- a/crates/tw-config/src/lib.rs +++ b/crates/tw-config/src/lib.rs @@ -803,10 +803,14 @@ pub struct Provider { pub proxy: String, #[serde(default, skip_serializing_if = "is_default_on_proxy_fail")] pub on_proxy_fail: OnProxyFail, - /// 探测不到时的兜底清单。 + /// 手动添加的模型:**一律算这家提供**,和上游自己列出的合在一起(上游没给出清单时 + /// 就是全部)。 /// - /// 有些中转站没实现 `/v1/models`。**这是 provider 级的「这家有什么」, - /// 不是全局的「我们对外暴露什么」** —— 那个由汇总推导出来。 + /// 上游的清单不全是常事:ChatGPT 账号的后端对旧版本的客户端藏起新模型,中转站只列 + /// 一部分,有的中转站根本没实现 `/v1/models`。清单里没有、这里写了的模型照样列进 + /// `/v1/models`、照样路由到这家。**这是 provider 级的「这家有什么」,不是全局的 + /// 「我们对外暴露什么」** —— 那个由汇总推导出来;启用范围(`models_only`)照样管着 + /// 它们。每一项是一个确切的模型 ID,见 [`check_manual_models`] #[serde(default, skip_serializing_if = "Vec::is_empty")] pub models: Vec, /// 只用这家的这些模型:模型 ID 或 glob。不写就是它提供的全部。 @@ -845,6 +849,10 @@ pub struct Provider { /// 一家上游的并发上限最多写多少 pub const MAX_PROVIDER_CONCURRENCY: u32 = 1000; +/// 手动添加的一个模型 ID 最多多少个字符。最长的真名字是 Bedrock 应用推理配置的 ARN, +/// 一百来个字符 +pub const MANUAL_MODEL_MAX: usize = 256; + impl Provider { /// 这家的这个模型在不在启用范围里(`models_only`)。**不管这家到底 /// 有没有这个模型** —— 那要看模型目录。 @@ -1206,7 +1214,7 @@ pub use security::{ }; // Billing 在本文件里定义,这里不必再导出 pub use store::{Fingerprint, Loaded, StoreError, version_of}; -pub use validate::{check_aliases, check_model_spec, validate}; +pub use validate::{check_aliases, check_manual_models, check_model_spec, validate}; pub fn default_path() -> PathBuf { tw_api::data::dir().join("config.yaml") diff --git a/crates/tw-config/src/validate.rs b/crates/tw-config/src/validate.rs index 3d74cf6d..622915a4 100644 --- a/crates/tw-config/src/validate.rs +++ b/crates/tw-config/src/validate.rs @@ -104,6 +104,17 @@ pub enum ValidationError { #[error("{}", self.msg())] AliasOnlyItself { alias: String }, #[error("{}", self.msg())] + ManualModelBlank { upstream: String }, + #[error("{}", self.msg())] + ManualModelPadded { upstream: String, model: String }, + #[error("{}", self.msg())] + ManualModelWildcard { upstream: String, model: String }, + #[error("{}", self.msg())] + ManualModelDuplicate { upstream: String, model: String }, + /// 太长的那个 ID 不进句子:几百个字符的一串放进提示里,比说「太长」更看不清 + #[error("{}", self.msg())] + ManualModelTooLong { upstream: String }, + #[error("{}", self.msg())] ModelSpecBlankModel { upstream: String }, #[error("{}", self.msg())] ModelSpecWildcard { upstream: String, model: String }, @@ -348,6 +359,30 @@ impl ValidationError { "alias `{alias}` lists only itself, so it changes nothing. List the names the \ upstreams use, or remove the alias" ), + ManualModelBlank { upstream } => msg!( + "config.manual_model_blank", upstream = upstream => + "upstream `{upstream}` has an empty entry among the models added by hand (models)" + ), + ManualModelPadded { upstream, model } => msg!( + "config.manual_model_padded", upstream = upstream, model = model => + "the model `{model}` added by hand to upstream `{upstream}` begins or ends with \ + whitespace. Write the model id without it" + ), + ManualModelWildcard { upstream, model } => msg!( + "config.manual_model_wildcard", upstream = upstream, model = model => + "the model `{model}` added by hand to upstream `{upstream}` contains * or ?. A \ + model added by hand is one exact model id; to use only some of an upstream's \ + models, set its scope (models_only)" + ), + ManualModelDuplicate { upstream, model } => msg!( + "config.manual_model_duplicate", upstream = upstream, model = model => + "the model `{model}` is added by hand to upstream `{upstream}` more than once" + ), + ManualModelTooLong { upstream } => msg!( + "config.manual_model_too_long", upstream = upstream, + max = crate::MANUAL_MODEL_MAX => + "a model added by hand to upstream `{upstream}` is longer than {max} characters" + ), ModelSpecBlankModel { upstream } => msg!( "config.model_spec_blank_model", upstream = upstream => "upstream `{upstream}` has a model spec (model_specs) for an empty model id" @@ -484,6 +519,7 @@ pub fn validate(cfg: &Config) -> Result<(), ValidationError> { }); } } + check_manual_models(&p.name, &p.models)?; for (model, spec) in &p.model_specs { check_model_spec(&p.name, model, Some(spec))?; } @@ -794,6 +830,41 @@ pub fn check_aliases(aliases: &crate::Aliases) -> Result<(), ValidationError> { /// 一家上游的一项手写模型规格写得对不对,和整份配置的校验是同一套(控制面保存一项 /// 之前也用它)。`spec` 是 `None` 时只查模型 ID:界面要删掉这一项。**模型在不在这家的 /// 清单里不查**:清单是运行时问来的。 +/// 一家上游手动添加的模型(`models`)写得对不对:每一项是一个确切的模型 ID —— 不空、 +/// 首尾没有空白、不带通配、不超过 [`crate::MANUAL_MODEL_MAX`] 个字符 —— 而且不重复。 +/// +/// 配置的校验和控制面设清单的端点用的是同一份:端点先去掉首尾空白再交过来。 +pub fn check_manual_models(upstream: &str, models: &[String]) -> Result<(), ValidationError> { + let named = |model: &str| (upstream.to_string(), model.to_string()); + let mut seen = std::collections::HashSet::new(); + for model in models { + if model.trim().is_empty() { + return Err(ValidationError::ManualModelBlank { + upstream: upstream.to_string(), + }); + } + if model.trim() != model { + let (upstream, model) = named(model); + return Err(ValidationError::ManualModelPadded { upstream, model }); + } + if model.chars().count() > crate::MANUAL_MODEL_MAX { + return Err(ValidationError::ManualModelTooLong { + upstream: upstream.to_string(), + }); + } + // `gpt-*` 写在这里,读的人会以为一批模型都加上了 —— 而它只是一个叫 `gpt-*` 的名字 + if model.contains(['*', '?']) { + let (upstream, model) = named(model); + return Err(ValidationError::ManualModelWildcard { upstream, model }); + } + if !seen.insert(model.as_str()) { + let (upstream, model) = named(model); + return Err(ValidationError::ManualModelDuplicate { upstream, model }); + } + } + Ok(()) +} + pub fn check_model_spec( upstream: &str, model: &str, @@ -924,6 +995,44 @@ mod tests { assert!(validate(&cfg(vec![c("d", "tw-1")], vec![p("r", "https://x.com")])).is_ok()); } + #[test] + fn models_added_by_hand_are_exact_ids_written_once() { + let parse = |models: &str| { + crate::try_parse(&format!( + "version: 1\nlisten:\n control:\n key: {}\nclients:\n - name: c\n key: tw-k\nproviders:\n - name: relay\n base_url: https://relay.example.com/v1\n models: {models}\n", + "c0".repeat(32) + )) + }; + let ok = parse("[gpt-6-luna, \"us.anthropic.claude-fable-5-v1:0\"]").unwrap(); + assert_eq!( + ok.providers[0].models, + ["gpt-6-luna", "us.anthropic.claude-fable-5-v1:0"] + ); + let long = "m".repeat(crate::MANUAL_MODEL_MAX + 1); + for (models, code) in [ + ("[\"\"]", "config.manual_model_blank"), + ("[\" \"]", "config.manual_model_blank"), + ("[\" gpt-6\"]", "config.manual_model_padded"), + ("[gpt-*]", "config.manual_model_wildcard"), + ("[gpt-6, gpt-6]", "config.manual_model_duplicate"), + (long.as_str(), "config.manual_model_too_long"), + ] { + let models = if models.starts_with('[') { + models.to_string() + } else { + format!("[{models}]") + }; + let m = parse(&models).unwrap_err().msg(); + assert_eq!(m.code, code, "{models}: {m:?}"); + assert_eq!(m.arg("upstream"), "relay", "{m:?}"); + } + // 正好那么长的可以 + let longest = "m".repeat(crate::MANUAL_MODEL_MAX); + assert!(parse(&format!("[{longest}]")).is_ok()); + let m = parse("[gpt-6, gpt-6]").unwrap_err().msg(); + assert_eq!(m.arg("model"), "gpt-6"); + } + #[test] fn model_specs_name_one_exact_model_and_set_a_positive_number() { let parse = |specs: &str| { diff --git a/crates/tw-config/tests/manual/schema.rs b/crates/tw-config/tests/manual/schema.rs index 8d162cb6..ed18514e 100644 --- a/crates/tw-config/tests/manual/schema.rs +++ b/crates/tw-config/tests/manual/schema.rs @@ -593,8 +593,8 @@ pub fn sections() -> Vec
{ Kind::Strs, Def::Is("[]"), t( - "Models to assume when the upstream does not answer `/v1/models`.", - "上游不支持 `/v1/models` 时,按这份清单认定它提供的模型。", + "Models added by hand, by exact id, for those the upstream serves but leaves out of its list. They count as offered together with the models the upstream lists, or are the whole list when it lists none: they appear in `/v1/models` and requests for them are routed here. `models_only` still applies. No wildcards, no duplicates, at most 256 characters each.", + "手动添加的模型,写确切的 ID:上游能服务、却没有列进清单的模型。它们和上游列出的模型一起算作这家提供的模型,上游不提供清单时就是全部:出现在 `/v1/models` 里,相应的请求也会路由到这家。`models_only` 照样适用。不支持通配,不能重复,每项最多 256 个字符。", ), ), row( diff --git a/crates/tw-control/src/diagnostics.rs b/crates/tw-control/src/diagnostics.rs index a1c19fd7..34bb66e0 100644 --- a/crates/tw-control/src/diagnostics.rs +++ b/crates/tw-control/src/diagnostics.rs @@ -138,12 +138,20 @@ pub async fn bundle(State(s): State) -> Result 0 => format!( + "{served} (upstream offers {}, {added} added by hand{scope})", + l.listed.len() + ), tw_gateway::models::Source::Discovered => { format!("{served} (upstream offers {}{scope})", l.models.len()) } tw_gateway::models::Source::Manual => { - format!("{served} (manual list of {}{scope})", l.models.len()) + format!( + "{served} ({} added by hand, no list from the upstream{scope})", + l.models.len() + ) } tw_gateway::models::Source::None => match &l.error { Some(why) => format!("unknown: {why}"), diff --git a/crates/tw-control/src/resources.rs b/crates/tw-control/src/resources.rs index b3ed9477..7c729f2d 100644 --- a/crates/tw-control/src/resources.rs +++ b/crates/tw-control/src/resources.rs @@ -36,6 +36,7 @@ pub fn router() -> axum::Router { .at(ep::DeleteProvider, delete_provider) .at(ep::ProviderModels, provider_models) .at(ep::SetModelSpec, set_model_spec) + .at(ep::SetManualModels, set_manual_models) .at(ep::RefreshProviderModels, refresh_models) .at(ep::RefreshStaleModels, refresh_stale_models) .at(ep::CreateProxy, create_proxy) @@ -182,6 +183,31 @@ async fn set_model_spec( Ok(Json(tw_api::ConfigWritten { version })) } +/// 换掉一家上游手动添加的模型:整份清单,按给的顺序;空的就是清掉。 +/// +/// **只动这一家的 `models`**([`edit::set_models`]),理由同 [`set_model_spec`]。每一项先 +/// 去掉首尾空白,再按整份配置的校验查一遍([`tw_config::check_manual_models`]),好让它说的 +/// 是这一项,而不是写进去之后被拒。写完由重载重算模型汇总:新加的马上出现在列表里、 +/// 路由得到,不用重新向上游问。 +async fn set_manual_models( + State(s): State, + Json(req): Json, +) -> Result, Fail> { + let models: Vec = req.models.iter().map(|m| m.trim().to_string()).collect(); + let version = s + .cfg + .transform(req.base_version.as_deref(), Origin::Ui, |text, cfg| { + if !cfg.providers.iter().any(|p| p.name == req.provider) { + return Err(not_found("upstream", &req.provider)); + } + tw_config::check_manual_models(&req.provider, &models).map_err(|e| invalid(e.msg()))?; + Ok(edit::set_models(text, &req.provider, &models)?) + }) + .await + .map_err(apply_fail)?; + Ok(Json(tw_api::ConfigWritten { version })) +} + /// 按接口地址自动识别会得到什么:协议、是不是官方端点、默认脱敏哪几类。 /// /// **不联网,只看地址。**编辑对话框在用户输入地址时调它,好让「自动识别」 @@ -334,6 +360,8 @@ fn models_view( let book = s.gateway.pricing.load(); let date = &book.table().date; let cfg = s.config(); + let listed: std::collections::HashSet<&str> = + listing.listed.iter().map(String::as_str).collect(); tw_api::ProviderModelsView { provider: p.name.clone(), source: listing.source.into(), @@ -364,6 +392,8 @@ fn models_view( price_source: r.as_ref().map(|r| tw_store::price_source(&r.source, date)), estimated: r.as_ref().is_some_and(|r| r.cross_platform), aliases: crate::routes::aliases_listing(&cfg, &id), + manual: p.models.contains(&id), + listed: listed.contains(id.as_str()), id, } }) diff --git a/crates/tw-control/tests/manual_models.rs b/crates/tw-control/tests/manual_models.rs new file mode 100644 index 00000000..d5d3dbe4 --- /dev/null +++ b/crates/tw-control/tests/manual_models.rs @@ -0,0 +1,377 @@ +//! 手动添加的模型:上游的清单里没有、配置里写进 `models` 的模型。上游页的模型清单说出 +//! 哪些是手动添加的、哪些上游自己也列了,`PUT /provider-manual-models` 设整份、清空, +//! 模型列表和试算把它们当作列出的模型;上游不给清单时它们就是全部,启用范围照样管着。 + +use std::sync::Arc; + +use axum::body::Body; +use axum::http::{Request, StatusCode}; +use serde_json::{Value, json}; +use tower::ServiceExt; +use tw_control::{ConfigManager, ControlState}; + +struct Bed { + dir: tempfile::TempDir, + app: axum::Router, +} + +impl Bed { + fn file(&self) -> String { + std::fs::read_to_string(self.dir.path().join("config.yaml")).unwrap() + } +} + +fn bed(yaml: &str) -> Bed { + let d = tempfile::tempdir().unwrap(); + let p = d.path().join("config.yaml"); + std::fs::write(&p, yaml).unwrap(); + let cfg = tw_config::try_parse(yaml).unwrap(); + let gw = tw_gateway::AppState::new(cfg).unwrap(); + let bus = gw.bus.clone(); + let state = ControlState { + shutdown: Default::default(), + remote: Default::default(), + cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus)), + gateway: gw, + store: None, + started: std::time::Instant::now(), + price_updater: Default::default(), + chatgpt: Default::default(), + zai: Default::default(), + }; + Bed { + app: tw_control::router(state), + dir: d, + } +} + +async fn call(app: &axum::Router, method: &str, path: &str, body: Value) -> (StatusCode, Value) { + let r = app + .clone() + .oneshot( + Request::builder() + .method(method) + .uri(path) + .header("content-type", "application/json") + .body(Body::from(body.to_string())) + .unwrap(), + ) + .await + .unwrap(); + let st = r.status(); + let b = axum::body::to_bytes(r.into_body(), 1 << 20).await.unwrap(); + let text = String::from_utf8_lossy(&b).to_string(); + let v = serde_json::from_str(&text).unwrap_or(Value::String(text)); + (st, v) +} + +/// 一个假上游:认 `sk-good`,列出两个模型。 +async fn upstream() -> std::net::SocketAddr { + let app = axum::Router::new().route( + "/v1/models", + axum::routing::get(|h: axum::http::HeaderMap| async move { + if h.get("x-api-key").and_then(|v| v.to_str().ok()) != Some("sk-good") { + return (StatusCode::UNAUTHORIZED, "{}".to_string()); + } + ( + StatusCode::OK, + r#"{"data":[{"id":"claude-sonnet-4-5"},{"id":"claude-haiku-4-5"}]}"#.to_string(), + ) + }), + ); + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let a = l.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(l, app).await.unwrap() }); + a +} + +/// `relay` 那一项后面接 `extra`(缩进四格的字段),整份配置后面接 `tail` +fn config(up: std::net::SocketAddr, key: &str, extra: &str, tail: &str) -> String { + format!( + "version: 1 +listen: + control: + key: c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00 +clients: + - name: c + key: tw-k +providers: + - name: relay + base_url: http://{up} + key: {key} + protocol: anthropic +{extra}{tail}" + ) +} + +/// 向上游问一遍,交回整个清单视图 +async fn refreshed(b: &Bed) -> Value { + let (st, v) = call( + &b.app, + "POST", + "/providers/relay/models/refresh", + Value::Null, + ) + .await; + assert_eq!(st, StatusCode::OK, "{v}"); + v +} + +/// 不问上游,读 core 记下的清单 +async fn current(b: &Bed) -> Value { + let (st, v) = call(&b.app, "GET", "/providers/relay/models", Value::Null).await; + assert_eq!(st, StatusCode::OK, "{v}"); + v +} + +fn ids(view: &Value) -> Vec { + view["models"] + .as_array() + .unwrap() + .iter() + .map(|m| m["id"].as_str().unwrap().to_string()) + .collect() +} + +fn row<'a>(view: &'a Value, id: &str) -> &'a Value { + view["models"] + .as_array() + .unwrap() + .iter() + .find(|m| m["id"] == id) + .unwrap_or_else(|| panic!("no row {id}: {view}")) +} + +async fn dry_run(b: &Bed, model: &str) -> Value { + let (st, v) = call( + &b.app, + "POST", + "/dryrun", + json!({ "model": model, "client": "c" }), + ) + .await; + assert_eq!(st, StatusCode::OK, "{v}"); + v +} + +async fn known(b: &Bed) -> Vec { + let (st, v) = call(&b.app, "GET", "/models", Value::Null).await; + assert_eq!(st, StatusCode::OK, "{v}"); + v.as_array() + .unwrap() + .iter() + .map(|m| m["id"].as_str().unwrap().to_string()) + .collect() +} + +async fn set(b: &Bed, body: Value) -> (StatusCode, Value) { + call(&b.app, "PUT", "/provider-manual-models", body).await +} + +#[tokio::test] +async fn each_row_says_whether_it_was_added_by_hand_and_whether_the_upstream_lists_it() { + let up = upstream().await; + let b = bed(&config( + up, + "sk-good", + " models: [gpt-6-luna, claude-haiku-4-5]\n", + "aliases:\n luna: gpt-6-luna\n", + )); + let v = refreshed(&b).await; + assert_eq!(v["source"], "discovered", "{v}"); + // 上游列出的在前,手动添加的接在后面;两边都有的只算一次 + assert_eq!( + ids(&v), + ["claude-sonnet-4-5", "claude-haiku-4-5", "gpt-6-luna"] + ); + let flags = |id: &str| { + let r = row(&v, id); + ( + r["manual"].clone(), + r["listed"].clone(), + r["enabled"].clone(), + ) + }; + assert_eq!( + flags("claude-sonnet-4-5"), + (json!(false), json!(true), json!(true)) + ); + assert_eq!( + flags("claude-haiku-4-5"), + (json!(true), json!(true), json!(true)) + ); + assert_eq!( + flags("gpt-6-luna"), + (json!(true), json!(false), json!(true)) + ); + assert_eq!(row(&v, "gpt-6-luna")["aliases"], json!(["luna"])); + + // 模型列表、概览的个数、试算都把它当作这家的模型 + let (_, ov) = call(&b.app, "GET", "/overview", Value::Null).await; + assert_eq!(ov["providers"][0]["model_count"], 3, "{ov}"); + assert_eq!( + ov["providers"][0]["models"], + json!(["gpt-6-luna", "claude-haiku-4-5"]) + ); + let models = known(&b).await; + assert!(models.iter().any(|m| m == "gpt-6-luna"), "{models:?}"); + assert!(models.iter().any(|m| m == "luna"), "{models:?}"); + let d = dry_run(&b, "gpt-6-luna").await; + assert_eq!(d["outcome"], "route", "{d}"); + assert_eq!(d["candidates"], json!(["relay"])); + let d = dry_run(&b, "luna").await; + assert_eq!(d["outcome"], "route", "{d}"); + assert_eq!(d["candidates"], json!(["relay"])); +} + +#[tokio::test] +async fn the_endpoint_sets_and_clears_the_models_added_by_hand() { + let up = upstream().await; + let b = bed(&config(up, "sk-good", "", "")); + let before = b.file(); + let v = refreshed(&b).await; + assert!( + v["models"] + .as_array() + .unwrap() + .iter() + .all(|m| m["manual"] == false), + "{v}" + ); + assert_eq!(dry_run(&b, "gpt-6-luna").await["outcome"], "unavailable"); + + // 去掉首尾空白;上游也列了的可以加 + let (st, w) = set( + &b, + json!({ "provider": "relay", "models": [" gpt-6-luna ", "claude-haiku-4-5"] }), + ) + .await; + assert_eq!(st, StatusCode::OK, "{w}"); + assert!(w["version"].as_str().is_some(), "{w}"); + let cfg = tw_config::try_parse(&b.file()).unwrap(); + assert_eq!( + cfg.providers[0].models, + ["gpt-6-luna", "claude-haiku-4-5"], + "{}", + b.file() + ); + // 马上就在清单里,不用重新向上游问 + let v = current(&b).await; + assert_eq!(v["source"], "discovered", "{v}"); + let luna = row(&v, "gpt-6-luna"); + assert_eq!( + (&luna["manual"], &luna["listed"]), + (&json!(true), &json!(false)) + ); + let d = dry_run(&b, "gpt-6-luna").await; + assert_eq!(d["outcome"], "route", "{d}"); + assert!(known(&b).await.iter().any(|m| m == "gpt-6-luna")); + + // 换成一份更短的:拿掉的那个不在了 + let (st, w) = set(&b, json!({ "provider": "relay", "models": ["gpt-6-luna"] })).await; + assert_eq!(st, StatusCode::OK, "{w}"); + let v = current(&b).await; + assert_eq!(row(&v, "claude-haiku-4-5")["manual"], false); + + // 清空:文件回到原样,回到只认上游的清单 + let (st, w) = set(&b, json!({ "provider": "relay", "models": [] })).await; + assert_eq!(st, StatusCode::OK, "{w}"); + assert_eq!(b.file(), before); + let v = current(&b).await; + assert_eq!(ids(&v), ["claude-sonnet-4-5", "claude-haiku-4-5"]); + let d = dry_run(&b, "gpt-6-luna").await; + assert_eq!(d["outcome"], "unavailable", "{d}"); + assert!(!known(&b).await.iter().any(|m| m == "gpt-6-luna")); + + // 基于旧版本的保存被拒 + let (st, _) = set( + &b, + json!({ "provider": "relay", "models": ["m"], "base_version": "nope" }), + ) + .await; + assert_eq!(st, StatusCode::CONFLICT); + assert_eq!(b.file(), before); +} + +#[tokio::test] +async fn a_bad_model_added_by_hand_is_refused_in_the_configurations_words() { + let up = upstream().await; + let b = bed(&config(up, "sk-good", "", "")); + let before = b.file(); + let long = "m".repeat(257); + for (models, status, code) in [ + ( + json!([""]), + StatusCode::BAD_REQUEST, + "config.manual_model_blank", + ), + ( + json!([" "]), + StatusCode::BAD_REQUEST, + "config.manual_model_blank", + ), + ( + json!(["gpt-*"]), + StatusCode::BAD_REQUEST, + "config.manual_model_wildcard", + ), + // 去掉空白之后重复 + ( + json!(["gpt-6", " gpt-6 "]), + StatusCode::BAD_REQUEST, + "config.manual_model_duplicate", + ), + ( + json!([long]), + StatusCode::BAD_REQUEST, + "config.manual_model_too_long", + ), + ( + json!(["a\nb"]), + StatusCode::BAD_REQUEST, + "config.edit.multiline", + ), + ] { + let (st, v) = set(&b, json!({ "provider": "relay", "models": models })).await; + assert_eq!(st, status, "{models}: {v}"); + assert_eq!(v["code"], code, "{models}: {v}"); + assert_eq!(b.file(), before); + } + let (st, v) = set(&b, json!({ "provider": "ghost", "models": ["m"] })).await; + assert_eq!(st, StatusCode::NOT_FOUND, "{v}"); + assert_eq!(v["code"], "config.edit.not_found", "{v}"); + assert_eq!(b.file(), before); +} + +/// 上游不给清单(这里是密钥被拒):手动添加的就是全部,照样标着;启用范围照样管着它们 +#[tokio::test] +async fn without_a_list_from_the_upstream_the_models_added_by_hand_are_the_whole_list() { + let up = upstream().await; + let b = bed(&config( + up, + "sk-bad", + " models: [手写的模型, gpt-6-luna]\n models_only: [gpt-*]\n", + "", + )); + let v = refreshed(&b).await; + assert_eq!(v["source"], "manual", "{v}"); + assert_eq!(v["status"], "failed", "{v}"); + assert_eq!(ids(&v), ["手写的模型", "gpt-6-luna"]); + for id in ["手写的模型", "gpt-6-luna"] { + let r = row(&v, id); + assert_eq!( + (&r["manual"], &r["listed"]), + (&json!(true), &json!(false)), + "{r}" + ); + } + assert_eq!(row(&v, "手写的模型")["enabled"], false); + assert_eq!(row(&v, "gpt-6-luna")["enabled"], true); + + let d = dry_run(&b, "gpt-6-luna").await; + assert_eq!(d["outcome"], "route", "{d}"); + // 范围外的手动模型不列、不路由 + assert!(!known(&b).await.iter().any(|m| m == "手写的模型")); + let d = dry_run(&b, "手写的模型").await; + assert_ne!(d["outcome"], "route", "{d}"); +} diff --git a/crates/tw-gateway/src/models.rs b/crates/tw-gateway/src/models.rs index 2473f664..2c289297 100644 --- a/crates/tw-gateway/src/models.rs +++ b/crates/tw-gateway/src/models.rs @@ -1,6 +1,11 @@ -//! 每个上游提供哪些模型:向上游要来的、配置里手写的,以及它们是什么时候、 +//! 每个上游提供哪些模型:向上游要来的、配置里手动添加的,以及它们是什么时候、 //! 怎么来的。 //! +//! **手动添加的模型(配置里的 `models`)一律算这家提供**,和上游列出的合在一起; +//! 上游没给出清单时它们就是全部。上游的清单不全是常事 —— ChatGPT 账号的后端对旧版本 +//! 的客户端藏起新模型,中转站只列一部分 —— 而清单是准入和挑候选的依据:只认清单的话, +//! 清单里漏掉的模型就到不了一家明明能服务它的上游。 +//! //! # 两份东西 //! //! - **目录([`Directory`])**记每个上游的原始答案:列出了什么、上次什么时候 @@ -47,7 +52,7 @@ const TICK: Duration = Duration::from_secs(10 * 60); pub enum Source { /// 上游自己列出来的 Discovered, - /// 上游没给出清单,用配置里手写的 `models` + /// 上游没给出清单,用配置里手动添加的 `models` Manual, /// 都没有。**不知道它有什么**,不是它什么都没有 None, @@ -64,7 +69,7 @@ impl Source { } /// 最近一次向上游问的结果。**和 [`Source`] 不是一回事**:没问到时清单可能 -/// 来自手写的兜底(`Manual`),而界面要说的是「问了,没问到,为什么」。 +/// 来自手动添加的那些(`Manual`),而界面要说的是「问了,没问到,为什么」。 #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Status { /// 还没问过:刚启动、刚加的、刚改了地址或凭据。停用的上游一直是这样 —— @@ -98,8 +103,11 @@ pub struct Listing { /// 正在向上游问。**和 `status` 同时成立**:上一次的答案照常可用, /// 新答案回来之前不作废 pub fetching: bool, - /// 清单本身。**还没按启用范围过滤** + /// 清单本身:上游列出的,后面接上手动添加的(上游也列了的不重复)。**还没按启用 + /// 范围过滤** pub models: Vec, + /// 其中上游自己列出的。上游没给出清单时是空的 + pub listed: Vec, /// 最近一次向上游问的时间。还没问过是空 pub checked_at_ms: Option, /// 没从上游拿到清单的原因 @@ -345,21 +353,24 @@ fn listing_of(entry: Option<&Entry>, p: &tw_config::Provider) -> Listing { Some(Answer::Failed(_)) => Status::Failed, }; match entry.map(|e| &e.answer) { - Some(Answer::Listed(models)) => Listing { + // 上游列出的在前,手动添加的接在后面。**删得掉的只有手动添加的那些**:上游列出 + // 的模型不该用的话,用启用范围把它排除在外 + Some(Answer::Listed(listed)) => Listing { source: Source::Discovered, status, fetching, - models: models.clone(), + models: with_manual(listed, &p.models), + listed: listed.clone(), checked_at_ms, error: None, }, - // 问不到就用手写的兜底。**两者不合并** —— 合并的话,用户删掉一个 - // 上游不再提供的模型时会发现它删不掉 + // 问不到:手动添加的就是全部 _ if !p.models.is_empty() => Listing { source: Source::Manual, status, fetching, - models: p.models.clone(), + models: with_manual(&[], &p.models), + listed: Vec::new(), checked_at_ms, error, }, @@ -368,12 +379,25 @@ fn listing_of(entry: Option<&Entry>, p: &tw_config::Provider) -> Listing { status, fetching, models: Vec::new(), + listed: Vec::new(), checked_at_ms, error, }, } } +/// 上游列出的 `listed`,后面接上手动添加的 `manual` 里它没列的,各自的顺序不变。 +fn with_manual(listed: &[String], manual: &[String]) -> Vec { + let mut seen: std::collections::HashSet<&str> = listed.iter().map(String::as_str).collect(); + let mut out = listed.to_vec(); + for m in manual { + if seen.insert(m.as_str()) { + out.push(m.clone()); + } + } + out +} + /// 问一家上游有哪些模型。 async fn ask(state: &AppState, rt: &Runtime, p: &tw_config::Provider) -> Answer { // 用这一家自己的 client:它带着该走的代理,换 OAuth token 也要走那条路 @@ -1271,6 +1295,81 @@ mod tests { assert_eq!(d.listing(&fresh).status, Status::Listed); } + /// 手动添加的模型和上游列出的合在一起:上游列出的在前,都有的只算一次;汇总里它和 + /// 列出的一样算这家提供 —— 按名称要、经过别名、规则指定都到得了这家。启用范围照样管着 + /// 它;从配置里拿掉之后回到只认上游的清单 + #[test] + fn models_added_by_hand_join_the_listed_ones_and_count_as_offered() { + let d = Directory::default(); + let mut c = cfg(vec![provider("chatgpt"), provider("relay")]); + c.providers[0].models = vec!["gpt-6-luna".into(), "gpt-5".into()]; + c.aliases = serde_yaml_ng::from_str("luna: [gpt-6-luna]\n").unwrap(); + d.reconcile(&c); + for p in &c.providers { + d.record( + &p.name, + &identity(&c, p), + Answer::Listed(vec!["gpt-5".into(), "gpt-5-mini".into()]), + 1, + ); + } + let l = d.listing(&c.providers[0]); + assert_eq!(l.source, Source::Discovered); + assert_eq!(l.models, ["gpt-5", "gpt-5-mini", "gpt-6-luna"]); + assert_eq!(l.listed, ["gpt-5", "gpt-5-mini"]); + + let cat = published(&d, &c); + assert_eq!(cat.offers("chatgpt", "gpt-6-luna"), Some(true)); + assert_eq!(cat.offers("relay", "gpt-6-luna"), Some(false)); + assert_eq!(cat.providers_for("gpt-6-luna"), ["chatgpt"]); + assert_eq!(cat.providers_for("luna"), ["chatgpt"]); + assert_eq!(cat.count_for("chatgpt"), 3); + let both = ["chatgpt", "relay"]; + // 按名称要 + let s = serving(&c, &cat, &decided(&[]), &asked(&both, "gpt-6-luna"), None); + assert_eq!(s.usable, ["chatgpt"]); + assert_eq!(s.skipped, [("relay".to_string(), Skip::NotOffered)]); + // 经过别名 + let s = serving(&c, &cat, &decided(&[]), &asked(&both, "luna"), None); + assert_eq!(s.usable, ["chatgpt"]); + assert_eq!( + sent_to(&c, &cat, &decided(&[]), &c.providers[0], "luna"), + Ok("gpt-6-luna".into()) + ); + // 规则指定 + let pinned = decided(&[("chatgpt", "gpt-6-luna")]); + let s = serving( + &c, + &cat, + &pinned, + &[("chatgpt".into(), "gpt-6-luna".into())], + None, + ); + assert_eq!(s.usable, ["chatgpt"]); + + // 启用范围照样管着手动添加的 + let mut scoped = c.clone(); + scoped.providers[0].models_only = Some(vec!["gpt-5*".into()]); + let cat = published(&d, &scoped); + assert_eq!(cat.offers("chatgpt", "gpt-6-luna"), Some(false)); + assert_eq!( + fit(&cat, &scoped.providers[0], "gpt-6-luna"), + Some(Skip::OutOfScope) + ); + + // 拿掉:只认上游的清单,不用重问 + c.providers[0].models.clear(); + assert!(!d.reconcile(&c)); + let cat = published(&d, &c); + assert_eq!(d.listing(&c.providers[0]).models, ["gpt-5", "gpt-5-mini"]); + assert_eq!(cat.offers("chatgpt", "gpt-6-luna"), Some(false)); + assert!(cat.providers_for("luna").is_empty()); + assert_eq!( + fit(&cat, &c.providers[0], "gpt-6-luna"), + Some(Skip::NotOffered) + ); + } + #[test] fn a_failure_with_a_manual_list_says_both() { let d = Directory::default(); @@ -1287,6 +1386,7 @@ mod tests { // 清单来自手写的兜底,但「问了、没问到、为什么」一样要说 assert_eq!((l.source, l.status), (Source::Manual, Status::Failed)); assert_eq!(l.models, ["手写"]); + assert!(l.listed.is_empty()); assert_eq!(l.error.as_ref().map(|m| m.text.as_str()), Some("密钥被拒")); } } diff --git a/crates/tw-gateway/tests/models.rs b/crates/tw-gateway/tests/models.rs index b138eca1..6bbabd29 100644 --- a/crates/tw-gateway/tests/models.rs +++ b/crates/tw-gateway/tests/models.rs @@ -12,6 +12,16 @@ use tw_config::{Client, Config, Provider}; /// 一个假上游:列出 `models`,只接受这些模型的请求,其余回 404。 async fn upstream(name: &'static str, models: &'static [&'static str]) -> SocketAddr { + hiding(name, models, &[]).await +} + +/// 一个清单不全的假上游:列出 `models`,`hidden` 不列,却照样服务 —— ChatGPT 账号的后端 +/// 对旧版本的客户端就是这样藏起新模型的。 +async fn hiding( + name: &'static str, + models: &'static [&'static str], + hidden: &'static [&'static str], +) -> SocketAddr { let app = Router::new() .route( "/v1/models", @@ -26,7 +36,7 @@ async fn upstream(name: &'static str, models: &'static [&'static str]) -> Socket post(move |body: axum::body::Bytes| async move { let v: serde_json::Value = serde_json::from_slice(&body).unwrap_or_default(); let model = v["model"].as_str().unwrap_or_default().to_string(); - if models.contains(&model.as_str()) { + if models.contains(&model.as_str()) || hidden.contains(&model.as_str()) { // 收到的模型名放在 `sent` 里:回答里的 `model` 会被网关写回客户端用的名称 // (见 `tw_gateway::answer_model`),看不出发出去的是哪个 ( @@ -290,6 +300,74 @@ async fn when_no_candidate_serves_the_model_the_error_names_each_one_and_why() { assert!(msg.contains("No upstream serves model"), "{msg}"); } +// ─────────────────────────────────────────────────────────── 手动添加的模型 + +/// 上游的清单里没有、手动添加了的模型:列进 `/v1/models`,按名称要、经过别名、规则指定都 +/// 送到这家(排在前面、清单里也没有它的那一家跳过);拿掉之后回到只认清单 +#[tokio::test] +async fn a_model_added_by_hand_is_listed_and_routed_like_a_listed_one() { + let relay = upstream("relay", &["gpt-5"]).await; + let account = hiding("account", &["gpt-5"], &["gpt-6-luna"]).await; + let mut cfg = grouped( + config(vec![provider("relay", relay), provider("account", account)]), + &["relay", "account"], + ); + cfg.providers[1].models = vec!["gpt-6-luna".into()]; + cfg.aliases = serde_yaml_ng::from_str("luna: gpt-6-luna\n").unwrap(); + let state = tw_gateway::AppState::new(cfg.clone()).unwrap(); + tw_gateway::models::refresh_all(&state).await; + let gw = serve(state.clone()).await; + + assert_eq!(listed(gw).await, ["gpt-5", "gpt-6-luna", "luna"]); + let (status, body) = ask(gw, "gpt-6-luna").await; + assert_eq!(status, 200, "{body}"); + assert_eq!(body["by"], "account"); + let (status, body) = ask(gw, "luna").await; + assert_eq!(status, 200, "{body}"); + assert_eq!( + (&body["by"], &body["sent"]), + (&"account".into(), &"gpt-6-luna".into()) + ); + // 列出的照旧按组里的顺序 + let (_, body) = ask(gw, "gpt-5").await; + assert_eq!(body["by"], "relay"); + + // 规则指定这家的这个模型 + let mut pinned = cfg.clone(); + let rule: tw_engine::Rule = + serde_yaml_ng::from_str("name: 指定\nto:\n - { provider: account, model: gpt-6-luna }\n") + .unwrap(); + pinned.routes = vec![tw_engine::RouteSet::default_with(vec![rule])]; + state.reload(pinned.clone()).unwrap(); + let (status, body) = ask(gw, "gpt-5").await; + assert_eq!(status, 200, "{body}"); + assert_eq!( + (&body["by"], &body["sent"]), + (&"account".into(), &"gpt-6-luna".into()) + ); + + // 启用范围照样管着它 + let mut scoped = cfg.clone(); + scoped.providers[1].models_only = Some(vec!["gpt-5".into()]); + state.reload(scoped).unwrap(); + assert_eq!(listed(gw).await, ["gpt-5"]); + let (status, body) = ask(gw, "gpt-6-luna").await; + assert_eq!(status, 400, "{body}"); + + // 拿掉:清单里没有,就到不了这家。不用重新向上游问 + let mut removed = pinned; + removed.providers[1].models.clear(); + state.reload(removed).unwrap(); + assert_eq!(listed(gw).await, ["gpt-5"]); + let (status, body) = ask(gw, "gpt-5").await; + assert_eq!(status, 400, "{body}"); + let msg = body["error"]["message"].as_str().unwrap(); + assert!( + msg.contains("do not offer") && msg.contains("account (gpt-6-luna)"), + "{msg}" + ); +} + // ─────────────────────────────────────────────────────────── 改写模型 /// 把请求交给 `to`、并把模型改写成 `model` 的一条规则。 diff --git a/docs/config.md b/docs/config.md index 01c93867..fae4f75f 100644 --- a/docs/config.md +++ b/docs/config.md @@ -398,7 +398,7 @@ Upstreams: the APIs requests are forwarded to. | `forward_client_identity` | bool | `false` | Also send the client's own identity: its `User-Agent`, identity headers such as `x-app` and `originator`, and identity fields in the request body such as `metadata.user_id`. Values are the client's, never made up. Off: requests carry ThinkWatch's `User-Agent` and no client identity. For upstreams that admit only certain clients (Kimi For Coding, Bailian Coding Plan, relays restricted to official clients). Not available for `chatgpt`. | | `proxy` | string | `direct` | `direct`; `system`, the proxy in the core process's `HTTPS_PROXY`, `HTTP_PROXY` or `ALL_PROXY` environment variables; or the name of an entry in `proxies`. | | `on_proxy_fail` | `fail` \| `direct` | `fail` | When the proxy cannot be reached: `fail` the request, or go `direct`. | -| `models` | list of strings | `[]` | Models to assume when the upstream does not answer `/v1/models`. | +| `models` | list of strings | `[]` | Models added by hand, by exact id, for those the upstream serves but leaves out of its list. They count as offered together with the models the upstream lists, or are the whole list when it lists none: they appear in `/v1/models` and requests for them are routed here. `models_only` still applies. No wildcards, no duplicates, at most 256 characters each. | | `models_only` | list of strings | — | Use only these of the upstream's models, as ids or globs. Others are not listed and are not routed here. Unset: all of them. Empty is refused; use `disabled`. | | `billing` | `per-token` \| `free` | `per-token` | `per-token`: cost is usage times the price in the upstream's price sheet, subscription accounts included. `free`: cost is recorded as 0. | | `pricing` | string | — | Name of a price sheet under `pricing.sheets`. Unset: the default price table. | @@ -435,6 +435,16 @@ providers: billing: free ``` +An upstream's models are the ones it lists on `/v1/models` (for Bedrock, the +region's model list) and the ones written in `models`. Upstreams often leave +models out of their list: a relay lists only some of what it serves, an +account backend hides new models from older clients. A model added in `models` +is listed in `/v1/models`, can be named by an alias, pinned in a rule and +allowed for a key, and is routed to this upstream like a listed one; +`models_only` applies to both. An upstream that lists nothing has exactly the +models in `models`; one with neither lists no model and is still sent requests +for any model. + A request carries the request itself and the headers its upstream needs, and nothing else from the client: the credential and the headers written in `headers`; ThinkWatch's own `User-Agent`; and, from the client's request, only diff --git a/docs/config.zh-CN.md b/docs/config.zh-CN.md index 8279e362..6e5f3e33 100644 --- a/docs/config.zh-CN.md +++ b/docs/config.zh-CN.md @@ -296,7 +296,7 @@ clients: | `forward_client_identity` | 布尔 | `false` | 同时发送客户端自己的身份:它的 `User-Agent`、`x-app` 和 `originator` 等身份请求头,以及请求体中的身份字段(如 `metadata.user_id`)。发送的都是客户端的原值,不做伪造。关闭时请求使用 ThinkWatch 的 `User-Agent`,不带客户端身份。用于只接受特定客户端的上游(Kimi For Coding、百炼 Coding Plan、只允许官方客户端的中转站)。`chatgpt` 不可用。 | | `proxy` | 字符串 | `direct` | `direct`;`system`,即 core 进程环境变量 `HTTPS_PROXY`、`HTTP_PROXY`、`ALL_PROXY` 中的代理;或 `proxies` 中某一项的名字。 | | `on_proxy_fail` | `fail` \| `direct` | `fail` | 代理不可用时:请求失败(`fail`),或改为直连(`direct`)。 | -| `models` | 字符串列表 | `[]` | 上游不支持 `/v1/models` 时,按这份清单认定它提供的模型。 | +| `models` | 字符串列表 | `[]` | 手动添加的模型,写确切的 ID:上游能服务、却没有列进清单的模型。它们和上游列出的模型一起算作这家提供的模型,上游不提供清单时就是全部:出现在 `/v1/models` 里,相应的请求也会路由到这家。`models_only` 照样适用。不支持通配,不能重复,每项最多 256 个字符。 | | `models_only` | 字符串列表 | — | 只使用这家的这些模型,写 ID 或通配。范围外的模型不出现在模型列表里,也不会路由到这家。不写:全部。写空列表会被拒绝,暂停使用请用 `disabled`。 | | `billing` | `per-token` \| `free` | `per-token` | `per-token`:费用为用量乘以所选价目表中的单价,订阅账号同样如此。`free`:费用记为 0。 | | `pricing` | 字符串 | — | `pricing.sheets` 中某张价目表的名字。不写:默认价目表。 | @@ -329,6 +329,8 @@ providers: billing: free ``` +一家上游提供的模型,是它在 `/v1/models` 列出的模型(Bedrock 为所在区域的模型清单),加上 `models` 中手动添加的模型。上游的清单常常不全:中转站只列出一部分,账号类的后端对旧版本客户端隐藏新模型。写进 `models` 的模型出现在 `/v1/models` 里,可以写进别名、在规则中指定、在密钥的 `allow` 中放行,也和列出的模型一样路由到这家;`models_only` 对两者同样适用。上游不提供清单时,`models` 就是它的全部模型;两者都没有时,它不列出任何模型,但任何模型的请求仍可能路由到这家。 + 每个请求只带请求本身和上游需要的请求头,客户端的其他信息一律不发:凭据和 `headers` 中写的请求头、ThinkWatch 自己的 `User-Agent`,以及客户端请求中该上游协议使用的请求头(Anthropic 为 `anthropic-*`,OpenAI 为 `Idempotency-Key` 和 `X-Client-Request-Id`,Gemini 没有)。客户端自动填写的身份字段(如 Claude Code 的 `metadata.user_id`)从请求体中去掉。只接受特定客户端的上游,打开 `forward_client_identity`。 ChatGPT 账号上游(`protocol: chatgpt`)只接受桌面应用登录得到的凭据,不能手写。不支持 Claude 和 Google 的订阅登录,请使用 API 密钥。