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 @@ -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
Expand Down
7 changes: 7 additions & 0 deletions crates/tw-dialect/src/anthropic/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -192,6 +194,11 @@ pub fn error_message(v: &Value) -> Option<String> {
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(
Expand Down
21 changes: 21 additions & 0 deletions crates/tw-gateway/src/client_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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", "/"] {
Expand Down
9 changes: 9 additions & 0 deletions crates/tw-gateway/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -45,6 +52,7 @@ impl Source {
Source::Request => "request",
Source::RateLimited => "rate_limited",
Source::Denied => "denied",
Source::NotSupported => "request",
}
}
fn status(&self) -> StatusCode {
Expand All @@ -56,6 +64,7 @@ impl Source {
// 429 而不是 503:客户端至少知道这是限流,可以退避。
Source::RateLimited => StatusCode::TOO_MANY_REQUESTS,
Source::Denied => StatusCode::FORBIDDEN,
Source::NotSupported => StatusCode::NOT_IMPLEMENTED,
}
}
}
Expand Down
18 changes: 18 additions & 0 deletions crates/tw-gateway/src/server/pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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."
),
));
}
// 错误信息要说清是哪一种:没有上游提供它,和这个客户端不让用它,
// 该去改的地方不一样。**改写过的两个名字都要说**:客户端写的是一个,
// 报错里说的是另一个,不说清楚像是网关认错了模型
Expand Down
13 changes: 13 additions & 0 deletions crates/tw-gateway/src/server/pipeline/hop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!(
Expand Down
1 change: 1 addition & 0 deletions crates/tw-gateway/src/wire.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ impl From<crate::error::Source> for FailureSource {
Source::Request => Self::Request,
Source::RateLimited => Self::RateLimited,
Source::Denied => Self::Denied,
Source::NotSupported => Self::Request,
}
}
}
Expand Down
50 changes: 50 additions & 0 deletions crates/tw-gateway/tests/bedrock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"
);
}
Loading