From b03fba6344490fb384ec3e7f7d5e9f0645dc8c03 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Tue, 29 Sep 2026 12:31:00 +0800 Subject: [PATCH] fix(gateway): refuse a hop that would drop the tool a request requires Claude Code runs each web search as its own request that carries only the server-side web_search tool and forces the model to use it. Converted for an upstream of another format (Bedrock, OpenAI, Gemini, ...), the server tool is dropped, so the model answered without searching and Claude Code passed that answer on as the search results, with no error anywhere. When the tool a request forces (tool_choice naming a tool, or requiring a tool call when every tool was dropped) cannot be sent in the upstream's format, that hop is not sent: the next upstream of the route is tried, and if none can take it the client gets a 400 saying which tool and which upstream (gw.convert.tool_unsendable, gw.convert.tools_unsendable). Server tools offered alongside others with tool_choice auto are still dropped and reported, as before. Co-Authored-By: Claude Opus 5.5 --- crates/tw-api/msg-codes.txt | 2 + crates/tw-gateway/src/server/pipeline/hop.rs | 40 ++++++++++++++ crates/tw-gateway/tests/dialect.rs | 56 ++++++++++++++++++++ 3 files changed, 98 insertions(+) diff --git a/crates/tw-api/msg-codes.txt b/crates/tw-api/msg-codes.txt index 91c38c63..da8cc7cf 100644 --- a/crates/tw-api/msg-codes.txt +++ b/crates/tw-api/msg-codes.txt @@ -223,6 +223,8 @@ gw.config.proxy_unusable gw.config.security_rules passthrough gw.content.refused gw.convert.failed +gw.convert.tool_unsendable +gw.convert.tools_unsendable gw.count_tokens.bedrock_model gw.count_tokens.bedrock_upstream gw.files.unsupported diff --git a/crates/tw-gateway/src/server/pipeline/hop.rs b/crates/tw-gateway/src/server/pipeline/hop.rs index 2984ca26..83ce16cd 100644 --- a/crates/tw-gateway/src/server/pipeline/hop.rs +++ b/crates/tw-gateway/src/server/pipeline/hop.rs @@ -428,6 +428,42 @@ fn protocol_mismatch( )) } +/// 请求强制要用、换成这一家的格式之后却没有了的工具。 +/// +/// Claude Code 搜网页时单独发一个请求,只带服务端工具 `web_search`,并且强制模型用它。服务端 +/// 工具只有它所属的那一家执行得了,换格式时被丢掉 —— 照样发出去,模型不搜索,直接回一段话, +/// 而 Claude Code 把这段话当成搜索结果交给模型。**这样的一跳不发**:换下一家,同格式的上游 +/// 可能还在后面;都不行,客户端收到的是说得清的这一句,而不是一份编出来的结果。 +/// +/// 只管强制的。`auto` 时这类工具只是顺带挂着(有的客户端每个请求都带),丢掉之后模型照常回答。 +fn unsendable_tool( + request: &tw_dialect::ir::Request, + dropped: &[String], + upstream: &str, +) -> Option { + use tw_dialect::ir::ToolChoice; + let msg = match request.tool_choice.as_ref()? { + ToolChoice::Named(tool) if !request.tools.iter().any(|t| t.name == *tool) => msg!( + "gw.convert.tool_unsendable", tool = tool.clone(), upstream = upstream => + "The request requires the tool `{tool}`, which cannot be sent to upstream `{upstream}` \ + in its format. Server-side tools such as web search are carried out only by the \ + provider they belong to." + ), + ToolChoice::Required + if request.tools.is_empty() && dropped.iter().any(|p| p.starts_with("tools.")) => + { + msg!( + "gw.convert.tools_unsendable", upstream = upstream => + "The request requires a tool call, and none of its tools can be sent to upstream \ + `{upstream}` in its format. Server-side tools such as web search are carried out \ + only by the provider they belong to." + ) + } + _ => return None, + }; + Some(GatewayError::new(crate::error::Source::Request, msg)) +} + /// 把客户端的请求改成这一跳要发的样子:同格式时只做参数改写, /// 跨格式时转换。转换不了就换下一家:同格式的上游可能还在后面。 fn prepare( @@ -561,6 +597,10 @@ fn prepare( &d.request.model, ), }); + // 请求强制要用的工具发不过去:这一跳不发,换下一家(见 `unsendable_tool`) + if let Some(err) = unsendable_tool(&d.request, &p.dropped, &provider.name) { + return Err(err); + } // **转换了就要说一声,丢了字段更要说。**用户会发现「扩展思考开了 // 却没生效」而完全不知道从哪儿查起 let mut dropped = p.dropped.clone(); diff --git a/crates/tw-gateway/tests/dialect.rs b/crates/tw-gateway/tests/dialect.rs index 17bbcd47..1749a5bc 100644 --- a/crates/tw-gateway/tests/dialect.rs +++ b/crates/tw-gateway/tests/dialect.rs @@ -300,6 +300,62 @@ async fn what_could_not_be_translated_is_reported_to_the_user() { ); } +/// Claude Code 搜网页的那个请求:只带服务端工具 `web_search`,并且强制模型用它。发到别的格式 +/// 的上游时这个工具发不过去 —— **不发**。照样发的话模型不搜索、直接回一段话,Claude Code +/// 会把它当成搜索结果;客户端要收到的是说得清的一句 +#[tokio::test] +async fn a_request_that_requires_a_server_tool_is_not_sent_without_it() { + let (up, seen) = start_openai_upstream(false).await; + let (gw, mut rx) = start_gateway(up).await; + let body = serde_json::json!({ + "model": "deepseek-chat", + "max_tokens": 1024, + "system": [{"type": "text", "text": "You are an assistant for performing a web search tool use"}], + "messages": [{"role": "user", "content": "Perform a web search for the query: bedrock pricing"}], + "tools": [{"type": "web_search_20250305", "name": "web_search", "max_uses": 8}], + "tool_choice": {"type": "tool", "name": "web_search"} + }); + let (status, text) = ask(gw, body.to_string()).await; + assert_eq!(status, 400, "{text}"); + let v: serde_json::Value = serde_json::from_str(&text).unwrap(); + assert!( + v["error"]["message"] + .as_str() + .is_some_and(|m| m.contains("`web_search`") && m.contains("`deepseek`")), + "{text}" + ); + assert!( + seen.lock().unwrap().is_empty(), + "没了这个工具的请求还是发出去了" + ); + + let mut code = None; + while let Ok(Ok(ev)) = tokio::time::timeout(Duration::from_secs(3), rx.recv()).await { + if let tw_api::Event::RequestFailed { message, .. } = ev { + code = Some(message.code); + break; + } + } + assert_eq!(code.as_deref(), Some("gw.convert.tool_unsendable")); +} + +/// 要求必须调用工具(`any`),而工具全是发不过去的服务端工具:一样不发 +#[tokio::test] +async fn a_required_tool_call_with_only_server_tools_is_not_sent() { + let (up, seen) = start_openai_upstream(false).await; + let (gw, _) = start_gateway(up).await; + let body = serde_json::json!({ + "model": "deepseek-chat", + "max_tokens": 1024, + "messages": [{"role": "user", "content": "find it"}], + "tools": [{"type": "web_search_20250305", "name": "web_search"}], + "tool_choice": {"type": "any"} + }); + let (status, text) = ask(gw, body.to_string()).await; + assert_eq!(status, 400, "{text}"); + assert!(seen.lock().unwrap().is_empty()); +} + #[tokio::test] async fn the_usage_sniffer_still_sees_the_numbers_after_translation() { // **这是最容易断的一处接缝。**翻译出来的流要能被我们自己的嗅探器