diff --git a/desktop-tauri/src-tauri/server/src/server/core/capability.rs b/desktop-tauri/src-tauri/server/src/server/core/capability.rs index 231d62921..84632f3bd 100644 --- a/desktop-tauri/src-tauri/server/src/server/core/capability.rs +++ b/desktop-tauri/src-tauri/server/src/server/core/capability.rs @@ -49,6 +49,14 @@ pub fn is_token_key(key: &str) -> bool { key == "maxInputTokens" || key == "maxOutputTokens" } +/// 条目的工具调用能力(发前预剥的读数):`Some(false)` = 明确不支持; +/// `Some(true)` = 明确支持;`None` = 没声明(缺失 / null / 非 bool)或条目缺失。 +/// +/// 调用方注意 `None ≠ Some(false)`:没声明的不当成不支持,只走模型名启发。 +pub fn tool_call_support(item: &Value) -> Option { + item.get("supportsToolCall").and_then(Value::as_bool) +} + /// 该键是不是布尔能力键。 pub fn is_bool_key(key: &str) -> bool { key == "supportsToolCall" diff --git a/desktop-tauri/src-tauri/server/src/server/core/model_rules/mod.rs b/desktop-tauri/src-tauri/server/src/server/core/model_rules/mod.rs index 86b26cc12..2d3d1774b 100644 --- a/desktop-tauri/src-tauri/server/src/server/core/model_rules/mod.rs +++ b/desktop-tauri/src-tauri/server/src/server/core/model_rules/mod.rs @@ -650,6 +650,41 @@ pub(crate) fn save(rules: &ModelRules) -> bool { use bindings::set_membership; +/// 一次工具降级的预剥判定(发前闸门用):`Strip` = 现在就剥(不动上游)。 +/// +/// 只有 `supportsToolCall == Some(false)` 才给 `Strip`:那是目录里**明确声明** +/// 不支持。`None`(没声明 / null / 非 bool)**不是**不支持,走模型名启发 +/// (`model_suggests_no_tools`);`Some(true)` 不剥。 +pub(crate) enum ToolStrip { + Strip, + Keep, +} + +pub(crate) fn tool_strip_for(provider: &str, wire_model: &str) -> ToolStrip { + let item = crate::server::core::providers::catalog::manifest_for_provider(provider) + .into_iter() + .find(|entry| { + crate::server::core::models::model_id(entry).eq_ignore_ascii_case(wire_model.trim()) + }); + match item.as_ref().map(crate::server::core::capability::tool_call_support) { + Some(Some(false)) => ToolStrip::Strip, + Some(Some(true)) => ToolStrip::Keep, + Some(None) | None => { + if model_suggests_no_tools(wire_model) { ToolStrip::Strip } else { ToolStrip::Keep } + } + } +} + +/// 模型名启发:ocr / embedding / reranker 类名字按不支持工具处理。 +/// +/// 只在能力位**没声明**时用(`None ≠ false`,见 `tool_strip_for`)—— 有明确 +/// 声明的一律以声明为准。大小写不敏感;匹配子串而非整词(`text-embedding-3` +/// 这类带前后缀的名字同样命中)。 +fn model_suggests_no_tools(model: &str) -> bool { + let lower = model.trim().to_ascii_lowercase(); + lower.contains("ocr") || lower.contains("embed") || lower.contains("rerank") +} + /// **上游模型 id / 自生成别名**的字符集口径:字母 / 数字 / `- _ . / :`。 /// /// 只用在两处 —— 手动登记的上游模型 id(`api::model_manage` 的 `/api/models/custom`) @@ -761,3 +796,33 @@ pub fn custom_models_for(provider: &str) -> Vec { }) .collect() } + +#[cfg(test)] +mod tool_strip_tests { + use super::model_suggests_no_tools; + use crate::server::core::capability::tool_call_support; + + /// 模型名启发:ocr / embedding / reranker 命中,其余不命中。 + #[test] + fn name_heuristic_hits_ocr_embedding_reranker() { + for name in ["ocr-pro", "text-embedding-3", "reranker-v2", "OCR"] { + assert!(model_suggests_no_tools(name), "{name} 应当启发为不支持工具"); + } + for name in ["gpt-4o", "deepseek-v4", ""] { + assert!(!model_suggests_no_tools(name), "{name} 不该被启发"); + } + } + + /// 能力位读数:Some(false) 明确不支持;None(缺失/null/非 bool)不是不支持。 + #[test] + fn tool_call_support_distinguishes_none_from_false() { + let no = serde_json::json!({"id": "x", "supportsToolCall": false}); + assert_eq!(tool_call_support(&no), Some(false)); + let missing = serde_json::json!({"id": "x"}); + assert_eq!(tool_call_support(&missing), None); + let null = serde_json::json!({"id": "x", "supportsToolCall": null}); + assert_eq!(tool_call_support(&null), None); + let yes = serde_json::json!({"id": "x", "supportsToolCall": true}); + assert_eq!(tool_call_support(&yes), Some(true)); + } +} diff --git a/desktop-tauri/src-tauri/server/src/server/core/protocol/mod.rs b/desktop-tauri/src-tauri/server/src/server/core/protocol/mod.rs index f49647040..60772406c 100644 --- a/desktop-tauri/src-tauri/server/src/server/core/protocol/mod.rs +++ b/desktop-tauri/src-tauri/server/src/server/core/protocol/mod.rs @@ -60,6 +60,7 @@ pub mod native_tool; pub mod responses; pub mod responses_outbound; mod responses_phase; +pub mod tool_args; pub mod tool_plan; pub mod usage; diff --git a/desktop-tauri/src-tauri/server/src/server/core/protocol/native_tool.rs b/desktop-tauri/src-tauri/server/src/server/core/protocol/native_tool.rs index 067b088a8..df03b6cf6 100644 --- a/desktop-tauri/src-tauri/server/src/server/core/protocol/native_tool.rs +++ b/desktop-tauri/src-tauri/server/src/server/core/protocol/native_tool.rs @@ -259,6 +259,51 @@ pub fn strip_cross_protocol(body: &Value, target: &str) -> Option<(Value, Downgr }) } +/// 不支持工具的上游:整份 `tools` 全剥 + `tool_choice` 能降级就降。 +/// +/// 与 [`downgrade`] 的区别:那道闸门只剔原生声明、保留 `type:"function"`; +/// 这里是「这家**什么工具都不接**」—— function 留着同样整轮 400。 +/// `tool_choice` 只降 `auto`(字符串 `"auto"` 或 `{type:"auto"}` 这类无点名形态), +/// 点名具体工具的一律撤掉(工具都没了,点名必是「指定的工具不存在」)。 +pub fn strip_all_tools(body: &Value) -> Option<(Value, Downgrade)> { + let mut next = body.clone(); + let mut dropped: Vec = Vec::new(); + if let Some(tools) = body.get("tools").and_then(Value::as_array) { + if !tools.is_empty() { + dropped = tools.clone(); + if let Some(object) = next.as_object_mut() { + object.remove("tools"); + } + } + } + let mut choice: Option = None; + if let Some(current) = next.get("tool_choice").cloned() { + if super::string_field(¤t, "type").eq_ignore_ascii_case("auto") + || current.as_str().is_some_and(|text| text.trim().eq_ignore_ascii_case("auto")) + { + if let Some(object) = next.as_object_mut() { + object.insert("tool_choice".to_string(), Value::String("auto".to_string())); + } + choice = Some("不支持工具的上游,tool_choice 降为 auto".to_string()); + } else if let Some(reason) = choice_conflict(¤t, &dropped) { + if let Some(object) = next.as_object_mut() { + object.remove("tool_choice"); + } + choice = Some(reason); + } else if next.get("tool_choice").is_some() { + // 非 auto 又没点中被剔工具:工具都没了,留着它同样整轮 400。 + if let Some(object) = next.as_object_mut() { + object.remove("tool_choice"); + } + choice = Some("tools 已整份剥离,tool_choice 一并撤掉".to_string()); + } + } + if dropped.is_empty() && choice.is_none() { + return None; + } + Some((next, Downgrade { tools: dropped, choice })) +} + /// 剔除与 `tool_choice` 撤回的共同实现(两个口径只差 `should_drop` 判据)。 fn strip_with bool>(body: &Value, should_drop: F) -> Option<(Value, Downgrade)> { let mut next = body.clone(); diff --git a/desktop-tauri/src-tauri/server/src/server/core/protocol/responses.rs b/desktop-tauri/src-tauri/server/src/server/core/protocol/responses.rs index 80a95ec95..caa85c78c 100644 --- a/desktop-tauri/src-tauri/server/src/server/core/protocol/responses.rs +++ b/desktop-tauri/src-tauri/server/src/server/core/protocol/responses.rs @@ -26,7 +26,7 @@ use serde_json::{json, Map, Value}; use super::{ content_parts, content_text, event_frame, freeform, is_truthy, json_text, native_tool, - random_id, responses_phase, string_field, string_value, tool_plan, SseLineBuffer, TOOL_IMAGE_PLACEHOLDER, + random_id, responses_phase, string_field, string_value, tool_args, tool_plan, SseLineBuffer, TOOL_IMAGE_PLACEHOLDER, FIELD_ENCRYPTED_CONTENT, }; use crate::server::logging; @@ -1046,12 +1046,19 @@ pub fn responses_from_chat( output.push(item); } if let Some(calls) = tool_calls { + // 引号数字归一化(`server-shim` v2.7 的干净版):回程 arguments 原样 + // 透传时,flash 级别模型发的 `{"limit":"10"}` 会在客户端侧严格反序列化 + // 失败。映射表只认本次请求的 tools 声明(见 `tool_args` 模块头), + // 修不了的保持原样 —— 最坏只是不生效,永远不坏流。 + let numerics = tool_args::NumericFields::build_numeric_map(request); for call in calls { let name = call.pointer("/function/name").map(string_value).unwrap_or_default(); let arguments = call .pointer("/function/arguments") .map(json_text) .unwrap_or_else(|| "{}".to_string()); + let arguments = tool_args::fix_args_str(&numerics, &name, &arguments) + .unwrap_or(arguments); let call_id = { let raw = string_field(call, "id"); if raw.is_empty() { random_id("call") } else { raw } @@ -1554,6 +1561,14 @@ impl ResponsesStream { let is_custom = self.plan.is_custom(&name); if announced_now { + // 引号数字归一化(`server-shim` v2.7 的干净版):宣告前攒下的 + // 参数是完整 JSON(名字与参数同一帧到达时),单 call 可解析即修; + // 多 call / 不完整保持原样 —— 只丢修复不坏流(见 `tool_args`)。 + let numerics = tool_args::NumericFields::build_numeric_map(&self.request); + let buffered = (!is_custom) + .then(|| tool_args::fix_args_str(&numerics, &name, &buffered)) + .flatten() + .unwrap_or(buffered); // 自由文本工具的「参数」是裸文本 input,item 形态与 function 不同 // —— 见官方 custom_tool_call 项的定义 let item = if is_custom { @@ -1820,6 +1835,18 @@ impl ResponsesStream { // 但也不能丢 —— 补一个占位名,否则客户端少一次工具调用 let name = if tool.name.is_empty() { "unknown".to_string() } else { tool.name.clone() }; let arguments = if tool.arguments.is_empty() { "{}".to_string() } else { tool.arguments.clone() }; + // 流式收尾同一归一化:`close_tools` 拿到的是完整 arguments, + // 单 call 可解析即修,多 call / 残缺保持原样(见 `tool_args`)。 + let arguments = (!self.plan.is_custom(&name)) + .then(|| { + tool_args::fix_args_str( + &tool_args::NumericFields::build_numeric_map(&self.request), + &name, + &arguments, + ) + }) + .flatten() + .unwrap_or(arguments); // 用统一口径构造 item:custom 命中时要输出 custom_tool_call 与 // 裸文本 input,类型给错客户端就按 JSON 解析,工具照样跑不起来 let item = { @@ -2042,6 +2069,14 @@ impl ResponsesCollector { let name = if tool.name.is_empty() { "unknown".to_string() } else { tool.name }; let call_id = if tool.call_id.is_empty() { random_id("call") } else { tool.call_id }; let arguments = if tool.arguments.is_empty() { "{}".to_string() } else { tool.arguments }; + // 聚合出口同一归一化:聚合的是完整 JSON,单 call 可解析即修, + // 修不了保持原样(见 `tool_args` 模块头)。 + let arguments = tool_args::fix_args_str( + &tool_args::NumericFields::build_numeric_map(request), + &name, + &arguments, + ) + .unwrap_or(arguments); // 与另外两个回程出口共用口径:custom 命中时输出 custom_tool_call // (item id 的前缀由 tool_call_item 内部按类型选,不必在这里管) output.push(tool_call_item(&name, &call_id, &arguments, &plan)); diff --git a/desktop-tauri/src-tauri/server/src/server/core/protocol/tool_args.rs b/desktop-tauri/src-tauri/server/src/server/core/protocol/tool_args.rs new file mode 100644 index 000000000..343f68c4f --- /dev/null +++ b/desktop-tauri/src-tauri/server/src/server/core/protocol/tool_args.rs @@ -0,0 +1,357 @@ +//! 参数引号数字归一化(`server-shim` v2.7 的干净版)。 +//! +//! 为什么需要它 ─────────────────────────────── +//! flash 级别模型会把可选数值参数发成字符串(`{"limit":"10"}`), +//! grok 在 PreToolUse hook 之前用严格 serde 解析 arguments,一个 +//! `invalid type: string "10", expected u8` 就烧掉整个调用。 +//! 请求体自带每个工具的 JSON schema,数值字段集从那里读 +//! 而不是硬编码:修复对路过的任何客户端/模型都精确, +//! 字符串字段(电话号码、日期、页码区间)永远碰不到。 +//! +//! 三条硬约束(与 shim 同口径)──────────────── +//! 1. 只认本次请求 `tools[].function.parameters.properties` 声明为 +//! `integer` / `number`(含 `["integer","null"]` 联合)的字段,附 +//! `minimum` / `maximum` 边界校验; +//! 2. 越界 / 前导零 / 空串保持原样,不 clamp; +//! 3. 只有完整、可解析的参数载荷才重写,其余字节级透传。 +//! +//! release 是 `panic=abort`:本模块零 unwrap/expect,取值一律走 Option 链。 + +use std::collections::BTreeMap; + +use serde_json::{Map, Value}; + +/// `"10"` → 10 用的整形判定(shim 的 `INT_ARG_RE`,同口径手写)。 +/// +/// 前导零保留原样:`010` 哲学上可能是八进制,而不是十进制 10, +/// 减法前导零会让不同语言的客户端解出不同的数。 +/// +/// 不用 regex:这两个创格简单到手写更可靠,还省一次编译期依赖。 +fn is_int_shape(text: &str) -> bool { + let digits = text + .strip_prefix('+') + .or_else(|| text.strip_prefix('-')) + .unwrap_or(text); + if digits == "0" { + return true; + } + let mut chars = digits.chars(); + match chars.next() { + Some('1'..='9') => chars.all(|c| c.is_ascii_digit()), + _ => false, + } +} + +/// `"10.5"` → 10.5 用的字面量判定(shim 的 `NUM_ARG_RE`,同口径手写)。 +/// +/// 返回 `Some(带不带小数点)`,形状不对返回 None。 +fn num_shape(text: &str) -> Option { + let digits = text + .strip_prefix('+') + .or_else(|| text.strip_prefix('-')) + .unwrap_or(text); + let mut parts = digits.split('.'); + let int_part = parts.next()?; + if !is_int_shape(int_part) { + return None; + } + match parts.next() { + // 无小数点:纯整数形状 + None => Some(false), + Some(frac) => { + // 第二个点有多余分片;空小数点(`10.`)也不算数 + if parts.next().is_some() { + return None; + } + if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + Some(true) + } + } +} + +/// 工具名 → 字段名 → (类型, 下界, 上界)。 +/// +/// 映射表只含数值声明的字段:只有告诉网关「可以修」 +/// 的,网关才修。 +#[derive(Default, Debug, Clone)] +pub struct NumericFields { + inner: BTreeMap, Option)>>, +} + +/// 一个声明的数值类型(`pub(crate)`:调用方只关心「修 / 不修」, +/// 具体 kind 是内部判定细节,不对外暴露)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum NumKind { + Integer, + Number, +} + +impl NumericFields { + /// 本次请求的 tools 声明 → 数值字段映射表。 + /// + /// 只认 `tools[].function.parameters.properties` 声明为 integer / + /// number(含 nullable union)的字段;其余字段(电话号码、 + /// 日期……)不进表,决不碰。 + pub fn build_numeric_map(request: &Value) -> Self { + let mut out = NumericFields::default(); + let Some(tools) = request.get("tools").and_then(Value::as_array) else { + return out; + }; + for tool in tools { + let Some(function) = tool.get("function") else { + continue; + }; + let name = function + .get("name") + .and_then(Value::as_str) + .unwrap_or("") + .to_string(); + let Some(properties) = function + .get("parameters") + .and_then(|parameters| parameters.get("properties")) + .and_then(Value::as_object) + else { + continue; + }; + if name.is_empty() { + continue; + } + let mut fields = BTreeMap::new(); + for (field, declared) in properties { + let Some(kind) = num_kind_of(declared.get("type")) else { + continue; + }; + fields.insert( + field.clone(), + ( + kind, + schema_bound(declared.get("minimum")), + schema_bound(declared.get("maximum")), + ), + ); + } + if !fields.is_empty() { + out.inner.insert(name, fields); + } + } + out + } + + pub fn is_empty(&self) -> bool { + self.inner.is_empty() + } + + /// 某工具的某字段是否声明为数值(`pub(crate)`:同模块族内部用)。 + pub(crate) fn field_of(&self, tool: &str, field: &str) -> Option<(NumKind, Option, Option)> { + self.inner.get(tool)?.get(field).copied() + } +} + +/// JSON-schema `type`(字符串或 nullable union)→ 数值类型。 +/// +/// `integer` 优先于 `number`:union 里两者都有时,整形 +/// 创格更严、更安全(修复后的值一定能过整形校验)。 +fn num_kind_of(declared: Option<&Value>) -> Option { + let mut kind: Option = None; + match declared { + Some(Value::String(single)) if single == "integer" => Some(NumKind::Integer), + Some(Value::String(single)) if single == "number" => Some(NumKind::Number), + Some(Value::Array(union)) => { + for member in union { + match member.as_str() { + Some("integer") => { + kind = Some(NumKind::Integer); + break; + } + Some("number") => kind = Some(NumKind::Number), + _ => {} + } + } + kind + } + _ => None, + } +} + +/// schema 的 minimum/maximum:只有有限数值才算数,bool 不算。 +fn schema_bound(value: Option<&Value>) -> Option { + value?.as_f64().filter(|number| number.is_finite()) +} + +/// 引号数字 → 整形/浮点,拿不准返回 None(保持原样)。 +/// +/// 返回 None 的几种情况:不是数字形状(前导零、空串、 +/// 电话号码含 - 等)、解析失败、越界(schema 有 +/// minimum/maximum 时)。越界保留原样而不是 clamp:保留了 +/// 原始错误信息可观测,上游还是会 400,模型自己会改。 +pub fn coerce(text: &str, kind: NumKind, lo: Option, hi: Option) -> Option { + let trimmed = text.trim(); + let number: f64 = match kind { + NumKind::Integer => { + if !is_int_shape(trimmed) { + return None; + } + trimmed.parse::().ok()? as f64 + } + NumKind::Number => { + let has_dot = match num_shape(trimmed) { + Some(has_dot) => has_dot, + None => return None, + }; + if has_dot { + trimmed.parse::().ok()? + } else { + trimmed.parse::().ok()? as f64 + } + } + }; + if !number.is_finite() { + return None; + } + if lo.is_some_and(|lo| number < lo) || hi.is_some_and(|hi| number > hi) { + return None; + } + if kind == NumKind::Integer { + // i64::MIN..=i64::MAX 是 parse 保证的,转换不会越界。 + Some(Value::from(number as i64)) + } else if trimmed.contains('.') { + Some(Value::from(number)) + } else { + Some(Value::from(number as i64)) + } +} + +/// 已解析的 arguments 对象就地修复:返回是否改动。 +/// +/// 只动明确为字符串的值:数字本体、bool、null、数组、 +/// 对象一律不动。 +pub fn fix_object( + args: &mut Map, + fields: &BTreeMap, Option)>, +) -> bool { + let mut changed = false; + for (field, (kind, lo, hi)) in fields { + let Some(raw) = args.get(field).and_then(Value::as_str) else { + continue; + }; + if let Some(number) = coerce(raw, *kind, *lo, *hi) { + args.insert(field.clone(), number); + changed = true; + } + } + changed +} + +/// 工具名 + arguments 字符串 → 修复后的 arguments 字符串。 +/// +/// 不可解析 / 无匹配字段 / 无改动时返回 None(调用方保持原样)。 +pub fn fix_args_str(map: &NumericFields, tool: &str, raw: &str) -> Option { + let fields = map.inner.get(tool)?; + let mut args: Value = serde_json::from_str(raw).ok()?; + let changed = fix_object(args.as_object_mut()?, fields); + if !changed { + return None; + } + serde_json::to_string(&args).ok() +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn request_with_props(props: Value) -> Value { + json!({ + "tools": [{ + "type": "function", + "function": { + "name": "get_items", + "parameters": { "type": "object", "properties": props } + } + }] + }) + } + + /// `{"limit":"10"}` → `{"limit":10}`:最基本的修复。 + #[test] + fn quoted_integer_is_coerced() { + let map = NumericFields::build_numeric_map( + &request_with_props(json!({ "limit": { "type": "integer" } })), + ); + assert_eq!( + fix_args_str(&map, "get_items", r#"{"limit":"10"}"#), + Some(r#"{"limit":10}"#.to_string()) + ); + } + + /// `"010"` 不动:哲学上可能是八进制,减法前导零会歪曲语义。 + #[test] + fn leading_zero_is_kept() { + let map = NumericFields::build_numeric_map( + &request_with_props(json!({ "limit": { "type": "integer" } })), + ); + assert_eq!(fix_args_str(&map, "get_items", r#"{"limit":"010"}"#), None); + } + + /// 越界保持原样:让上游 400 报错可观测,模型自己会改, + /// 网关不 clamp。 + #[test] + fn out_of_range_is_kept() { + let map = NumericFields::build_numeric_map(&request_with_props( + json!({ "limit": { "type": "integer", "minimum": 1, "maximum": 5 } }), + )); + assert_eq!(fix_args_str(&map, "get_items", r#"{"limit":"10"}"#), None); + } + + /// 电话号码不动:没声明为数值的字段决不碰。 + #[test] + fn phone_string_is_kept() { + let map = NumericFields::build_numeric_map( + &request_with_props(json!({ "phone": { "type": "string" } })), + ); + assert_eq!( + fix_args_str(&map, "get_items", r#"{"phone":"13800138000"}"#), + None + ); + } + + /// nullable union `["integer","null"]` 生效(schemars 对 Option + /// 的渲染,flash 级别模型最容易发成字符串的就是这种)。 + #[test] + fn nullable_union_is_coerced() { + let map = NumericFields::build_numeric_map(&request_with_props( + json!({ "limit": { "type": ["integer", "null"] } }), + )); + assert_eq!( + fix_args_str(&map, "get_items", r#"{"limit":"10"}"#), + Some(r#"{"limit":10}"#.to_string()) + ); + } + + /// `"10.5"` → 10.5;整形字段拒绝小数。 + #[test] + fn number_and_integer_kinds() { + let map = NumericFields::build_numeric_map(&request_with_props( + json!({ "ratio": { "type": "number" }, "limit": { "type": "integer" } }), + )); + assert_eq!( + fix_args_str(&map, "get_items", r#"{"ratio":"10.5"}"#), + Some(r#"{"ratio":10.5}"#.to_string()) + ); + assert_eq!( + fix_args_str(&map, "get_items", r#"{"limit":"10.5"}"#), + None + ); + } + + /// 空串保持原样。 + #[test] + fn empty_string_is_kept() { + let map = NumericFields::build_numeric_map( + &request_with_props(json!({ "limit": { "type": "integer" } })), + ); + assert_eq!(fix_args_str(&map, "get_items", r#"{"limit":""}"#), None); + } +} diff --git a/desktop-tauri/src-tauri/server/src/server/core/upstream/aggregate.rs b/desktop-tauri/src-tauri/server/src/server/core/upstream/aggregate.rs index 3b5f38e23..809879501 100644 --- a/desktop-tauri/src-tauri/server/src/server/core/upstream/aggregate.rs +++ b/desktop-tauri/src-tauri/server/src/server/core/upstream/aggregate.rs @@ -336,7 +336,7 @@ impl CompletionAccumulator { } /// 组装最终 body(对应 Node 的 handleChunk 结束后的返回对象) - fn into_completion(self) -> AggregatedCompletion { + fn into_completion(mut self) -> AggregatedCompletion { // ── 诊断:上游只回了思考、正文为空 ────────────────────────── // 这是**允许发生**的一种结局(始终思考的模型在小输出额度下会把额度 // 全花在思考上,上游仍回 200,见 `providers::zcode::reasoning` 的模块头)。 @@ -364,7 +364,15 @@ impl CompletionAccumulator { if !self.reasoning.is_empty() { message.insert("reasoning_content".to_string(), Value::String(self.reasoning)); } - if !self.tool_calls.is_empty() { + let dropped = super::tool_delta::filter_completed_tool_calls(&mut self.tool_calls); + let named_kept = !self.tool_calls.is_empty(); + if super::tool_delta::fix_completion_finish_reason(&mut self.finish, named_kept, dropped) { + crate::server::logging::verbose( + "[Upstream]", + &format!("幽灵工具调用已丢({dropped}个)且无具名调用:finish tool_calls->stop"), + ); + } + if named_kept { message.insert( "tool_calls".to_string(), Value::Array(self.tool_calls.into_values().collect()), @@ -607,6 +615,47 @@ mod tests { .to_string() } + /// 幽灵分片(空名空参,同 index 无命名)在非流式聚合下发前被丢,终帧 + /// `tool_calls` 改写为 `stop`——对照 shim `strip_phantom_nonstream`。 + /// 不修改的话,客户端拿到空名调用 + `finish == "tool_calls"` + /// 会挂起等一个永远凑不齐的参数。 + #[test] + fn phantom_tool_call_is_dropped_and_finish_fixed_to_stop() { + let mut acc = CompletionAccumulator::default(); + feed( + &mut acc, + r#"data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"","type":"function","function":{"name":"","arguments":""}}]},"finish_reason":null}]}"#, + ); + feed( + &mut acc, + r#"data: {"choices":[{"delta":{},"finish_reason":"tool_calls"}]}"#, + ); + feed(&mut acc, "data: [DONE]"); + let body = acc.into_completion().body; + assert!(body["choices"][0]["message"].get("tool_calls").is_none()); + assert_eq!(body["choices"][0]["finish_reason"], "stop"); + } + + /// 具名调用不受影响:保留下发,终帧保持 `tool_calls` 。 + #[test] + fn named_tool_call_survives_phantom_filter() { + let mut acc = CompletionAccumulator::default(); + feed( + &mut acc, + r#"data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"pwsh","arguments":"{}"}}]},"finish_reason":null}]}"#, + ); + feed( + &mut acc, + r#"data: {"choices":[{"delta":{},"finish_reason":"tool_calls"}]}"#, + ); + feed(&mut acc, "data: [DONE]"); + let body = acc.into_completion().body; + let calls = body["choices"][0]["message"]["tool_calls"].as_array().unwrap(); + assert_eq!(calls.len(), 1); + assert_eq!(calls[0]["function"]["name"], "pwsh"); + assert_eq!(body["choices"][0]["finish_reason"], "tool_calls"); + } + #[test] fn non_stream_folding_drops_the_keepalive_newlines_too() { // 两条路径口径必须一致:同一个请求要不要流式,正文不该长得不一样 diff --git a/desktop-tauri/src-tauri/server/src/server/core/upstream/mod.rs b/desktop-tauri/src-tauri/server/src/server/core/upstream/mod.rs index 3b6e34121..810d522bd 100644 --- a/desktop-tauri/src-tauri/server/src/server/core/upstream/mod.rs +++ b/desktop-tauri/src-tauri/server/src/server/core/upstream/mod.rs @@ -54,6 +54,8 @@ mod images; pub mod image_compress; mod multipart; mod native_tools; +mod tool_delta; +pub use tool_delta::{StreamToolCalls, filter_completed_tool_calls, fix_completion_finish_reason, rewrite_empty_finish_reason}; mod http_dns; mod network_fallback; pub mod refusal; diff --git a/desktop-tauri/src-tauri/server/src/server/core/upstream/payload.rs b/desktop-tauri/src-tauri/server/src/server/core/upstream/payload.rs index 79aaba3ca..6d90db26d 100644 --- a/desktop-tauri/src-tauri/server/src/server/core/upstream/payload.rs +++ b/desktop-tauri/src-tauri/server/src/server/core/upstream/payload.rs @@ -198,6 +198,7 @@ pub(super) async fn send_body<'a>( provider_id: &str, account: Option<&Value>, degraded: bool, + tools_remedied: bool, ) -> SendBody<'a> { if ctx.images.is_some() { let requested = ctx.body.get("model").and_then(Value::as_str).unwrap_or(""); @@ -374,6 +375,41 @@ pub(super) async fn send_body<'a>( // 未注入时读取原有客户端参数;绑定成功时以覆盖后的等级为准。 let upstream_reasoning = injected.or_else(|| outbound_reasoning_of(provider_id, &body)); ctx.telemetry.note_upstream_reasoning(upstream_reasoning.clone()); + // ── ⑤ 工具预剥(发前闸门:这家不支持工具就不带 tools 出门)──────── + // shapes: `supportsToolCall == Some(false)` 整份剥 tools + tool_choice 复用 + // strip_all_tools 降级;`None`(没声明)只对 ocr/embedding/reranker 类名字 + // 按不支持处理,`None ≠ false`。有明确 `Some(true)` 的不碰。 + let mut body = body; + if tools_remedied { + // 动作 0b 的补救体:上游已明确 tools 不支持,整份剥离后重发。 + match crate::server::core::protocol::native_tool::strip_all_tools(body.as_ref()) { + Some((next, dropped)) => { + logging::log( + "[Upstream]", + &dropped.describe(Some(provider_id), Some("工具不支持补救")), + ); + body = Cow::Owned(next); + } + None => {} + } + } + if !crate::server::core::custom_providers::is_custom_provider_id(provider_id) { + match crate::server::core::model_rules::tool_strip_for(provider_id, &wire.model) { + crate::server::core::model_rules::ToolStrip::Strip => { + match crate::server::core::protocol::native_tool::strip_all_tools(body.as_ref()) { + Some((next, dropped)) => { + logging::log( + "[Upstream]", + &dropped.describe(Some(provider_id), Some("该模型不支持工具调用")), + ); + body = Cow::Owned(next); + } + None => {} + } + } + crate::server::core::model_rules::ToolStrip::Keep => {} + } + } SendBody { body, wire_model: wire.model, wire_reasoning: upstream_reasoning } } diff --git a/desktop-tauri/src-tauri/server/src/server/core/upstream/provider_loop.rs b/desktop-tauri/src-tauri/server/src/server/core/upstream/provider_loop.rs index 822c84c88..48dc22378 100644 --- a/desktop-tauri/src-tauri/server/src/server/core/upstream/provider_loop.rs +++ b/desktop-tauri/src-tauri/server/src/server/core/upstream/provider_loop.rs @@ -121,6 +121,8 @@ struct OutboundFailure { /// 收的就是 `error.message`(`上游返回 429: {上游原文}`), /// accounts.json 里落的那段文案因此逐字不变。 error: GatewayError, + /// 归一化后的上游错误体(`{code, message}`,供结构化判定读字段)。 + error_body: Value, /// 插件明确终止本次请求;不再刷新凭证、降级提示词或换账号。 stop: bool, policy: crate::server::core::providers::policy::ErrorPolicy, @@ -283,6 +285,38 @@ const PAYLOAD_SIZE_REJECTION_STATUSES: &[u16] = &[413]; /// 一个是「字节」,一个是「名字」,出处与措辞不同,将来各自的排除面也可能变。 const DETERMINISTIC_NOT_FOUND_STATUSES: &[u16] = &[404]; +/// 工具不支持的结构化判定:上游明确说 tools/tool_choice 不支持。 +/// +/// 字段级优先:原始错误体的 code / type / param 等于 tools/tool_choice +/// (大小写不敏感)即命中;否则消息小写含 tool + 不支持(support/unsupported/ +/// not support)为辅。只判结构,不碰英文文案匹配原文。 +fn structured_tools_unsupported(error: &GatewayError, error_body: &Value, body: &Value) -> bool { + for key in ["code", "type", "param", "error_code"] { + let hit = error_body + .get(key) + .and_then(Value::as_str) + .map(|text| { + let lower = text.trim().to_ascii_lowercase(); + lower == "tools" || lower == "tool_choice" || lower == "toolchoice" + }) + .unwrap_or(false); + if hit { + return true; + } + } + // body 里 tools/tool_choice 的存在是补救的前提:没带工具的 400 不该进补救。 + let has_tools = body + .get("tools") + .and_then(Value::as_array) + .is_some_and(|tools| !tools.is_empty()) + || body.get("tool_choice").is_some(); + if !has_tools { + return false; + } + let message = error.message.to_ascii_lowercase(); + message.contains("tool") && message.contains("support") +} + /// 轮询出网档(`core::proxy_rotate`)在 429 时**原地换出口**的次数上限。 /// /// 为什么是 3:OpenCode Zen 免费档的 429 按 IP 判(这个出口的额度用完),换出口 @@ -385,6 +419,14 @@ fn fallback_retry_advice( { None } + // 工具不支持:动作 0b 会剥 tools 同账号补救一次;补救后仍失败说明剥完 + // 也不行,原地重发同一份字节只会空转三次,不进退避。 + UpstreamErrorClass::Fatal { message, .. } + if message.to_ascii_lowercase().contains("tool") + && message.to_ascii_lowercase().contains("support") => + { + None + } UpstreamErrorClass::Fatal { .. } => Some(RetryAdvice { delay_ms: config::retry_settings().delay_ms(), reason: format!("上游错误(HTTP {status}),换账号前先原地重发"), @@ -657,6 +699,9 @@ async fn attempt_queue( // 不可降级时它照样返回自己的文本),下面「动作 0」的重试条件同理按**当次 // 承载家**判定。 let mut degraded = crate::server::core::degrade::active(); + // ── 工具补救标记(与 degraded/refreshed 同级):本轮是否已做过工具降级补救。 + // 置位后不再重复触发,一次请求最多补救一次(不记新 attempt、不换号、不进退避)。 + let mut tools_remedied = false; // 各家的发送体:某一家即将发送前按作用范围决定一次,换到**同一家同池**的 // 另一个账号时复用(不重复处理、不重复统计)。键带账号的池(Cline 的账号 // 记录有 `free`/`pass`):发送名跟着实际承载的账号所在池走 @@ -667,10 +712,13 @@ async fn attempt_queue( // 那一份发送体是另一份副本,键不同就自然落进另一条缓存项 —— 不必手工失效 // 缓存,也不会把「降级前那份」错发给后面的账号。 // + // 键的第四维是**工具补救标记**:工具不支持 400 后本轮会剥 tools 重发(见 + // 「动作 0b」),那一份同样是另一份副本,键不同自然落进另一条缓存项。 + // // 值里同时带着**该家实际收到的上游模型名**(`SendBody::wire_model`)—— // 它是限额冷却的键,与发出去的字节同源(见 `payload::SendBody`)。 // 缓存因此不只省一次脱敏:429 记账与成功清理都从这里取真名,不必再解析一遍。 - let mut send_cache: HashMap<(&'static str, String, String, bool), SendBody<'_>> = HashMap::new(); + let mut send_cache: HashMap<(&'static str, String, String, bool, bool), SendBody<'_>> = HashMap::new(); // 标签是必需的:下面「429 降级到下一个账号」发生在**内层发送循环**里, // 裸 `continue` 会回到内层(用同一个账号再发一次,正好是要避免的事)。 @@ -1126,9 +1174,9 @@ async fn attempt_queue( // `send_body` 现在是 async(要问插件家「这个思考档位怎么翻译」), // 而 `or_insert_with` 的闭包不能 await。改成「先查、miss 时 await // 生成、再插入」—— 语义等价,代价是 miss 那次多一次哈希查找。 - let cache_key = (provider_id, account_pool.clone(), selected_model.clone(), degraded); + let cache_key = (provider_id, account_pool.clone(), selected_model.clone(), degraded, tools_remedied); if !send_cache.contains_key(&cache_key) { - let built = send_body(ctx, provider_id, target.account.as_ref(), degraded).await; + let built = send_body(ctx, provider_id, target.account.as_ref(), degraded, tools_remedied).await; send_cache.insert(cache_key.clone(), built); } let send = match send_cache.get(&cache_key) { @@ -1485,6 +1533,28 @@ async fn attempt_queue( logging::log("[Upstream]", &format!("⚠️ {reason}")); continue; } + // ── 动作 0b:工具不支持 → 剥 tools 同账号立即重试一次 ── + // 上游明确说 tools/tool_choice 不支持(400 + 结构化判定),这是 + // **发送体问题**而不是账号问题:换号重发同一份 body 结论不变, + // 先把 tools 剥掉再发一次才有意义。首次原样发送、补救最多一次、 + // 不记新 attempt、不换号、不进退避(与动作 0 同一记账形态)。 + if matches!(failure.class, UpstreamErrorClass::Fatal { .. }) + && failure.error.status_code == 400 + && !tools_remedied + && !named_switch + && structured_tools_unsupported(&failure.error, &failure.error_body, body) + { + tools_remedied = true; + let reason = + "上游不支持工具调用(400),剥离 tools 后同账号重试一次"; + ctx.telemetry.note_attempt_retry( + reason, + Some(i64::from(failure.error.status_code)), + 0, + ); + logging::console_line("[Upstream]", &format!("⚠️ {reason}")); + continue; + } // ── 动作 2:token 失效 → 刷新后同一账号重试一次 ────── // 只在「首次失败 + 是 token 失效 + 还没刷新过」时走。 // 刷新失败、或重试再失败(此时 `refreshed` 已为 true) @@ -2340,7 +2410,7 @@ async fn attempt_custom( // **即将发送**。`send_body` 对自定义 id 是零改写(它的模型名改写只认 // modelRules),处理结果就是「提示词/脱敏后的客户端请求体」—— 自定义 // 语义的改写(映射 alias → 真名、思考等级)在 forward 里做。 - let send = send_body(ctx, &provider_id, target.account.as_ref(), degraded).await; + let send = send_body(ctx, &provider_id, target.account.as_ref(), degraded, false).await; // 「上游模型」列以**真名**为准:send_body 对自定义 id 是零改写(它记的 // 是请求名),真名的解析与改写发生在 forward 内部 —— 这里按同源解析 // 覆盖一次(note_upstream_model 是覆盖式,最后一次为准;空串被内部过滤)。 @@ -2549,7 +2619,7 @@ async fn attempt_stateful( // `degraded` 由调用方(账号循环)给出:本路径**没有**就地补救(有状态 // provider 一次转发就是一个会话轮次,没有「换提示词重发」这一步), // 但降级期内(状态机已生效)首发的提示词也要跟着换。 - let send = send_body(ctx, provider_id, target.account.as_ref(), degraded).await; + let send = send_body(ctx, provider_id, target.account.as_ref(), degraded, false).await; // 内置家透传出口的内部字段剥离:与无状态路径同一理由(见那里的说明) let stripped = strip_internal_fields(&send.body); let body: &serde_json::Value = &stripped; @@ -2816,6 +2886,7 @@ fn cancelled_failure() -> OutboundFailure { upstream_code: None, }, error: cancellation::cancelled_error(), + error_body: Value::Null, stop: true, policy: Default::default(), } @@ -2939,6 +3010,7 @@ async fn send_with_retry( status: 502, message: gateway.message.clone(), upstream_code: None, }, error: gateway, + error_body: Value::Null, stop: true, policy: Default::default(), }); @@ -2968,6 +3040,7 @@ async fn send_with_retry( upstream_code: None, }, error: gateway, + error_body: Value::Null, stop: false, policy: Default::default(), }); @@ -3002,6 +3075,7 @@ async fn send_with_retry( return Err(OutboundFailure { class, error: if error.message.is_empty() { super::images::output_error(message) } else { error }, + error_body: failure.body.clone(), stop, policy: Default::default(), }); @@ -3017,6 +3091,7 @@ async fn send_with_retry( upstream_code: error.upstream_code, }, error, + error_body: Value::Null, stop: true, policy: Default::default(), })?; @@ -3135,7 +3210,7 @@ async fn send_with_retry( GatewayError::with_status(error.status_code, format!("{};图片请求可能已消耗额度,未自动重试", error.message)) .with_optional_code(error.upstream_code) } else { error }; - return Err(OutboundFailure { class, error, stop, policy }); + return Err(OutboundFailure { class, error, error_body: body, stop, policy }); } } diff --git a/desktop-tauri/src-tauri/server/src/server/core/upstream/provider_loop/tests.rs b/desktop-tauri/src-tauri/server/src/server/core/upstream/provider_loop/tests.rs index ee9163c3a..62ae79bbf 100644 --- a/desktop-tauri/src-tauri/server/src/server/core/upstream/provider_loop/tests.rs +++ b/desktop-tauri/src-tauri/server/src/server/core/upstream/provider_loop/tests.rs @@ -358,3 +358,74 @@ fn a_deterministic_404_skips_the_in_place_resend() { "404 的豁免不许顺手把 400 也豁免了" ); } + +/// 工具不支持:补救后仍失败不再原地重发(同一份字节空转三次没有意义)。 +#[test] +fn tool_unsupported_skips_the_in_place_resend() { + let unsupported = UpstreamErrorClass::Fatal { + status: 400, + upstream_code: None, + message: "上游返回 400: tools not supported".to_string(), + }; + assert!( + fallback_retry_advice(&unsupported, 3, 400).is_none(), + "工具类 400 不该再原地重发" + ); +} + +/// 结构化判定:字段级优先,消息小写含 tool+support 为辅;没带工具不补救。 +#[test] +fn structured_tools_unsupported_hits_fields_first() { + let body = serde_json::json!({ + "model": "ocr-model", + "tools": [{"type": "function", "function": {"name": "x"}}], + "tool_choice": "auto", + }); + let error = GatewayError::with_status(400, "whatever"); + // 字段命中:error_body.code == tools + let field_hit = serde_json::json!({"code": "tools", "message": "bad"}); + assert!( + structured_tools_unsupported(&error, &field_hit, &body), + "code 字段等于 tools 应当命中" + ); + // 消息命中:小写含 tool + support + let msg_hit = serde_json::json!({"message": "Tools are not supported"}); + let msg_error = GatewayError::with_status(400, "Tools are not supported"); + assert!( + structured_tools_unsupported(&msg_error, &msg_hit, &body), + "消息含 tool+support 应当命中" + ); + // 没带工具:不补救 + let bare = serde_json::json!({"model": "m"}); + assert!( + !structured_tools_unsupported(&msg_error, &msg_hit, &bare), + "没带 tools/tool_choice 的 400 不该进补救" + ); +} + +/// 全剥 wrapper:tools 整份剥,tool_choice 只降 auto;点名的一并撤。 +#[test] +fn strip_all_tools_drops_everything_but_keeps_auto() { + use crate::server::core::protocol::native_tool::strip_all_tools; + let body = serde_json::json!({ + "model": "m", + "tools": [{"type": "function", "function": {"name": "x"}}], + "tool_choice": "auto", + }); + let (next, _) = strip_all_tools(&body).expect("应当剥离"); + assert!(next.get("tools").is_none(), "tools 应整份剥离"); + assert_eq!( + next.get("tool_choice").and_then(serde_json::Value::as_str), + Some("auto"), + "auto 应降级保留" + ); + // 点名具体工具:撤掉 + let named = serde_json::json!({ + "model": "m", + "tools": [{"type": "function", "function": {"name": "x"}}], + "tool_choice": {"type": "function", "function": {"name": "x"}}, + }); + let (next, _) = strip_all_tools(&named).expect("应当剥离"); + assert!(next.get("tools").is_none()); + assert!(next.get("tool_choice").is_none(), "点名工具已无,应撤掉"); +} diff --git a/desktop-tauri/src-tauri/server/src/server/core/upstream/tool_delta.rs b/desktop-tauri/src-tauri/server/src/server/core/upstream/tool_delta.rs new file mode 100644 index 000000000..f546aa618 --- /dev/null +++ b/desktop-tauri/src-tauri/server/src/server/core/upstream/tool_delta.rs @@ -0,0 +1,267 @@ +//! 流式 / 非流式通用的工具调用增量归一(对照 server-shim v2.15 的幽灵丢弃 + v2.1 的空 finish 改写)。 +//! +//! ── 为什么需要它 ────────────────────────────────── +//! 某些上游在工具调用流里混着发“幽灵”分片:`tool_calls[i].function.name` 为空、 +//! `arguments` 也为空,且同一 `index` 从未出现过具名分片。客户端拿到这种分片 +//! 拼不出可执行的调用(OpenAI 规范里 `name` 是必填的),而终帧 +//! `finish_reason == "tool_calls"` 又告诉它“有待执行的调用” —— 客户端会挂起 +//! 等待一个永远不会凑齐的参数。shim 的实测结论是:丢弃这种 +//! 分片不会损害参数连续性(真调用总是先带名再带参)。 +//! +//! ── 两个调用点 ──────────────────────────────────── +//! - 流式公共出口(`usage_normalize::UsageStream` + `sse::ReasoningCoalescer`、 +//! 支持照进行时聚合)逐帧调 [`StreamToolCalls::push`] 与 [`StreamToolCalls::finish_reason`]。 +//! - 非流式聚合(`aggregate::into_completion`)在下发前调 +//! [`filter_completed_tool_calls`] 与 [`fix_completion_finish_reason`]。 +//! +//! ── 与 `aggregate::merge_tool_call` 的关系 ─────────────── +//! 聚合器仍用它自己的合并规则按 `index` 累积(id/type 覆盖、name/arguments 追加), +//! 本模块只负责“下发前过滤 + 终帧修正”:分层而不是把合并规则搬过来。 + +use serde_json::Value; + +/// 流式 tool_calls 的逐 index 聚合器(对照 shim `tool_meta` 的两个键)。 +/// +/// - `named`: 哪些 index 出现过非空 `function.name`(对照 `seen["_named"]` 集合); +/// - `dropped`: 丢过多少个幽灵分片(对照 `seen["_dropped"]` 计数)。 +#[derive(Default, Debug)] +pub struct StreamToolCalls { + named: std::collections::HashSet, + dropped: u64, +} + +impl StreamToolCalls { + pub fn new() -> Self { + Self::default() + } + + /// 丢过多少个幽灵分片(终帧修正的入口条件之一)。 + pub fn dropped(&self) -> u64 { + self.dropped + } + + /// 是否见过具名分片(终帧修正的另一个入口条件)。 + pub fn has_named(&self) -> bool { + !self.named.is_empty() + } + + /// 对 `delta.tool_calls` 做行级过滤:幽灵分片直接丢、具名分片记录 index。 + /// + /// 返回 `true` 表示本帧被改写过(有丢弃),调用方需要重新序列化该帧。 + /// 返回 `false` 时 `delta` 毫动未动,调用方保持原字节下发。 + /// + /// 判据与 shim 同义(`_is_phantom_stream_tc` + `strip_phantom_stream_block`): + /// 空名、参数为空且同 index 无命名记录。参数为空指的是 + /// shim 的 `_tc_args_empty` —— 缺失 / null / `""` 去空后为空 / `"{}"`。 + pub fn push(&mut self, delta: &mut serde_json::Map) -> bool { + let Some(calls) = delta.get("tool_calls").and_then(Value::as_array) else { + return false; + }; + if calls.is_empty() { + return false; + } + // 先记录本帧里的具名 index:同一帧内“先命名后幽灵”的排列也不丢命名本身。 + for call in calls { + if let (Some(index), Some(name)) = (tool_call_index(call), tool_call_name(call)) { + if !name.trim().is_empty() { + self.named.insert(index); + } + } + } + let before = calls.len(); + let kept: Vec = calls + .iter() + .filter(|call| !self.is_phantom(call)) + .cloned() + .collect(); + let dropped = before.saturating_sub(kept.len()); + if dropped == 0 { + return false; + } + self.dropped += dropped as u64; + if kept.is_empty() { + delta.remove("tool_calls"); + } else if let Some(slot) = delta.get_mut("tool_calls") { + *slot = Value::Array(kept); + } + true + } + + /// 终帧修正(对照 shim `fix_phantom_finish`):丢过幽灵分片、从未见过 + /// 具名分片,而本帧 `finish_reason == "tool_calls"` —— 客户端会挂起等一个 + /// 永远凑不齐的参数,故改写为 `"stop"`,让文本轮完整收尾。 + /// + /// 返回 `true` 表示改写过,调用方需要重新序列化该帧。 + pub fn finish_reason(&self, choice: &mut serde_json::Map) -> bool { + if self.dropped == 0 || !self.named.is_empty() { + return false; + } + if choice.get("finish_reason").and_then(Value::as_str) != Some("tool_calls") { + return false; + } + choice.insert("finish_reason".to_string(), Value::String("stop".to_string())); + true + } + + fn is_phantom(&self, call: &Value) -> bool { + if tool_call_name(call).is_some_and(|name| !name.trim().is_empty()) { + return false; + } + if tool_call_index(call).is_some_and(|index| self.named.contains(&index)) { + return false; + } + let args_empty = call + .get("function") + .and_then(|function| { + let args = function.get("arguments")?; + if args.is_null() { + return Some(true); + } + args.as_str().map(|text| { + let text = text.trim(); + text.is_empty() || text == "{}" + }) + }) + .unwrap_or(true); + args_empty + } +} + +/// 空 `finish_reason ""` 是否出现在本帧(对照 shim `EMPTY_FINISH_RE`:任意空格形态)。 +/// +/// 行级检查先走字节包含(`UsageStream::poll_next` 的快速路径保留), +/// 命中后再走 JSON 级改写:`choices[].finish_reason == ""` → `null`。 +/// OpenAI 规范里流式中间帧的结束理由是 null,空串不是非终止信号。 +pub fn rewrite_empty_finish_reason(chunk: &mut Value) -> bool { + let Some(choices) = chunk.get_mut("choices").and_then(Value::as_array_mut) else { + return false; + }; + let mut changed = false; + for choice in choices { + let Some(choice) = choice.as_object_mut() else { + continue; + }; + if choice.get("finish_reason").and_then(Value::as_str) == Some("") { + choice.insert("finish_reason".to_string(), Value::Null); + changed = true; + } + } + changed +} + +/// 非流式聚合下发前过滤(对照 shim `strip_phantom_nonstream`):丢掉所有 +/// 无名 `tool_calls` 条目,返回丢过多少个。聚合完没有“将来分片”了, +/// 所以不用跟踪 index 命名状态 —— 无名即丢。 +/// +/// 调用时机是 `aggregate::into_completion` 拼 `tool_calls` 数组之前,故输入是 +/// `按 index 聚好的 map`而不是最终数组。 +pub fn filter_completed_tool_calls(tool_calls: &mut std::collections::BTreeMap) -> u64 { + let before = tool_calls.len(); + tool_calls.retain(|_, call| tool_call_name(call).is_some_and(|name| !name.trim().is_empty())); + (before.saturating_sub(tool_calls.len())) as u64 +} + +/// 非流式终帧修正(对照 shim `strip_phantom_nonstream` 的后半段): +/// `finish == "tool_calls"` 且聚合后没有具名调用且丢过幽灵条目 +/// —— 改写为 `"stop"`。返回是否改写过。 +pub fn fix_completion_finish_reason(finish: &mut String, named_kept: bool, dropped: u64) -> bool { + if finish == "tool_calls" && !named_kept && dropped > 0 { + finish.clear(); + finish.push_str("stop"); + return true; + } + false +} + +fn tool_call_index(call: &Value) -> Option { + call.get("index") + .and_then(Value::as_i64) + // Node:`Number.isInteger(tc.index) ? tc.index : 0`(聚合器同口径)。 + .or_else(|| call.get("index").is_none().then_some(0)) +} + +fn tool_call_name(call: &Value) -> Option<&str> { + call.get("function")?.get("name")?.as_str() +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn delta_of(calls: Value) -> serde_json::Map { + json!({ "tool_calls": calls }).as_object().cloned().unwrap() + } + + #[test] + fn empty_finish_reason_rewrites_to_null() { + let mut chunk = json!({"choices": [{"delta": {}, "finish_reason": ""}]}); + assert!(rewrite_empty_finish_reason(&mut chunk)); + assert_eq!(chunk["choices"][0]["finish_reason"], Value::Null); + } + + #[test] + fn non_empty_finish_reason_is_untouched() { + for finish in ["stop", "tool_calls", "length"] { + let mut chunk = json!({"choices": [{"delta": {}, "finish_reason": finish}]}); + assert!(!rewrite_empty_finish_reason(&mut chunk)); + assert_eq!(chunk["choices"][0]["finish_reason"], finish); + } + let mut null_chunk = json!({"choices": [{"delta": {}, "finish_reason": Value::Null}]}); + assert!(!rewrite_empty_finish_reason(&mut null_chunk)); + } + + #[test] + fn phantom_stream_delta_is_dropped_and_counted() { + let mut tracker = StreamToolCalls::new(); + let mut delta = delta_of(json!([{"index": 0, "function": {"name": "", "arguments": ""}}])); + assert!(tracker.push(&mut delta)); + assert_eq!(tracker.dropped(), 1); + assert!(delta.get("tool_calls").is_none()); + } + + #[test] + fn named_stream_delta_survives_and_marks_index() { + let mut tracker = StreamToolCalls::new(); + let mut delta = delta_of(json!([{"index": 0, "function": {"name": "pwsh", "arguments": ""}}])); + assert!(!tracker.push(&mut delta)); + assert!(tracker.has_named()); + // 同 index 后续的空名参数分片是真调用的一部分,不丢。 + let mut args = delta_of(json!([{"index": 0, "function": {"arguments": "{\"a\":1}"}}])); + assert!(!tracker.push(&mut args)); + assert_eq!(tracker.dropped(), 0); + } + + #[test] + fn phantom_finish_rewrites_to_stop_only_when_nothing_named() { + let mut tracker = StreamToolCalls::new(); + let mut delta = delta_of(json!([{"index": 0, "function": {"name": "", "arguments": ""}}])); + assert!(tracker.push(&mut delta)); + let mut choice = json!({"finish_reason": "tool_calls"}).as_object().cloned().unwrap(); + assert!(tracker.finish_reason(&mut choice)); + assert_eq!(choice["finish_reason"], "stop"); + } + + #[test] + fn phantom_finish_keeps_tool_calls_when_named_exists() { + let mut tracker = StreamToolCalls::new(); + let mut named = delta_of(json!([{"index": 0, "function": {"name": "pwsh", "arguments": "{}"}}])); + assert!(!tracker.push(&mut named)); + // 同 index 的后续幽灵分片不会出现(已有命名记录),直接验终帧不改。 + let mut choice = json!({"finish_reason": "tool_calls"}).as_object().cloned().unwrap(); + assert!(!tracker.finish_reason(&mut choice)); + assert_eq!(choice["finish_reason"], "tool_calls"); + } + + #[test] + fn completed_filter_drops_nameless_and_fixes_finish() { + let mut calls = std::collections::BTreeMap::new(); + calls.insert(0, json!({"id": "", "type": "function", "function": {"name": "", "arguments": ""}})); + let dropped = filter_completed_tool_calls(&mut calls); + assert_eq!(dropped, 1); + assert!(calls.is_empty()); + let mut finish = "tool_calls".to_string(); + assert!(fix_completion_finish_reason(&mut finish, false, dropped)); + assert_eq!(finish, "stop"); + } +} diff --git a/desktop-tauri/src-tauri/server/src/server/core/upstream/usage_normalize.rs b/desktop-tauri/src-tauri/server/src/server/core/upstream/usage_normalize.rs index 3e257fb7a..752f0a4db 100644 --- a/desktop-tauri/src-tauri/server/src/server/core/upstream/usage_normalize.rs +++ b/desktop-tauri/src-tauri/server/src/server/core/upstream/usage_normalize.rs @@ -36,6 +36,7 @@ pub(super) fn normalize_outcome(outcome: ForwardOutcome, telemetry: Arc>, passthrough_line: bool, ended: bool, + /// 流式 tool_calls 的逐 index 聚合状态(幽灵丢弃 + 终帧修正,见 [`super::tool_delta`] 模块头)。 + /// + /// 状态必须跨行持续整个流:具名分片可能在幽灵分片之前几十帧就出现过。 + tool_state: super::tool_delta::StreamToolCalls, } impl UsageStream { @@ -100,14 +105,47 @@ impl UsageStream { self.pending.push_back(Ok(rewritten.unwrap_or_else(|| Bytes::from(line)))); } + /// 行级改写三件套(有一件命中才重序列化,否则返回 `None`保持原字节): + /// + /// 1. usage 补齐(既有行为,保持“上报与改写与否无关”的旧序); + /// 2. 空 `finish_reason ""` → `null`(对照 shim `EMPTY_FINISH_RE`,任意空格形态) + /// —— OpenAI 规范里流式中间帧的结束理由是 null,空串不是非终止信号; + /// 3. 幽灵 `tool_calls` 分片丢弃 + 终帧 `tool_calls` → `stop` 修正 + /// (对照 shim v2.15,判据见 [`super::tool_delta`] 模块头)。 fn rewrite_line(&mut self, line: &[u8]) -> Option { let payload = line.strip_prefix(b"data:")?; - if !payload.windows(7).any(|window| window == b"\"usage\"") { return None; } + let has_usage = payload.windows(7).any(|window| window == b"\"usage\""); + let has_tool_calls = payload.windows(12).any(|window| window == b"\"tool_calls\""); + // `"finish_reason"` = 引号 + 13 字母 + 引号,共 15 字节。 + let has_finish = payload.windows(15).any(|window| window == b"\"finish_reason\""); + if !has_usage && !has_tool_calls && !has_finish { return None; } let mut chunk: Value = serde_json::from_slice(payload).ok()?; - let usage = chunk.get_mut("usage")?; - self.tokens.absorb(TokenUsage::from_chat(usage)?); - let changed = self.tokens.write_chat(usage); - self.telemetry.report_usage(usage); + // 旧序保留:上报发生在“改写与否”之前,统计少记一条可以接受, + // 把请求搞坏不可接受——与改造前一致,未上报成功时整行保持原字节。 + let mut changed = false; + if has_usage { + if let Some(usage) = chunk.get_mut("usage") { + if let Some(tokens) = TokenUsage::from_chat(usage) { + self.tokens.absorb(tokens); + changed |= self.tokens.write_chat(usage); + self.telemetry.report_usage(usage); + } + } + } + if has_tool_calls { + if let Some(choices) = chunk.get_mut("choices").and_then(Value::as_array_mut) { + for choice in choices.iter_mut() { + let Some(choice) = choice.as_object_mut() else { continue; }; + if let Some(delta) = choice.get_mut("delta").and_then(Value::as_object_mut) { + changed |= self.tool_state.push(delta); + } + changed |= self.tool_state.finish_reason(choice); + } + } + } + if has_finish { + changed |= super::tool_delta::rewrite_empty_finish_reason(&mut chunk); + } if !changed { return None; } let text = serde_json::to_string(&chunk).ok()?; let ending = if line.ends_with(b"\r\n") { "\r\n" } @@ -129,8 +167,13 @@ impl Stream for UsageStream { match Pin::new(&mut this.source).poll_next(context) { Poll::Pending => return Poll::Pending, Poll::Ready(Some(Ok(bytes))) => { + // 快速路径:整个分片不带任何需要改写的键时直接下发, + // 保持原字节。三个判据与 `rewrite_line` 的入口条件同步: + // 增删改写项时两处一起改(否则快速路径会绕过新改写)。 if this.line.is_empty() && !this.passthrough_line && bytes.ends_with(b"\n") && !bytes.windows(7).any(|window| window == b"\"usage\"") + && !bytes.windows(12).any(|window| window == b"\"tool_calls\"") + && !bytes.windows(15).any(|window| window == b"\"finish_reason\"") { return Poll::Ready(Some(Ok(bytes))); }