diff --git a/crates/tw-api/msg-codes.txt b/crates/tw-api/msg-codes.txt index da8cc7cf..5be2f14a 100644 --- a/crates/tw-api/msg-codes.txt +++ b/crates/tw-api/msg-codes.txt @@ -225,7 +225,6 @@ 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 gw.hidden_text.refused_message diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index c5acc248..13f0ee37 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -646,7 +646,12 @@ pub const MSG_CODES: &str = include_str!("../msg-codes.txt"); /// ([`AffinityView`]):这次沿用了这一轮的路由决定、留在了上次回答的那一家的, /// 说得出来。照 28 写的界面保存策略组时交的 `session_affinity` 被忽略,读 /// `hurts_cache` 读到的是 undefined。 -pub const CONTROL_API_VERSION: u32 = 29; +/// +/// **30 起数 token 可以由网关本地估算**:`/v1/messages/count_tokens` 和 Gemini 的 +/// `:countTokens` 路由到别的格式的上游、或者上游回 404 / 405 时,网关自己估一个数回去。 +/// 尝试链多一种结果 [`AttemptOutcome::Estimated`],那一行是 `local`、费用 0。照 29 写的 +/// 界面不认这个词。 +pub const CONTROL_API_VERSION: u32 = 30; #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] @@ -1278,6 +1283,11 @@ slug_enum! { Status = "status", /// 没有收到响应(超时、无法连接),或者这一跳没有发出去 Error = "error", + /// 数 token 的请求由网关本地估算,没有用这一家的回答:这一家不是客户端那种 + /// 格式(没有发出去,没有 `status`),或者它回了 404 / 405、没实现这个接口 + /// (`status` 是它回的那个)。尝试链到此为止,这一行记成网关自己答的 + /// ([`HistoryRow::local`]),费用 0 + Estimated = "estimated", } } diff --git a/crates/tw-gateway/src/client_api.rs b/crates/tw-gateway/src/client_api.rs index defc8ab0..740c24a0 100644 --- a/crates/tw-gateway/src/client_api.rs +++ b/crates/tw-gateway/src/client_api.rs @@ -79,13 +79,17 @@ impl ClientApi { && (p.ends_with(":generateContent") || p.ends_with(":streamGenerateContent"))) } - /// 这个路径是不是 Anthropic 的数 token(`/v1/messages/count_tokens`)。 + /// 这个路径是不是数 token:Anthropic 的 `/v1/messages/count_tokens`、Gemini 的 + /// `:countTokens`。 /// - /// Bedrock 上游接不了它(见 [`crate::error::Source::NotSupported`]):bedrock-runtime - /// 的 CountTokens 只数得了一部分老模型,较新的、只能跨区域推理的那些在那里数不了。 + /// **别的格式的上游也能「服务」它**:不发过去,网关自己估一个数(见 [`crate::count`])。 + /// 只有 Anthropic 的数 token 到了 Bedrock 上游例外,回 501(见 + /// [`crate::error::Source::NotSupported`]):bedrock-runtime 的 CountTokens 只数得了 + /// 一部分老模型,Claude Code 认这个回答,会自己去数一个准的。 pub fn counts_tokens(path: &str) -> bool { let p = path.trim_end_matches('/'); p.strip_prefix("/v1").unwrap_or(p) == "/messages/count_tokens" + || (p.contains("/models/") && p.ends_with(":countTokens")) } /// 转换库里对应的格式 @@ -113,13 +117,15 @@ impl ClientApi { self.protocol().slug() } - /// 能服务这次调用的上游协议。 + /// 能服务这次调用的上游协议。`any` 是生成回答,或者数 token(见 + /// [`ClientApi::counts_tokens`])。 /// /// **模型准入、`/v1/models` 和转发时选不选这家,用的都是这一张表** —— /// 列出来的模型发过去一定有人能接。生成回答四种格式互相转换,谁都能服务; - /// 别的接口只有同格式的上游能处理(见 [`ClientApi::generates`])。 - pub fn servable_by(&self, generates: bool) -> &'static [Protocol] { - if generates { + /// 数 token 别的格式的上游由网关本地估算;别的接口只有同格式的上游能处理(见 + /// [`ClientApi::generates`])。 + pub fn servable_by(&self, any: bool) -> &'static [Protocol] { + if any { return &[ Protocol::Anthropic, Protocol::OpenaiChat, @@ -233,12 +239,14 @@ mod tests { } #[test] - fn only_anthropics_count_tokens_path_counts_tokens() { + fn both_count_tokens_paths_count_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), + ("/v1beta/models/gemini-2.5-pro:countTokens", true), + ("/v1beta/models/gemini-2.5-pro:generateContent", false), + ("/v1/embeddings", false), ] { assert_eq!(ClientApi::counts_tokens(path), counts, "{path}"); } diff --git a/crates/tw-gateway/src/count.rs b/crates/tw-gateway/src/count.rs new file mode 100644 index 00000000..320435a6 --- /dev/null +++ b/crates/tw-gateway/src/count.rs @@ -0,0 +1,261 @@ +//! 数 token 的本地估算。 +//! +//! Claude Code 每一轮都要调一次 `/v1/messages/count_tokens`,Gemini 的客户端调 +//! `:countTokens`。**这两个接口别的格式没有对应物**:转成一次真正的补全既花钱, +//! 回来的也不是客户端要的形状(见 [`crate::client_api::ClientApi::generates`])。 +//! 以前路由到别的格式的上游时直接报错,客户端那一轮就断了。 +//! +//! 现在由网关自己估一个数回去: +//! +//! - 选中的上游不是客户端那种格式 —— **一个字节都不发给它**; +//! - 同格式的上游回 404 / 405 —— 不少中转只实现了生成回答,没实现数 token。 +//! +//! **估的数只是量级。**客户端拿它判断上下文快满了没有,差个一两成不改变结论; +//! 精确要跑各家自己的 tokenizer,而这个请求本来就是为了不花那份钱。估出来的这一行 +//! 记成网关自己答的(`local`),费用 0,不进 token 统计 —— 它没有真的用掉谁的 token。 + +use serde_json::Value; +use tw_dialect::ir::{Dialect, Part, Request, ToolInput, ToolKind}; + +/// 一张图按多少 token 算。 +/// +/// 各家按像素算,而这里不解码图片:取 Anthropic 一张接近上限的图(约 1.15 百万像素, +/// 宽 × 高 / 750)的数。**宁可高估**:客户端拿这个数判断要不要压缩上下文,低估的 +/// 代价是请求超长被拒,高估只是早一点压缩。 +pub const IMAGE_TOKENS: u64 = 1_600; + +/// 一份文件(PDF 之类)按多少 token 算。页数不解析,按一页多一点算一个下限 +pub const FILE_TOKENS: u64 = 1_600; + +/// 每条消息的结构开销(角色、分隔符) +const PER_MESSAGE: u64 = 3; + +/// 上游对数 token 回了这个状态码:它没实现这个接口,由网关来估。 +/// +/// 只认 404 和 405。**501 不算**:那是 Claude Code 认的「数不了」(见 +/// [`crate::error::Source::NotSupported`]),它会自己去数一个准的。 +pub fn unsupported(status: u16) -> bool { + matches!(status, 404 | 405) +} + +/// 估一个请求的输入 token 数。 +/// +/// 文字按 ASCII 四个字节一个 token、其余每个字符一个 token 算:英文和代码大约是 +/// 这个比例,中日韩文字一个字常常就是一个 token —— 按字节数除以四会把中文估低 +/// 四分之一。工具定义按它序列化之后的样子算,模型看到的就是那一段 JSON。 +/// +/// 推理(thinking)不算:早先几轮的推理上游不放进上下文。 +pub fn estimate(r: &Request) -> u64 { + let mut text = Text::default(); + let mut fixed = 0u64; + for s in &r.system { + text.add(s); + } + for m in &r.messages { + fixed += PER_MESSAGE; + for p in &m.parts { + fixed += part(&mut text, p); + } + } + for t in &r.tools { + text.add(&t.name); + if let Some(d) = &t.description { + text.add(d); + } + if let ToolKind::Function { schema, .. } = &t.kind { + text.add(&schema.to_string()); + } + } + text.tokens() + fixed +} + +/// 一段内容:文字记进 `text`,图片、文件按固定的数返回。 +fn part(text: &mut Text, p: &Part) -> u64 { + match p { + Part::Text(t) => text.add(t), + Part::Thinking(_) => {} + Part::ToolCall(c) => { + text.add(&c.name); + match &c.input { + ToolInput::Json(v) => text.add(&v.to_string()), + ToolInput::Text(t) => text.add(t), + } + } + Part::ToolResult(t) => return t.content.iter().map(|p| part(text, p)).sum(), + Part::Image(_) => return IMAGE_TOKENS, + Part::File { .. } => return FILE_TOKENS, + } + 0 +} + +/// 攒着的文字:ASCII 字节数和其余字符数分开数。 +#[derive(Default)] +struct Text { + ascii: u64, + other: u64, +} + +impl Text { + fn add(&mut self, s: &str) { + for c in s.chars() { + if c.is_ascii() { + self.ascii += 1; + } else { + self.other += 1; + } + } + } + + fn tokens(&self) -> u64 { + self.ascii.div_ceil(4) + self.other + } +} + +/// 替上游答这个数 token 的请求:要回给客户端的正文。`client` 是客户端的格式。 +/// +/// 解不开的请求体照样给一个数:按里面所有字符串的长度估。**数 token 不该因为 +/// 我们的解析器不认识某个字段就失败** —— 客户端拿不到这个数,这一轮就断了。 +pub fn answer(client: Dialect, path: &str, body: &[u8]) -> Vec { + let v = serde_json::from_slice::(body).unwrap_or(Value::Null); + let n = decode(client, path, &v) + .map(|r| estimate(&r)) + .unwrap_or_else(|| { + let mut text = Text::default(); + strings(&v, &mut text); + text.tokens() + }); + let out = match client { + Dialect::Gemini => serde_json::json!({ "totalTokens": n }), + _ => serde_json::json!({ "input_tokens": n }), + }; + out.to_string().into_bytes() +} + +/// 按生成回答的格式解码。Anthropic 数 token 的请求体就是生成回答的那一份(少了 +/// `max_tokens`);Gemini 的要么就是 `contents` 那些,要么包在 `generateContentRequest` 里。 +fn decode(client: Dialect, path: &str, v: &Value) -> Option { + let (v, path) = match client { + Dialect::Gemini => ( + v.get("generateContentRequest").unwrap_or(v), + path.strip_suffix(":countTokens") + .map(|p| format!("{p}:generateContent"))?, + ), + _ => (v, path.to_string()), + }; + tw_dialect::convert::decode(client, v, &path, None) + .ok() + .map(|d| d.request) +} + +/// 所有字符串值 +fn strings(v: &Value, text: &mut Text) { + match v { + Value::String(s) => text.add(s), + Value::Array(a) => a.iter().for_each(|v| strings(v, text)), + Value::Object(o) => o.values().for_each(|v| strings(v, text)), + _ => {} + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn count(client: Dialect, path: &str, body: Value) -> Value { + serde_json::from_slice(&answer(client, path, body.to_string().as_bytes())).unwrap() + } + + #[test] + fn an_anthropic_request_is_answered_in_anthropics_shape() { + let v = count( + Dialect::Anthropic, + "/v1/messages/count_tokens", + json!({ + "model": "claude-opus-4-7", + "system": "abcdefgh", + "messages": [{"role": "user", "content": "abcd"}], + }), + ); + // 8 + 4 个 ASCII 字符是 3 个 token,一条消息 3 个 + assert_eq!(v, json!({"input_tokens": 6})); + } + + #[test] + fn a_gemini_request_is_answered_in_geminis_shape_wrapped_or_not() { + let contents = json!([{"role": "user", "parts": [{"text": "abcdabcd"}]}]); + let path = "/v1beta/models/gemini-2.5-pro:countTokens"; + let bare = count(Dialect::Gemini, path, json!({"contents": contents})); + assert_eq!(bare, json!({"totalTokens": 5})); + let wrapped = count( + Dialect::Gemini, + path, + json!({"generateContentRequest": {"model": "models/gemini-2.5-pro", "contents": contents}}), + ); + assert_eq!(wrapped, bare); + } + + #[test] + fn chinese_counts_a_token_a_character() { + let v = count( + Dialect::Anthropic, + "/v1/messages/count_tokens", + json!({"model": "m", "messages": [{"role": "user", "content": "帮我重构这个文件"}]}), + ); + assert_eq!(v["input_tokens"], 8 + PER_MESSAGE); + } + + #[test] + fn images_tools_and_tool_traffic_all_count() { + let body = json!({ + "model": "m", + "tools": [{"name": "read_file", "description": "Read a file", + "input_schema": {"type": "object", "properties": {"path": {"type": "string"}}}}], + "messages": [ + {"role": "user", "content": [ + {"type": "text", "text": "看图"}, + {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "iVBORw0KGgo".repeat(10_000)}}, + ]}, + {"role": "assistant", "content": [ + {"type": "thinking", "thinking": "不该算进去的推理".repeat(100), "signature": "s"}, + {"type": "tool_use", "id": "t1", "name": "read_file", "input": {"path": "/a"}}, + ]}, + {"role": "user", "content": [ + {"type": "tool_result", "tool_use_id": "t1", "content": [ + {"type": "text", "text": "file body"}, + {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "AAAA"}}, + ]}, + ]}, + ], + }); + let n = count(Dialect::Anthropic, "/v1/messages/count_tokens", body)["input_tokens"] + .as_u64() + .unwrap(); + // 两张图各按固定的数算,base64 的长度不算进去;推理不算 + assert!(n > 2 * IMAGE_TOKENS, "{n}"); + assert!(n < 2 * IMAGE_TOKENS + 100, "{n}"); + } + + #[test] + fn a_body_we_cannot_decode_still_gets_a_number() { + let v = count( + Dialect::Anthropic, + "/v1/messages/count_tokens", + json!(["not an object", "abcdefgh"]), + ); + assert!(v["input_tokens"].as_u64().unwrap() > 0, "{v}"); + } + + #[test] + fn only_404_and_405_mean_the_upstream_cannot_count() { + for (status, want) in [ + (404, true), + (405, true), + (501, false), + (400, false), + (500, false), + ] { + assert_eq!(unsupported(status), want, "{status}"); + } + } +} diff --git a/crates/tw-gateway/src/lib.rs b/crates/tw-gateway/src/lib.rs index 818346b4..f7b25860 100644 --- a/crates/tw-gateway/src/lib.rs +++ b/crates/tw-gateway/src/lib.rs @@ -13,6 +13,7 @@ pub mod bodies; pub mod chatgpt; pub mod client_api; pub mod clientprobe; +pub mod count; pub mod egress; pub mod ending; pub mod error; @@ -34,6 +35,7 @@ pub mod outbound; pub mod probe; pub mod quota; pub mod quote; +pub mod seal; pub mod server; pub mod session; pub mod state; diff --git a/crates/tw-gateway/src/seal.rs b/crates/tw-gateway/src/seal.rs new file mode 100644 index 00000000..70fc8a28 --- /dev/null +++ b/crates/tw-gateway/src/seal.rs @@ -0,0 +1,359 @@ +//! 别的账号封存的推理。 +//! +//! 推理模型把上一轮的推理封存起来交给客户端,下一轮原样带回:Responses 的 +//! `reasoning` 条目带着 `encrypted_content`,Anthropic 的 `thinking` 块带着 `signature` +//! (`redacted_thinking` 整块都是 `data`)。**封存和产生它的账号绑定**:故障转移、 +//! 换了一个账号或者另一家中转之后,新的那一家解不开,整个请求被拒 —— +//! +//! - OpenAI:400,`error.code` 是 `invalid_encrypted_content`(「The encrypted content +//! for item rs_… could not be verified」); +//! - Anthropic:400,「Invalid `signature` in `thinking` block」。 +//! +//! 客户端每一轮都把整段历史带回来,于是这段对话从此每一轮都被拒。 +//! +//! 被拒了就**去掉封存的推理,同一家再发一次**(只一次)。说过的话、调过的工具都 +//! 还在,去掉的只是模型写给自己的那几段笔记。再记下(这段对话,这一家)拒过哪些, +//! 下一轮发给它之前先去掉,不用每一轮都先被拒一次 —— **只去掉它拒过的那些**: +//! 它自己后来封存的照样带上,缓存和推理的连贯都还在。 + +use std::collections::{HashMap, HashSet}; +use std::sync::Mutex; + +use serde_json::Value; +use tw_dialect::ir::Dialect; + +/// 一段封存的推理的指纹 +pub type Seal = [u8; 32]; + +/// 记着几段对话就清一次早就不说话的 +const PRUNE_AT: usize = 4096; + +/// 被拒的响应体最多看这么多。拒绝的原话很短,没必要把一个大响应读进来找 +const REFUSAL_MAX: usize = 64 * 1024; + +/// (对话, 上游) → (最后一次被拒的时刻, 拒过的封存) +type ByConversation = HashMap<(String, String), (u64, HashSet)>; + +/// 每段对话、每一家拒过的封存。**只在内存里,跨重载存活**:重启之后丢了也只是 +/// 下一轮再被拒一次、再重发一次。 +#[derive(Default)] +pub struct Refused { + by: Mutex, +} + +impl Refused { + /// `upstream` 在对话 `conversation` 里拒了这些封存。 + pub fn note(&self, conversation: &str, upstream: &str, seals: &[Seal], at_ms: u64) { + if seals.is_empty() { + return; + } + let mut by = self.by.lock().unwrap_or_else(|p| p.into_inner()); + if by.len() >= PRUNE_AT { + by.retain(|_, (last, _)| at_ms.saturating_sub(*last) <= crate::session::SESSION_GAP_MS); + } + // 都还在说话:丢最老的那段。表不能无限长 + if by.len() >= PRUNE_AT + && let Some(oldest) = by + .iter() + .min_by_key(|(_, (last, _))| *last) + .map(|(k, _)| k.clone()) + { + by.remove(&oldest); + } + let e = by + .entry((conversation.to_string(), upstream.to_string())) + .or_default(); + e.0 = e.0.max(at_ms); + e.1.extend(seals.iter().copied()); + } + + /// `upstream` 在对话 `conversation` 里拒过的封存。没拒过的是 None + pub fn of(&self, conversation: &str, upstream: &str) -> Option> { + let by = self.by.lock().unwrap_or_else(|p| p.into_inner()); + by.get(&(conversation.to_string(), upstream.to_string())) + .map(|(_, s)| s.clone()) + } +} + +/// 上游这个 400 是在拒绝封存的推理吗。`wire` 是发给它的那一份的格式。 +/// +/// 看原话,不看错误外壳的结构:同一句话,OpenAI 放在 `error.code`,Codex 后端和 +/// 中转各有各的包法。 +pub fn refusal(wire: Dialect, body: &[u8]) -> bool { + if body.len() > REFUSAL_MAX { + return false; + } + let text = String::from_utf8_lossy(body).to_ascii_lowercase(); + match wire { + Dialect::Responses => { + text.contains("invalid_encrypted_content") + || ((text.contains("encrypted content") || text.contains("encrypted_content")) + && [ + "could not be verified", + "could not be decrypted", + "could not decrypt", + ] + .iter() + .any(|w| text.contains(w))) + } + Dialect::Anthropic => { + text.contains("invalid") && text.contains("signature") && text.contains("thinking") + } + _ => false, + } +} + +/// 去掉请求体里封存的推理。`only` 给了的只去掉其中的那些,没给的全去掉。 +/// +/// 返回去掉之后的请求体和去掉了哪些。**什么都没去掉是 None** —— 解不开、不是这两种 +/// 格式、里面没有封存的推理,都是原样发。 +pub fn strip( + wire: Dialect, + body: &[u8], + only: Option<&HashSet>, +) -> Option<(Vec, Vec)> { + if !matches!(wire, Dialect::Responses | Dialect::Anthropic) { + return None; + } + let mut v: Value = serde_json::from_slice(body).ok()?; + let drop = |s: &str| { + let seal = seal(s); + only.is_none_or(|o| o.contains(&seal)).then_some(seal) + }; + let mut removed = Vec::new(); + match wire { + Dialect::Responses => { + let items = v.get_mut("input")?.as_array_mut()?; + items.retain(|it| { + match it + .get("encrypted_content") + .and_then(Value::as_str) + .filter(|e| !e.is_empty() && is(it, "reasoning")) + .and_then(drop) + { + Some(seal) => { + removed.push(seal); + false + } + None => true, + } + }); + } + _ => { + let messages = v.get_mut("messages")?.as_array_mut()?; + // 最后一条 assistant 消息开头的推理被去掉了、它又在调工具:Anthropic 要求 + // 开着推理时这条消息以推理开头,只能把这一轮的推理关掉 + let last = messages + .iter() + .rposition(|m| m.get("role").and_then(Value::as_str) == Some("assistant")); + let mut lost_lead = false; + for (i, m) in messages.iter_mut().enumerate() { + let Some(blocks) = m.get_mut("content").and_then(Value::as_array_mut) else { + continue; + }; + let mut first = true; + blocks.retain(|b| { + let lead = std::mem::take(&mut first); + let sealed = if is(b, "thinking") { + b.get("signature").and_then(Value::as_str) + } else if is(b, "redacted_thinking") { + b.get("data").and_then(Value::as_str) + } else { + None + }; + match sealed.filter(|s| !s.is_empty()).and_then(drop) { + Some(seal) => { + removed.push(seal); + lost_lead |= lead && Some(i) == last; + false + } + None => true, + } + }); + if lost_lead && Some(i) == last && !blocks.iter().any(|b| is(b, "tool_use")) { + lost_lead = false; + } + } + // 只剩推理的 assistant 消息去掉之后是空的:空消息会被拒 + messages.retain(|m| { + m.get("content") + .and_then(Value::as_array) + .is_none_or(|b| !b.is_empty()) + }); + if lost_lead && let Some(o) = v.as_object_mut() { + o.remove("thinking"); + } + } + } + if removed.is_empty() { + return None; + } + Some((serde_json::to_vec(&v).ok()?, removed)) +} + +fn is(block: &Value, kind: &str) -> bool { + block.get("type").and_then(Value::as_str) == Some(kind) +} + +fn seal(s: &str) -> Seal { + *blake3::hash(s.as_bytes()).as_bytes() +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn responses(items: Value) -> Vec { + json!({"model": "gpt-5", "input": items}) + .to_string() + .into_bytes() + } + + #[test] + fn openais_refusal_is_recognised_and_other_400s_are_not() { + let refused = json!({"error": { + "message": "The encrypted content for item rs_68 could not be verified.", + "type": "invalid_request_error", "param": null, "code": "invalid_encrypted_content"}}); + assert!(refusal(Dialect::Responses, refused.to_string().as_bytes())); + // 没带码、只有那句话的中转 + assert!(refusal( + Dialect::Responses, + br#"{"detail":"Could not decrypt the provided encrypted_content."}"# + )); + let other = json!({"error": {"message": "max_output_tokens is too large", "code": "invalid_value"}}); + assert!(!refusal(Dialect::Responses, other.to_string().as_bytes())); + // 格式不对上:Anthropic 的那句不算 Responses 的 + assert!(!refusal(Dialect::Chat, refused.to_string().as_bytes())); + } + + #[test] + fn anthropics_refusal_is_recognised() { + let refused = json!({"type": "error", "error": {"type": "invalid_request_error", + "message": "messages.1.content.0: Invalid `signature` in `thinking` block"}}); + assert!(refusal(Dialect::Anthropic, refused.to_string().as_bytes())); + let other = json!({"type": "error", "error": {"type": "invalid_request_error", + "message": "max_tokens: must be greater than thinking.budget_tokens"}}); + assert!(!refusal(Dialect::Anthropic, other.to_string().as_bytes())); + } + + #[test] + fn only_the_sealed_reasoning_leaves_a_responses_request() { + let body = responses(json!([ + {"role": "user", "content": "hi"}, + {"type": "reasoning", "id": "rs_1", "summary": [], "encrypted_content": "gAAA-other"}, + {"type": "function_call", "call_id": "c1", "name": "ls", "arguments": "{}"}, + {"type": "function_call_output", "call_id": "c1", "output": "a.txt"}, + {"type": "reasoning", "id": "rs_2", "summary": [], "encrypted_content": "gAAA-mine"}, + {"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "done"}]}, + ])); + let (out, removed) = strip(Dialect::Responses, &body, None).unwrap(); + assert_eq!(removed.len(), 2); + let v: Value = serde_json::from_slice(&out).unwrap(); + let kinds: Vec<_> = v["input"] + .as_array() + .unwrap() + .iter() + .map(|i| i["type"].as_str().unwrap_or("message").to_string()) + .collect(); + assert_eq!( + kinds, + [ + "message", + "function_call", + "function_call_output", + "message" + ] + ); + + // 只去掉拒过的那个:这一家自己后来封存的照样带上 + let only: HashSet = [seal("gAAA-other")].into(); + let (out, removed) = strip(Dialect::Responses, &body, Some(&only)).unwrap(); + assert_eq!(removed, [seal("gAAA-other")]); + let v: Value = serde_json::from_slice(&out).unwrap(); + assert!(v.to_string().contains("gAAA-mine")); + assert!(!v.to_string().contains("gAAA-other")); + } + + #[test] + fn nothing_to_strip_is_none() { + let body = responses(json!([{"role": "user", "content": "hi"}])); + assert!(strip(Dialect::Responses, &body, None).is_none()); + let only: HashSet = [seal("x")].into(); + let body = responses(json!([{"type": "reasoning", "encrypted_content": "y"}])); + assert!(strip(Dialect::Responses, &body, Some(&only)).is_none()); + assert!(strip(Dialect::Chat, &body, None).is_none()); + } + + #[test] + fn signed_thinking_leaves_an_anthropic_request_and_so_does_thinking_when_it_must() { + let body = json!({ + "model": "claude-opus-4-7", "max_tokens": 1000, + "thinking": {"type": "enabled", "budget_tokens": 800}, + "messages": [ + {"role": "user", "content": "hi"}, + {"role": "assistant", "content": [ + {"type": "thinking", "thinking": "想", "signature": "sig-a"}, + {"type": "text", "text": "你好"}, + ]}, + {"role": "user", "content": "列一下文件"}, + {"role": "assistant", "content": [ + {"type": "redacted_thinking", "data": "blob"}, + {"type": "tool_use", "id": "t1", "name": "ls", "input": {}}, + ]}, + {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": "a.txt"}]}, + ], + }) + .to_string(); + let (out, removed) = strip(Dialect::Anthropic, body.as_bytes(), None).unwrap(); + assert_eq!(removed, [seal("sig-a"), seal("blob")]); + let v: Value = serde_json::from_slice(&out).unwrap(); + assert_eq!( + v["messages"][1]["content"], + json!([{"type": "text", "text": "你好"}]) + ); + assert_eq!(v["messages"][3]["content"][0]["type"], "tool_use"); + // 调工具的那条不再以推理开头:这一轮的推理只能关掉 + assert!(v.get("thinking").is_none(), "{v}"); + } + + #[test] + fn thinking_stays_on_when_the_last_turn_still_leads_with_its_own_reasoning() { + let body = json!({ + "model": "claude-opus-4-7", "max_tokens": 1000, + "thinking": {"type": "enabled", "budget_tokens": 800}, + "messages": [ + {"role": "user", "content": "hi"}, + {"role": "assistant", "content": [{"type": "thinking", "thinking": "旧", "signature": "old"}]}, + {"role": "user", "content": "列一下文件"}, + {"role": "assistant", "content": [ + {"type": "thinking", "thinking": "新", "signature": "new"}, + {"type": "tool_use", "id": "t1", "name": "ls", "input": {}}, + ]}, + {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": "a.txt"}]}, + ], + }) + .to_string(); + let only: HashSet = [seal("old")].into(); + let (out, _) = strip(Dialect::Anthropic, body.as_bytes(), Some(&only)).unwrap(); + let v: Value = serde_json::from_slice(&out).unwrap(); + // 只剩推理的那条去掉了 + assert_eq!(v["messages"].as_array().unwrap().len(), 4); + assert_eq!(v["messages"][2]["content"][0]["signature"], "new"); + assert!(v.get("thinking").is_some()); + } + + #[test] + fn refusals_are_remembered_per_conversation_and_upstream_and_bounded() { + let r = Refused::default(); + r.note("conv", "relay", &[seal("a")], 1); + r.note("conv", "relay", &[seal("b")], 2); + assert_eq!(r.of("conv", "relay").unwrap().len(), 2); + assert!(r.of("conv", "official").is_none()); + assert!(r.of("other", "relay").is_none()); + for i in 0..PRUNE_AT + 10 { + r.note(&format!("c{i}"), "relay", &[seal("a")], 10 + i as u64); + } + assert!(r.by.lock().unwrap().len() <= PRUNE_AT); + } +} diff --git a/crates/tw-gateway/src/server/pipeline.rs b/crates/tw-gateway/src/server/pipeline.rs index 242cbe2e..17725304 100644 --- a/crates/tw-gateway/src/server/pipeline.rs +++ b/crates/tw-gateway/src/server/pipeline.rs @@ -49,6 +49,8 @@ struct Started { alive: Vec, /// 第一阶段的结论。路由事件在它上面补上第二阶段和尝试链 choice: Choice, + /// 这是哪段对话(见 [`crate::affinity::identity`])。认不出来是 None + conversation: Option, } pub(super) async fn pipeline( @@ -111,10 +113,17 @@ pub(super) async fn pipeline( ending, ); screen(&state, &rt, &reading, &started)?; - let served = hop::try_upstreams(&state, &rt, &req, &reading, &decision, &started).await?; + let answer = hop::try_upstreams(&state, &rt, &req, &reading, &decision, &started).await?; let mut ending = ending .take() .expect("written when the start event was emitted"); + // 网关估的数不是哪一家回答的:不记这段对话留在哪一家 + let served = match answer { + hop::Answer::Served(served) => *served, + hop::Answer::Estimated(body) => { + return Ok(estimated(&state, &req, started.id, body, ending)); + } + }; // 记下实际回答的那一家:故障转移之后接下的备选,就是这段对话之后留下的那一家 if let Some(c) = &conv { ending.answered_by(state.affinity.ticket( @@ -135,6 +144,43 @@ pub(super) async fn pipeline( )) } +/// 数 token 由网关估了数(见 [`crate::count`]):把它交给客户端,照常报响应头和结局。 +/// +/// **不经过 `relay`**:那里按上游的回答记首字节时间、额度、凭据和代理的状态,而这个 +/// 回答不是上游给的 —— 记上去的话,一家从没被问过的上游会显示成「刚刚答得飞快」。 +/// 响应头上带 `x-thinkwatch-local`,和本地应答的一样。 +fn estimated( + state: &AppState, + req: &Inbound, + id: u64, + body: Bytes, + mut ending: crate::ending::Ending, +) -> Response { + state.bus.emit(tw_api::Event::RequestHeaders { + id, + status: 200, + ttfb_ms: req.started.elapsed().as_millis() as u64, + }); + ending.responded(200); + // 留档:请求详情里看得到回了什么数 + ending.feed(&body); + ending.finished(200); + ( + [ + ( + axum::http::header::CONTENT_TYPE, + axum::http::HeaderValue::from_static("application/json"), + ), + ( + axum::http::HeaderName::from_static("x-thinkwatch-local"), + axum::http::HeaderValue::from_static("1"), + ), + ], + body, + ) + .into_response() +} + /// 管线第 1.3 步的结果。 enum Probe { /// 本地答了,不往下走 @@ -282,9 +328,11 @@ fn admit( .iter() .find(|c| c.name == req.client_name) .and_then(|c| c.allow.clone()); + // 数 token 也不挑格式:别的格式的上游由网关本地估算(见 `crate::count`) + let any = reading.generates || crate::client_api::ClientApi::counts_tokens(req.uri.path()); let servable = req .api - .map(|a| crate::client_api::slugs(a.servable_by(reading.generates))); + .map(|a| crate::client_api::slugs(a.servable_by(any))); // 阶段一之后要的模型。规则一家候选都没给时就看它 let model = decision.set.model.as_deref().unwrap_or(&facts.model); let mut models: Vec<&str> = asked.iter().map(|(_, m)| m.as_str()).collect(); @@ -297,24 +345,6 @@ 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." - ), - )); - } // 错误信息要说清是哪一种:没有上游提供它,和这个客户端不让用它, // 该去改的地方不一样。**改写过的两个名字都要说**:客户端写的是一个, // 报错里说的是另一个,不说清楚像是网关认错了模型 @@ -552,7 +582,12 @@ fn start( at_ms: now_ms(), }); } - Started { id, alive, choice } + Started { + id, + alive, + choice, + conversation: crate::affinity::identity(&req.headers, fp), + } } /// 发 `RequestStarted`、把这个请求欠着的结局放进 `ending`、把请求体交去留档, diff --git a/crates/tw-gateway/src/server/pipeline/hop.rs b/crates/tw-gateway/src/server/pipeline/hop.rs index 033277a1..a927a243 100644 --- a/crates/tw-gateway/src/server/pipeline/hop.rs +++ b/crates/tw-gateway/src/server/pipeline/hop.rs @@ -27,6 +27,14 @@ pub(super) struct Served<'a> { pub(super) session: Option, } +/// 这个请求的着落。 +pub(super) enum Answer<'a> { + /// 一家上游接下了它 + Served(Box>), + /// 数 token 的请求由网关本地估算(见 [`crate::count`]):要回给客户端的正文 + Estimated(Bytes), +} + /// 这一跳要发出去的东西。 struct Outbound { body: Bytes, @@ -53,8 +61,14 @@ pub(super) async fn try_upstreams<'a>( reading: &crate::client_api::Reading, decision: &tw_engine::Decision, started: &Started, -) -> Result, GatewayError> { +) -> Result, GatewayError> { let id = started.id; + // 数 token(见 `crate::count`):选中的那一家数不了就由网关估,**不换模型** + let counting = crate::client_api::ClientApi::counts_tokens(req.uri.path()); + // 数 token 第一跳要的模型(规则改写过的是改写后的)。往下只换要同一个模型的 + let mut count_model: Option> = None; + // 由网关估了数的那一家 + let mut estimated: Option<&tw_config::Provider> = None; let mut attempts: Vec = Vec::new(); // 每一跳的结果和耗时。**失败的原因要留着** —— 一条说「试过 A → B → // C」的链,和一条还说清每一跳为什么失败的链,排查价值差得远。 @@ -78,9 +92,20 @@ pub(super) async fn try_upstreams<'a>( ))); continue; }; + // 数 token 选中的那一家失败了(5xx、429、连不上):往下只换同格式的上游。 + // **别的格式的那几家不估**:选中的那一家出了错,报出来的该是这个错 + if counting && !attempts.is_empty() && !same_format(req, provider) { + continue; + } attempts.push(provider.name.clone()); let hop_started = std::time::Instant::now(); + // 数 token 选中的是别的格式的上游:不发,网关自己估 + if counting && attempts.len() == 1 && estimates(req, provider) { + chain.push(estimated_hop(provider, None, None, hop_started)); + estimated = Some(provider); + break; + } if let Some(err) = protocol_mismatch(req, reading.generates, provider) { chain.push(hop_failed( &provider.name, @@ -143,6 +168,17 @@ pub(super) async fn try_upstreams<'a>( .model .clone() .filter(|m| *m != reading.facts.model); + // 数 token 不换模型:另一个模型的 tokenizer 数出来的不是这个数 + if counting { + match &count_model { + None => count_model = Some(model.clone()), + Some(first) if *first != model => { + attempts.pop(); + continue; + } + Some(_) => {} + } + } let out = match prepare(state, req, reading, provider, &effective_set, id) { Ok(out) => out, @@ -158,10 +194,12 @@ pub(super) async fn try_upstreams<'a>( } }; + // 这一家在这段对话里拒过的别家封存的推理:发之前先去掉(见 `crate::seal`) + let unsealed = unseal_upfront(state, req, started, provider, &out); // 出站脱敏的拦截档:换掉**这一跳真正发出去的那一份**(可能转换过 // 格式)。规则是全局的,每一跳换掉的是同一批东西 let (body, ledger) = - crate::guard::replace(rt.config.security.redact.mode, &rt.redact, out.body.clone()); + crate::guard::replace(rt.config.security.redact.mode, &rt.redact, unsealed); // 用这个 provider 自己的 Client —— 它带着该走的代理。**在取密钥 // 之前拿到**:OAuth 换 token 也要走这条代理。 @@ -224,18 +262,32 @@ pub(super) async fn try_upstreams<'a>( "forwarding" ); - match send( + let sent = send( state, req, provider, http, &out, - body, - upstream_headers, + body.clone(), + upstream_headers.clone(), aws.as_ref(), ) - .await - { + .await; + // 上游拒绝了别家封存的推理:去掉它们,同一家再发一次 + let sent = match sent { + Ok(r) => { + let resend = Resend { + out: &out, + body: &body, + headers: &upstream_headers, + aws: aws.as_ref(), + conversation: started.conversation.as_deref(), + }; + resend_unsealed(state, req, provider, http, resend, r).await + } + Err(e) => Err(e), + }; + match sent { Ok(r) if r.status().is_server_error() || r.status() == 429 => { // 额度用完时上游回的正是 429,这一跳的额度头也要读 state.note_quota(id, &provider.name, r.headers()); @@ -290,6 +342,17 @@ pub(super) async fn try_upstreams<'a>( &provider.name, state.health.record_success(&provider.name), ); + // 同格式的上游没实现数 token(不少中转只做了生成回答):网关自己估 + if counting && crate::count::unsupported(r.status().as_u16()) { + chain.push(estimated_hop( + provider, + model.clone(), + Some(r.status().as_u16()), + hop_started, + )); + estimated = Some(provider); + break; + } chain.push(hop( &provider.name, model.clone(), @@ -341,10 +404,12 @@ pub(super) async fn try_upstreams<'a>( // 失败那条路就没有尝试链,而那恰恰是最需要看它的时候。 // 最终服务的那家怎么收钱。**跟着请求走,不能事后查配置** —— // 配置随时会被热重载,而一条三天前的记录该按它当时那家的算。 - let billing = served - .as_ref() - .map(|s| s.provider.billing) - .unwrap_or_default(); + // 网关估的数不花钱 + let billing = match (&served, estimated) { + (_, Some(_)) => tw_config::Billing::Free, + (Some(s), None) => s.provider.billing, + (None, None) => Default::default(), + }; let choice = &started.choice; state.bus.emit(tw_api::Event::RequestRouted { id, @@ -360,6 +425,18 @@ pub(super) async fn try_upstreams<'a>( if let Some(err) = halt { return Err(err); } + if let Some(provider) = estimated { + tracing::debug!(provider = %provider.name, "estimated the token count locally"); + let client = req + .api + .map(|a| a.dialect()) + .unwrap_or(tw_dialect::ir::Dialect::Anthropic); + return Ok(Answer::Estimated(Bytes::from(crate::count::answer( + client, + req.uri.path(), + &req.body, + )))); + } let Some(served) = served else { let mut err = last_err.unwrap_or_else(|| { @@ -385,7 +462,42 @@ pub(super) async fn try_upstreams<'a>( served.provider.name ); } - Ok(served) + Ok(Answer::Served(Box::new(served))) +} + +/// 这一家和客户端是同一种格式(配置里没写格式的也算:照原样发过去) +fn same_format(req: &Inbound, provider: &tw_config::Provider) -> bool { + match (req.api, provider.effective_protocol()) { + (Some(a), Some(p)) => a.protocol() == p, + _ => true, + } +} + +/// 数 token 选中了这一家,由网关自己估:它不是客户端那种格式。 +/// +/// **Anthropic 的数 token 到了 Bedrock 上游例外**,回 501(见 [`protocol_mismatch`]): +/// Claude Code 认那个回答,会自己去数一个准的。 +fn estimates(req: &Inbound, provider: &tw_config::Provider) -> bool { + !same_format(req, provider) + && !(req.api == Some(crate::client_api::ClientApi::AnthropicMessages) + && provider.effective_protocol() == Some(tw_config::Protocol::Bedrock)) +} + +/// 网关估了数的那一跳。`status` 是上游回的(它没实现数 token),没发出去的没有 +fn estimated_hop( + provider: &tw_config::Provider, + model: Option, + status: Option, + started: std::time::Instant, +) -> tw_api::AttemptView { + tw_api::AttemptView { + provider: provider.name.clone(), + model, + outcome: tw_api::AttemptOutcome::Estimated, + status, + error: None, + ms: started.elapsed().as_millis() as u64, + } } /// 生成回答以外的接口(计 token、嵌入……)没有别的格式可以转换,只能交给同格式 @@ -408,6 +520,7 @@ fn protocol_mismatch( // 数 token 到了 Bedrock 上游:501 `not_supported`,客户端会改用别的办法数(见 // `Source::NotSupported`)。**同样不发出去** if p == tw_config::Protocol::Bedrock + && a == crate::client_api::ClientApi::AnthropicMessages && crate::client_api::ClientApi::counts_tokens(req.uri.path()) { return Some(GatewayError::new( @@ -674,6 +787,102 @@ fn prepare( }) } +/// 这一跳发出去的那一份是什么格式:转换过的是目标格式,直通的是客户端的 +fn wire(req: &Inbound, out: &Outbound) -> Option { + out.target.or(req.api.map(|a| a.dialect())) +} + +/// 这一跳要发的请求体,去掉这一家在这段对话里拒过的封存(见 [`crate::seal`])。 +/// 没拒过的原样发 +fn unseal_upfront( + state: &AppState, + req: &Inbound, + started: &Started, + provider: &tw_config::Provider, + out: &Outbound, +) -> Bytes { + let refused = wire(req, out).zip( + started + .conversation + .as_deref() + .and_then(|c| state.seals.of(c, &provider.name)), + ); + match refused.and_then(|(w, only)| crate::seal::strip(w, &out.body, Some(&only))) { + Some((body, removed)) => { + tracing::debug!( + provider = %provider.name, + removed = removed.len(), + "left out the reasoning this upstream refused earlier in the conversation" + ); + Bytes::from(body) + } + None => out.body.clone(), + } +} + +/// 重发一次要用的:这一跳原来发的那些 +struct Resend<'a> { + out: &'a Outbound, + body: &'a Bytes, + headers: &'a [(String, String)], + aws: Option<&'a tw_bedrock::Credentials>, + conversation: Option<&'a str>, +} + +/// 上游回 400、拒绝了请求里别家封存的推理(见 [`crate::seal`]):去掉**全部**封存的 +/// 推理,同一家再发一次,只一次。拒过哪些记下来,这段对话往后发给它之前先去掉。 +/// +/// **不换一家**:换到哪一家都可能是另一个账号,同样解不开;而这一家好好的,只是 +/// 不认那几段笔记。不是这种 400 的原样交回去。 +async fn resend_unsealed( + state: &AppState, + req: &Inbound, + provider: &tw_config::Provider, + http: &reqwest::Client, + resend: Resend<'_>, + r: reqwest::Response, +) -> Result { + let Some(wire) = wire(req, resend.out) else { + return Ok(r); + }; + if r.status() != 400 { + return Ok(r); + } + let Some((stripped, removed)) = crate::seal::strip(wire, resend.body, None) else { + return Ok(r); + }; + let status = r.status(); + let headers = r.headers().clone(); + let said = r.bytes().await.map_err(SendError::Http)?; + if !crate::seal::refusal(wire, &said) { + let mut back = http::Response::new(said); + *back.status_mut() = status; + *back.headers_mut() = headers; + return Ok(reqwest::Response::from(back)); + } + if let Some(c) = resend.conversation { + state + .seals + .note(c, &provider.name, &removed, crate::server::now_ms()); + } + tracing::info!( + provider = %provider.name, + removed = removed.len(), + "the upstream refused reasoning sealed by another account; sending again without it" + ); + send( + state, + req, + provider, + http, + resend.out, + Bytes::from(stripped), + resend.headers.to_vec(), + resend.aws, + ) + .await +} + /// 这一跳发往的完整地址。 /// /// Bedrock 的模型 id 写在路径里,按 AWS 的规矩转义(ARN 里的 `/`),见 diff --git a/crates/tw-gateway/src/state.rs b/crates/tw-gateway/src/state.rs index eef33be7..3f27290b 100644 --- a/crates/tw-gateway/src/state.rs +++ b/crates/tw-gateway/src/state.rs @@ -209,6 +209,8 @@ pub struct AppState { pub sessions: Arc, /// 每段对话这一轮的路由决定、上次回答它的那一家(见 [`crate::affinity`])。**跨重载存活** pub affinity: Arc, + /// 每段对话里、每一家上游拒过的别家封存的推理(见 [`crate::seal`])。**跨重载存活** + pub seals: Arc, /// Anthropic 流里上游静默多久就补一个 `ping`(见 `relay`)。**测试会把它调短**, /// 否则一条心跳的测试要干等十五秒 pub ping_every: std::time::Duration, @@ -264,6 +266,7 @@ impl AppState { live: crate::live::Live::default(), sessions: Default::default(), affinity: Default::default(), + seals: Default::default(), ping_every: crate::PING_EVERY, ping_for: crate::PING_FOR, }; diff --git a/crates/tw-gateway/tests/bedrock.rs b/crates/tw-gateway/tests/bedrock.rs index 4a410475..0e6e051f 100644 --- a/crates/tw-gateway/tests/bedrock.rs +++ b/crates/tw-gateway/tests/bedrock.rs @@ -660,21 +660,18 @@ async fn counting_tokens_is_not_supported_the_way_claude_code_expects() { ) }; - // 模型清单还没取到:选上游时认出来 + // 模型清单还没取到 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}"); - // 取到了:准入时就认出来 + // 取到了:准入照样放行(数 token 不挑上游的格式),选上游时一样认出来 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!(text.contains("upstream `br`"), "{text}"); assert!( seen.lock().unwrap().iter().all(|s| s.method == "GET"), diff --git a/crates/tw-gateway/tests/conversion.rs b/crates/tw-gateway/tests/conversion.rs index c6652a9d..5df50aed 100644 --- a/crates/tw-gateway/tests/conversion.rs +++ b/crates/tw-gateway/tests/conversion.rs @@ -333,6 +333,8 @@ async fn an_upstream_error_comes_back_in_the_clients_error_shape() { ); } +/// 数 token 到了别的格式的上游:不转成一次真的补全(那要花钱),也不发过去 —— +/// 网关自己估一个数(见 `tw_gateway::count`) #[tokio::test] async fn counting_tokens_is_not_converted_into_a_paid_completion() { let (up, seen) = upstream(200, "application/json", "{}".into()).await; @@ -344,8 +346,8 @@ async fn counting_tokens_is_not_converted_into_a_paid_completion() { json!({"model": "deepseek-chat", "messages": [{"role": "user", "content": "hi"}]}), ) .await; - assert_eq!(status, 400, "{body}"); - assert!(body.contains("count_tokens"), "{body}"); + assert_eq!(status, 200, "{body}"); + assert!(body.contains("input_tokens"), "{body}"); assert!( seen.lock().unwrap().uri.is_empty(), "请求被发到了别的格式的上游" diff --git a/crates/tw-gateway/tests/fallbacks.rs b/crates/tw-gateway/tests/fallbacks.rs new file mode 100644 index 00000000..1f4d4b58 --- /dev/null +++ b/crates/tw-gateway/tests/fallbacks.rs @@ -0,0 +1,346 @@ +//! 上游接不住时网关替它补上的两件事,端到端。 +//! +//! - 数 token 选中了别的格式的上游、或者同格式的上游没实现它(404 / 405):网关 +//! 自己估一个数,一个字节都不发给别的格式的上游(见 `tw_gateway::count`) +//! - 上游拒绝了别的账号封存的推理:去掉它们同一家再发一次,这段对话往后发给它之前 +//! 先去掉拒过的那些(见 `tw_gateway::seal`) + +use std::net::SocketAddr; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use axum::Router; +use axum::extract::{OriginalUri, State}; +use serde_json::{Value, json}; +use tw_config::{Client, Config, Protocol, Provider}; + +/// 一个假上游收到的请求:路径和请求体 +type Seen = Arc>>; + +/// 一个假上游:按到达的顺序依次用 `replies` 回(用完了一直用最后一个),记下收到的请求。 +async fn upstream(replies: Vec<(u16, Value)>) -> (SocketAddr, Seen) { + let seen: Seen = Default::default(); + let app = Router::new() + .fallback( + move |State(s): State, OriginalUri(uri): OriginalUri, body: bytes::Bytes| { + let replies = replies.clone(); + async move { + let mut s = s.lock().unwrap(); + let n = s.len(); + s.push(( + uri.to_string(), + serde_json::from_slice(&body).unwrap_or(Value::Null), + )); + let (status, reply) = replies[n.min(replies.len() - 1)].clone(); + axum::response::Response::builder() + .status(status) + .header("content-type", "application/json") + .body(axum::body::Body::from(reply.to_string())) + .unwrap() + } + }, + ) + .with_state(seen.clone()); + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = l.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(l, app).await.unwrap() }); + (addr, seen) +} + +fn provider(name: &str, up: SocketAddr, protocol: Protocol) -> Provider { + Provider { + name: name.into(), + base_url: format!("http://{up}"), + key: Some("sk-upstream".into()), + protocol: Some(protocol), + ..Default::default() + } +} + +async fn gateway( + providers: Vec, +) -> (SocketAddr, tokio::sync::broadcast::Receiver) { + let cfg = Config { + version: 1, + clients: vec![Client { + name: "c".into(), + key: "tw-k".into(), + ..Default::default() + }], + providers, + ..Default::default() + }; + let state = tw_gateway::AppState::new(cfg).unwrap(); + let rx = state.bus.subscribe(); + let addr = tw_gateway::serve(state, ([127, 0, 0, 1], 0).into()) + .await + .unwrap(); + tokio::time::sleep(Duration::from_millis(50)).await; + (addr, rx) +} + +/// 发一个请求:状态码、`x-thinkwatch-local` 在不在、正文 +async fn post(gw: SocketAddr, path: &str, body: Value) -> (u16, bool, String) { + let resp = reqwest::Client::new() + .post(format!("http://{gw}{path}")) + .header("content-type", "application/json") + .header("x-api-key", "tw-k") + .header("authorization", "Bearer tw-k") + .body(body.to_string()) + .send() + .await + .unwrap(); + let status = resp.status().as_u16(); + let local = resp.headers().contains_key("x-thinkwatch-local"); + (status, local, resp.text().await.unwrap()) +} + +/// 这个请求的路由事件和结束事件 +async fn routed_and_finished( + rx: &mut tokio::sync::broadcast::Receiver, +) -> (Vec, tw_api::Billing, tw_api::Event) { + let mut routed = None; + loop { + let e = tokio::time::timeout(Duration::from_secs(5), rx.recv()) + .await + .expect("no ending") + .unwrap(); + match e { + tw_api::Event::RequestRouted { + attempts, billing, .. + } => routed = Some((attempts, billing)), + e @ (tw_api::Event::RequestFinished { .. } | tw_api::Event::RequestFailed { .. }) => { + let (attempts, billing) = routed.expect("routed before the ending"); + return (attempts, billing, e); + } + _ => {} + } + } +} + +const COUNT: &str = "/v1/messages/count_tokens"; + +fn count_body() -> Value { + json!({"model": "gpt-5", "system": "You are terse.", + "messages": [{"role": "user", "content": "Summarise the README in one line."}]}) +} + +#[tokio::test] +async fn counting_tokens_through_an_upstream_of_another_format_is_estimated_locally() { + let (up, seen) = upstream(vec![(500, json!({"error": "nothing should arrive"}))]).await; + let (gw, mut rx) = gateway(vec![provider("openai", up, Protocol::OpenaiChat)]).await; + let (status, local, body) = post(gw, COUNT, count_body()).await; + assert_eq!(status, 200, "{body}"); + assert!(local, "an estimate carries x-thinkwatch-local"); + let v: Value = serde_json::from_str(&body).unwrap(); + assert!(v["input_tokens"].as_u64().unwrap() > 5, "{v}"); + assert!(seen.lock().unwrap().is_empty(), "the upstream was asked"); + + let (attempts, billing, end) = routed_and_finished(&mut rx).await; + assert_eq!(attempts.len(), 1); + assert_eq!(attempts[0].provider, "openai"); + assert_eq!(attempts[0].outcome, tw_api::AttemptOutcome::Estimated); + assert_eq!(attempts[0].status, None, "nothing was sent"); + assert_eq!(billing, tw_api::Billing::Free); + assert!( + matches!( + end, + tw_api::Event::RequestFinished { + status: 200, + usage: None, + .. + } + ), + "{end:?}" + ); +} + +#[tokio::test] +async fn an_anthropic_relay_without_count_tokens_gets_estimated_for() { + let (up, seen) = upstream(vec![(404, json!({"error": "not found"}))]).await; + let (gw, mut rx) = gateway(vec![provider("relay", up, Protocol::Anthropic)]).await; + let (status, local, body) = post(gw, COUNT, count_body()).await; + assert_eq!((status, local), (200, true), "{body}"); + assert!(serde_json::from_str::(&body).unwrap()["input_tokens"].is_u64()); + assert_eq!(seen.lock().unwrap().len(), 1); + + let (attempts, _, _) = routed_and_finished(&mut rx).await; + assert_eq!(attempts[0].outcome, tw_api::AttemptOutcome::Estimated); + assert_eq!(attempts[0].status, Some(404), "what the relay said"); +} + +#[tokio::test] +async fn an_anthropic_upstream_that_counts_is_still_asked() { + let (up, seen) = upstream(vec![(200, json!({"input_tokens": 42}))]).await; + let (gw, _rx) = gateway(vec![provider("official", up, Protocol::Anthropic)]).await; + let (status, local, body) = post(gw, COUNT, count_body()).await; + assert_eq!((status, local), (200, false), "{body}"); + assert_eq!( + serde_json::from_str::(&body).unwrap(), + json!({"input_tokens": 42}) + ); + assert_eq!(seen.lock().unwrap().len(), 1); +} + +#[tokio::test] +async fn a_failed_count_does_not_move_to_an_upstream_of_another_format() { + // 选中的那一家 503:往下只换同格式的。别的格式的那一家既不问,也不替它估一个数 + let (a, seen_a) = upstream(vec![(503, json!({"error": "overloaded"}))]).await; + let (b, seen_b) = upstream(vec![(500, json!({"error": "nothing should arrive"}))]).await; + let (gw, mut rx) = gateway(vec![ + provider("official", a, Protocol::Anthropic), + provider("openai", b, Protocol::OpenaiChat), + ]) + .await; + let (status, local, body) = post(gw, COUNT, count_body()).await; + assert!(!local, "{body}"); + assert_eq!(status, 502, "{body}"); + assert_eq!(seen_a.lock().unwrap().len(), 1); + assert!(seen_b.lock().unwrap().is_empty()); + let (attempts, _, _) = routed_and_finished(&mut rx).await; + assert_eq!(attempts.len(), 1, "{attempts:?}"); +} + +#[tokio::test] +async fn geminis_count_tokens_is_estimated_in_geminis_shape() { + let (up, seen) = upstream(vec![(500, json!({"error": "nothing should arrive"}))]).await; + let (gw, _rx) = gateway(vec![provider("claude", up, Protocol::Anthropic)]).await; + let (status, local, body) = post( + gw, + "/v1beta/models/gemini-2.5-pro:countTokens", + json!({"contents": [{"role": "user", "parts": [{"text": "Summarise the README."}]}]}), + ) + .await; + assert_eq!((status, local), (200, true), "{body}"); + let v: Value = serde_json::from_str(&body).unwrap(); + assert!(v["totalTokens"].as_u64().unwrap() > 0, "{v}"); + assert!(seen.lock().unwrap().is_empty()); +} + +// ---------------------------------------------------------------- 封存的推理 + +fn refused_by_openai() -> (u16, Value) { + ( + 400, + json!({"error": {"message": "The encrypted content for item rs_1 could not be verified.", + "type": "invalid_request_error", "param": null, + "code": "invalid_encrypted_content"}}), + ) +} + +fn responses_ok() -> (u16, Value) { + ( + 200, + json!({"id": "resp_1", "object": "response", "status": "completed", "model": "gpt-5", + "output": [{"type": "message", "role": "assistant", + "content": [{"type": "output_text", "text": "done"}]}], + "usage": {"input_tokens": 10, "output_tokens": 2, "total_tokens": 12}}), + ) +} + +fn codex_turn(reasoning: &[&str]) -> Value { + let mut input = vec![json!({"role": "user", "content": "list the files"})]; + for (i, sealed) in reasoning.iter().enumerate() { + input.push( + json!({"type": "reasoning", "id": format!("rs_{i}"), "summary": [], + "encrypted_content": sealed}), + ); + input.push( + json!({"type": "function_call", "call_id": format!("c{i}"), "name": "ls", + "arguments": "{}"}), + ); + input.push( + json!({"type": "function_call_output", "call_id": format!("c{i}"), + "output": "a.txt"}), + ); + } + json!({"model": "gpt-5", "prompt_cache_key": "conv-1", "input": input, + "include": ["reasoning.encrypted_content"]}) +} + +fn sealed_in(v: &Value) -> Vec { + v["input"] + .as_array() + .unwrap() + .iter() + .filter_map(|i| i["encrypted_content"].as_str().map(str::to_string)) + .collect() +} + +#[tokio::test] +async fn reasoning_sealed_by_another_account_is_left_out_and_sent_again_once() { + let (up, seen) = upstream(vec![refused_by_openai(), responses_ok(), responses_ok()]).await; + let (gw, _rx) = gateway(vec![provider("openai", up, Protocol::OpenaiResponses)]).await; + + let (status, _, body) = post(gw, "/v1/responses", codex_turn(&["gAAA-other"])).await; + assert_eq!(status, 200, "{body}"); + { + let seen = seen.lock().unwrap(); + assert_eq!(seen.len(), 2, "refused, then sent again"); + assert_eq!(sealed_in(&seen[0].1), ["gAAA-other"]); + assert!(sealed_in(&seen[1].1).is_empty()); + // 说过的话、调过的工具都还在 + assert_eq!(seen[1].1["input"].as_array().unwrap().len(), 3); + } + + // 下一轮:拒过的那段发之前就去掉,这一家自己后来封存的照样带上。不再先被拒一次 + let (status, _, body) = post( + gw, + "/v1/responses", + codex_turn(&["gAAA-other", "gAAA-mine"]), + ) + .await; + assert_eq!(status, 200, "{body}"); + let seen = seen.lock().unwrap(); + assert_eq!(seen.len(), 3); + assert_eq!(sealed_in(&seen[2].1), ["gAAA-mine"]); +} + +#[tokio::test] +async fn another_400_comes_back_as_it_was_and_is_not_sent_again() { + let reply = json!({"error": {"message": "max_output_tokens is too large", + "type": "invalid_request_error", "code": "invalid_value"}}); + let (up, seen) = upstream(vec![(400, reply.clone()), responses_ok()]).await; + let (gw, _rx) = gateway(vec![provider("openai", up, Protocol::OpenaiResponses)]).await; + let (status, _, body) = post(gw, "/v1/responses", codex_turn(&["gAAA-other"])).await; + assert_eq!(status, 400); + assert_eq!(serde_json::from_str::(&body).unwrap(), reply); + assert_eq!(seen.lock().unwrap().len(), 1); +} + +#[tokio::test] +async fn a_refused_thinking_signature_is_left_out_and_sent_again() { + let refused = json!({"type": "error", "error": {"type": "invalid_request_error", + "message": "messages.1.content.0: Invalid `signature` in `thinking` block"}}); + let ok = json!({"id": "msg_1", "type": "message", "role": "assistant", "model": "claude-opus-4-7", + "content": [{"type": "text", "text": "好"}], "stop_reason": "end_turn", + "usage": {"input_tokens": 10, "output_tokens": 1}}); + let (up, seen) = upstream(vec![(400, refused), (200, ok)]).await; + let (gw, _rx) = gateway(vec![provider("relay", up, Protocol::Anthropic)]).await; + let (status, _, body) = post( + gw, + "/v1/messages", + json!({ + "model": "claude-opus-4-7", "max_tokens": 2000, + "thinking": {"type": "enabled", "budget_tokens": 1024}, + "messages": [ + {"role": "user", "content": "hi"}, + {"role": "assistant", "content": [ + {"type": "thinking", "thinking": "想", "signature": "EqQBCkgIBx"}, + {"type": "text", "text": "你好"}, + ]}, + {"role": "user", "content": "再说一句"}, + ], + }), + ) + .await; + assert_eq!(status, 200, "{body}"); + let seen = seen.lock().unwrap(); + assert_eq!(seen.len(), 2); + assert_eq!( + seen[1].1["messages"][1]["content"], + json!([{"type": "text", "text": "你好"}]) + ); + // 最后一条 assistant 消息不在调工具:推理照样开着 + assert!(seen[1].1.get("thinking").is_some()); +} diff --git a/crates/tw-store/src/recorder.rs b/crates/tw-store/src/recorder.rs index c281bbc0..1b35326c 100644 --- a/crates/tw-store/src/recorder.rs +++ b/crates/tw-store/src/recorder.rs @@ -634,6 +634,13 @@ impl Recorder { // 这家所选价目表里该模型的单价」,订阅账号算出来的就是按 API 价格 // 折算的费用。**不计费的记 $0**:那是一个确定的数。 let free = p.billing == tw_api::Billing::Free; + // 数 token 由网关本地估算的(尝试链停在 `estimated` 上):和本地应答一样记成 + // `local` —— 没有用掉谁的 token,汇总和 token 统计都不算它 + let local = p + .routing + .attempts + .last() + .is_some_and(|a| a.outcome == tw_api::AttemptOutcome::Estimated); // // **没跑完的一律按估算记**(取消、失败)。输出只算到断开那一刻,而 // Anthropic 在流的末尾才报累计输出 —— 断在中间时手里那个数是个 @@ -649,13 +656,13 @@ impl Recorder { .last() .and_then(|a| a.model.as_deref()) .unwrap_or(&p.model); - let resolved = if free { + let resolved = if free || local { None } else { book.resolve_for(&p.provider, priced_as) }; let cost = match (&u, &resolved) { - _ if free => Some(Cost::Known(0)), + _ if free || local => Some(Cost::Known(0)), (Some(u), Some(r)) => Some(r.cost(u, partial)), _ => None, }; @@ -720,7 +727,7 @@ impl Recorder { Ending::Failed(message) => Some((*message).clone()), _ => None, }, - local: false, + local, cancelled: matches!(how, Ending::Cancelled), routing: serde_json::to_string(&p.routing).ok(), billing: p.billing, @@ -1288,6 +1295,42 @@ mod tests { assert_eq!(s.locally_answered, 1); } + /// 数 token 由网关估了数:这一行是网关自己答的,费用 0,不进汇总 + #[test] + fn a_token_count_estimated_locally_is_marked_local_and_free() { + let (_d, mut r) = rec(); + r.on_event(&started(3, "gpt-5")); + r.on_event(&Event::RequestRouted { + id: 3, + route: "default".into(), + rule: "默认".into(), + group: None, + rewritten_by: vec![], + denied_by: None, + attempts: vec![tw_api::AttemptView { + provider: "官方".into(), + model: None, + outcome: tw_api::AttemptOutcome::Estimated, + status: Some(404), + error: None, + ms: 80, + }], + billing: tw_api::Billing::Free, + affinity: None, + }); + r.on_event(&finished(3, None)); + let row = r.db().get(3).unwrap().unwrap(); + assert!(row.local); + assert_eq!(row.cost_micros, Some(0)); + // 尝试链照样在:看得出估数是因为这一家没实现数 token + let routing: tw_api::RoutingView = + serde_json::from_str(row.routing.as_deref().unwrap()).unwrap(); + assert_eq!(routing.attempts[0].status, Some(404)); + let s = r.db().summary(0, i64::MAX).unwrap(); + assert_eq!(s.requests, 0, "估的数混进了请求总数"); + assert_eq!(s.locally_answered, 1); + } + #[test] fn a_finish_without_a_start_is_ignored_rather_than_writing_a_row_full_of_holes() { // 进程刚起来时,上一轮的请求可能还会送来结束事件。