diff --git a/crates/tw-api/msg-codes.txt b/crates/tw-api/msg-codes.txt index e8fa1e44..1c08267a 100644 --- a/crates/tw-api/msg-codes.txt +++ b/crates/tw-api/msg-codes.txt @@ -216,6 +216,8 @@ gw.config.proxy_unusable gw.config.security_rules passthrough gw.content.refused gw.convert.failed +gw.count_tokens.bedrock_model +gw.count_tokens.bedrock_upstream gw.files.unsupported gw.hidden_text.refused_message gw.hidden_text.refused_tool_result diff --git a/crates/tw-dialect/src/anthropic/response.rs b/crates/tw-dialect/src/anthropic/response.rs index 6c4ac067..a0cf0427 100644 --- a/crates/tw-dialect/src/anthropic/response.rs +++ b/crates/tw-dialect/src/anthropic/response.rs @@ -174,6 +174,8 @@ pub fn error_body(status: u16, message: &str) -> Value { 404 => "not_found_error", 413 => "request_too_large", 429 => "rate_limit_error", + // 这个接口在这里没有。Claude Code 认它:数 token 回这个时,它改用别的办法数 + 501 => "not_supported", 504 => "timeout_error", 529 | 503 => "overloaded_error", _ => "api_error", @@ -192,6 +194,11 @@ pub fn error_message(v: &Value) -> Option { mod tests { use super::*; + #[test] + fn a_501_is_not_supported_the_way_claude_code_reads_it() { + assert_eq!(error_body(501, "x")["error"]["type"], "not_supported"); + } + #[test] fn the_one_hour_cache_tier_survives_a_round_trip() { let u = usage( diff --git a/crates/tw-gateway/src/client_api.rs b/crates/tw-gateway/src/client_api.rs index 90431017..defc8ab0 100644 --- a/crates/tw-gateway/src/client_api.rs +++ b/crates/tw-gateway/src/client_api.rs @@ -79,6 +79,15 @@ impl ClientApi { && (p.ends_with(":generateContent") || p.ends_with(":streamGenerateContent"))) } + /// 这个路径是不是 Anthropic 的数 token(`/v1/messages/count_tokens`)。 + /// + /// Bedrock 上游接不了它(见 [`crate::error::Source::NotSupported`]):bedrock-runtime + /// 的 CountTokens 只数得了一部分老模型,较新的、只能跨区域推理的那些在那里数不了。 + pub fn counts_tokens(path: &str) -> bool { + let p = path.trim_end_matches('/'); + p.strip_prefix("/v1").unwrap_or(p) == "/messages/count_tokens" + } + /// 转换库里对应的格式 pub fn dialect(&self) -> Dialect { match self { @@ -223,6 +232,18 @@ mod tests { } } + #[test] + fn only_anthropics_count_tokens_path_counts_tokens() { + for (path, counts) in [ + ("/v1/messages/count_tokens", true), + ("/messages/count_tokens/", true), + ("/v1/messages", false), + ("/v1beta/models/gemini-2.5-pro:countTokens", false), + ] { + assert_eq!(ClientApi::counts_tokens(path), counts, "{path}"); + } + } + #[test] fn a_path_we_do_not_know_is_not_guessed() { for path in ["/v1/models", "/v1/files", "/healthz", "/v1/messagesx", "/"] { diff --git a/crates/tw-gateway/src/error.rs b/crates/tw-gateway/src/error.rs index 757219fb..98bca412 100644 --- a/crates/tw-gateway/src/error.rs +++ b/crates/tw-gateway/src/error.rs @@ -33,6 +33,13 @@ pub enum Source { /// 去改他的请求,而该改的是规则。表里它是 403 + /// `permission_error`。 Denied, + /// 这个接口在这一家上游那里没有,客户端该换一种办法。 + /// + /// **501 `not_supported` 是 Claude Code 认的回答**:它的网关对接约定里,Bedrock + /// 上游数不了 token 时就回这个,客户端会改用一次 `max_tokens: 1` 的请求来数。回 + /// 400 的话它当成请求写错了。对外的词表(`x-thinkwatch-error`、`RequestFailed.source`) + /// 里算 `request`:服务不了的是这个请求要的接口 + NotSupported, } impl Source { @@ -45,6 +52,7 @@ impl Source { Source::Request => "request", Source::RateLimited => "rate_limited", Source::Denied => "denied", + Source::NotSupported => "request", } } fn status(&self) -> StatusCode { @@ -56,6 +64,7 @@ impl Source { // 429 而不是 503:客户端至少知道这是限流,可以退避。 Source::RateLimited => StatusCode::TOO_MANY_REQUESTS, Source::Denied => StatusCode::FORBIDDEN, + Source::NotSupported => StatusCode::NOT_IMPLEMENTED, } } } diff --git a/crates/tw-gateway/src/server/pipeline.rs b/crates/tw-gateway/src/server/pipeline.rs index 1d66c53c..be04ca97 100644 --- a/crates/tw-gateway/src/server/pipeline.rs +++ b/crates/tw-gateway/src/server/pipeline.rs @@ -247,6 +247,24 @@ fn admit( { return Ok(()); } + // 数 token 的模型只有 Bedrock 上游有:回 501 `not_supported`,Claude Code 会改用别的 + // 办法数(见 `Source::NotSupported`)。说「没有上游提供它」的话,用户会去查一个其实 + // 能用的模型 + let bedrock = [tw_config::Protocol::Bedrock.slug()]; + if crate::client_api::ClientApi::counts_tokens(req.uri.path()) + && models + .iter() + .any(|m| catalog.admits(m, Some(&bedrock), allow.as_deref())) + { + return Err(GatewayError::new( + crate::error::Source::NotSupported, + msg!( + "gw.count_tokens.bedrock_model", model = model => + "Counting tokens is not available for model {model}: only AWS Bedrock upstreams \ + serve it." + ), + )); + } // 错误信息要说清是哪一种:没有上游提供它,和这个客户端不让用它, // 该去改的地方不一样。**改写过的两个名字都要说**:客户端写的是一个, // 报错里说的是另一个,不说清楚像是网关认错了模型 diff --git a/crates/tw-gateway/src/server/pipeline/hop.rs b/crates/tw-gateway/src/server/pipeline/hop.rs index 07cff23e..071250e4 100644 --- a/crates/tw-gateway/src/server/pipeline/hop.rs +++ b/crates/tw-gateway/src/server/pipeline/hop.rs @@ -404,6 +404,19 @@ fn protocol_mismatch( if a.protocol() == p { return None; } + // 数 token 到了 Bedrock 上游:501 `not_supported`,客户端会改用别的办法数(见 + // `Source::NotSupported`)。**同样不发出去** + if p == tw_config::Protocol::Bedrock + && crate::client_api::ClientApi::counts_tokens(req.uri.path()) + { + return Some(GatewayError::new( + crate::error::Source::NotSupported, + msg!( + "gw.count_tokens.bedrock_upstream", upstream = provider.name.clone() => + "Counting tokens is not available through AWS Bedrock upstream `{upstream}`." + ), + )); + } Some(GatewayError::new( crate::error::Source::Request, msg!( diff --git a/crates/tw-gateway/src/wire.rs b/crates/tw-gateway/src/wire.rs index a98e3d06..0607cd13 100644 --- a/crates/tw-gateway/src/wire.rs +++ b/crates/tw-gateway/src/wire.rs @@ -13,6 +13,7 @@ impl From for FailureSource { Source::Request => Self::Request, Source::RateLimited => Self::RateLimited, Source::Denied => Self::Denied, + Source::NotSupported => Self::Request, } } } diff --git a/crates/tw-gateway/tests/bedrock.rs b/crates/tw-gateway/tests/bedrock.rs index 8a5650ed..7707e0ea 100644 --- a/crates/tw-gateway/tests/bedrock.rs +++ b/crates/tw-gateway/tests/bedrock.rs @@ -607,3 +607,53 @@ async fn a_speed_test_reports_an_exception_inside_the_stream() { assert_eq!(e.code, "l3.stream_failed", "{e:?}"); assert!(e.text.contains("serviceUnavailableException"), "{e:?}"); } + +/// Anthropic 的数 token 到了 Bedrock 上游:回 501 `not_supported`,**什么都不发给 AWS**。 +/// Claude Code 认这个回答,会改用一次 `max_tokens: 1` 的请求来数;回 400 的话它当成 +/// 请求写错了 +#[tokio::test] +async fn counting_tokens_is_not_supported_the_way_claude_code_expects() { + let (up, seen) = bedrock(Arc::new(|s: &Seen| { + let path = s.uri.split('?').next().unwrap(); + match path { + "/foundation-models" => json_answer(200, json!({"modelSummaries": []})), + "/inference-profiles" => json_answer( + 200, + json!({"inferenceProfileSummaries": [{"inferenceProfileId": MODEL}]}), + ), + _ => json_answer(500, json!({"message": "nothing else should arrive"})), + } + })) + .await; + let (gw, state, _) = gateway(with_keys(up)).await; + let body = json!({"model": MODEL, "messages": [{"role": "user", "content": "hi"}]}); + let count = |body: Value| { + post( + gw, + "/v1/messages/count_tokens", + &[("x-api-key", "tw-k")], + body, + ) + }; + + // 模型清单还没取到:选上游时认出来 + let (status, text) = count(body.clone()).await; + assert_eq!(status, 501, "{text}"); + let v: Value = serde_json::from_str(&text).unwrap(); + assert_eq!(v["error"]["type"], "not_supported", "{text}"); + assert!(text.contains("upstream `br`"), "{text}"); + + // 取到了:准入时就认出来 + tw_gateway::models::refresh_one(&state, "br").await.unwrap(); + let (status, text) = count(body).await; + assert_eq!(status, 501, "{text}"); + assert!( + text.contains("only AWS Bedrock upstreams serve it"), + "{text}" + ); + + assert!( + seen.lock().unwrap().iter().all(|s| s.method == "GET"), + "counting tokens reached AWS" + ); +}