diff --git a/FEATURES.md b/FEATURES.md index 8e89d00..e1a62eb 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -1579,6 +1579,12 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 標在:設定 › 模型 左欄每列右邊(滑過看整句)、右邊標題下一句;Bot 設定「AI 供應商與模型」下面;聊天頂端 Bot 名字後面(滑過看模型和整句);空聊天的「供應商 · 模型 · 雲端」;輸入框 + 的模型選單每家後面。手機:Bot 設定 › 模型 右邊、選模型時每家的標題、設定 › 模型 每家的說明(大腦送 `runs`、`runs_words`)。左欄放寬到 212 px 放得下「自訂(OpenAI 相容)」加標籤。 - 「Ollama(本機)」改叫「Ollama」:它可以指到區網的另一台,名字裡寫死「本機」會說錯,現在看標籤。 +### 工具參數沒送到 + +- 模型叫工具、參數卻是空的(`{}`):以前 `browser` 回「這一步沒有給 action」,模型照樣再送一次空的、連三次就整輪不能用(jenny-Host 的 OpenCode Go · deepseek-v4.1-flash 一天 395 次,思考裡每次都寫了要做的動作)。現在說實話:「這一步送到 AnyBot 時參數是空的——不是你沒寫,是參數沒有送到」,附上動作清單和例子;`browser` 再加「如果再叫一次還是空的,改用單一動作的工具」(`browser_open {url}`、`browser_read`、`browser_click {ref|text}`、`browser_type {ref|text, value}`、`browser_press {key}`、`browser_wait {text|seconds}`、`browser_eval {script}`…,AnyBot 照收)。參數不是合法 JSON 時說「不是合法的 JSON」和怎麼寫(換行 \n、引號 \")。 +- 收模型回應時更寬容:閘道把參數當物件送(不是字串)、參數另外編號送來(名字那格是 `{}`)、真的參數前多一個 `{}`,都照意思接起來;Anthropic 格式的參數整包放在一開始、沒有分段,也照收;分段的參數不是 JSON 就照原樣留著(讓工具說它不是 JSON),不再悄悄換成 `{}`。 +- 需要參數的工具最後還是空的,紀錄檔記一行「模型(…)叫 browser 卻沒帶參數;串流裡這個呼叫的原文:…」(最多 1500 字),查得到參數在哪裡不見的。 + ### 診斷(/doctor) - 聊天打 /doctor:這台電腦的 AnyBot 一項一行 ✓ 或 ✗:版本、資料夾、今天的紀錄檔;這台 ↔ 帳號伺服器(長連線的狀態);帳號伺服器是 *.ts.net 時,Tailscale 是直連還是走它在哪裡的中繼(`tailscale ping`;走中繼會寫延遲和「多半是中間擋了 UDP 41641」);帳號伺服器 ↔ 大腦(帳號伺服器說在不在線上);螢幕連不連得到大腦和原因;上次同步的大小和速度(1 MB 以上、每秒不到 300 KB 算慢);每個 Bot 用到的模型服務連不連得到(列模型清單);Bot 的電腦;每個開著的連接器;磁碟剩多少(少於 2 GB 算 ✗);指令有沒有沙盒(macOS 的 sandbox-exec、Linux 的 Landlock 第幾版,沒有就 ✗);上次內部出錯。要上網的檢查在背景跑,好了一次留一行。 diff --git a/docs/feature-map/browser.md b/docs/feature-map/browser.md index 1596889..aef4a3e 100644 --- a/docs/feature-map/browser.md +++ b/docs/feature-map/browser.md @@ -38,6 +38,8 @@ Bot 用 AnyBot 自己的瀏覽器上網、登入、點按、打字、送出。 ## 陷阱 +- 有些模型經閘道叫 `browser` 時參數送到是空的(`{}`;OpenCode Go · deepseek-v4.1-flash 一天 395 次,思考裡每次都有寫動作):AnyBot 說「參數是空的——不是你沒寫,是沒有送到」,再叫一次還是空的就改用單一動作的工具(`browser_open {url}`、`browser_click {ref|text}`…,AnyBot 照收),紀錄檔記一行「叫 browser 卻沒帶參數;串流裡這個呼叫的原文:…」。參數不是合法 JSON 時說「不是合法的 JSON」(字串裡的換行要寫 \n),不再說成沒給 action。 + - 別人傳來的訊息那一輪不能用 AnyBot 瀏覽器、保險庫和 `sent`(帶著使用者的登入)。公開網頁用 `web_fetch`。 - 不同電腦、不同設定檔的登入不共用;沒帶 `profile` 會用到別的。 - 「做事的電腦」開不了瀏覽器(沒裝 Chrome/Brave…、SSH)時,步驟回「使用者選的電腦「…」現在開不了 AnyBot 的瀏覽器」,不改開在這台 Mac。公開網頁用 `web_fetch`,其他先問。 diff --git a/src/agent.rs b/src/agent.rs index 0743fa3..d78e5de 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -807,11 +807,28 @@ fn refresh_own(job: &mut Job, bot_id: u64) -> Option { fn bad_action(tool: &str, args: &str) -> String { let spec = if tool == crate::browser::TOOL { crate::browser::tool(&serde_json::json!({"type": "string"})) } else { computer::specs_for(&["這台".to_string()], "這台", true).into_iter().find(|t| t["name"] == computer::TOOL).unwrap_or_default() }; let actions: Vec<&str> = spec["parameters"]["properties"]["action"]["enum"].as_array().map(|a| a.iter().filter_map(|x| x.as_str()).collect()).unwrap_or_default(); - let given = match tools::args_of(args)["action"].as_str() { + let example = if tool == crate::browser::TOOL { r#"{"action": "press", "key": "ctrl+Return"}"# } else { r#"{"action": "click", "ref": "12"}"# }; + let v = tools::args_of(args); + // The arguments came to AnyBot empty — the model meant an action (its thinking says so every + // time), the call carried none: told as it is, with the one-action tools that do get their + // arguments through (jenny-Host's model sent `browser` `{}` 395 times in a day; told 「you + // gave no action」 it sent the same again, three times, and lost the tool for the turn). + if v.as_object().is_some_and(|o| o.is_empty()) { + let direct = if tool == crate::browser::TOOL { + "\n如果再叫一次還是空的,改用單一動作的工具,參數一樣、不用 action:browser_open {url}、browser_read、browser_elements、browser_click {ref|text}、browser_type {ref|text, value}、browser_press {key}、browser_wait {text|seconds}、browser_scroll {direction}、browser_eval {script}、browser_screenshot。" + } else { + "" + }; + return format!("沒有執行:這一步的 {tool} 送到 AnyBot 時參數是空的({{}})——不是你沒寫,是參數沒有送到。再叫一次,參數直接放在最外層,例如 {example}(action 可以是:{})。{direct}", actions.join("、")); + } + if v.is_null() { + let head: String = args.chars().take(120).collect(); + return format!("沒有執行:這一步的 {tool} 參數不是合法的 JSON(開頭:{head})。字串裡的換行要寫成 \\n、引號寫成 \\\",參數直接放在最外層,例如 {example}。"); + } + let given = match v["action"].as_str() { Some(a) => format!("「{a}」不是它的動作"), None => "沒有給 action".to_string(), }; - let example = if tool == crate::browser::TOOL { r#"{"action": "press", "key": "ctrl+Return"}"# } else { r#"{"action": "click", "ref": "12"}"# }; format!("沒有執行:{tool} 要用 action 指定做什麼,這一步{given}。可以用的有:{}。參數直接放在最外層,例如 {example}。", actions.join("、")) } @@ -4167,6 +4184,15 @@ echo 'done送出了' > done.html; (setsid pyt assert!(t.contains("「paste」不是它的動作"), "{t}"); let t = bad_action(computer::TOOL, "{}"); assert!(t.contains("screenshot") && t.contains("click"), "{t}"); + // Arguments that came empty: said so (not 「you gave no action」), with the one-action + // tools that get theirs through; arguments that aren't JSON: said so, with how. + for empty in ["{}", "", " "] { + let t = bad_action(crate::browser::TOOL, empty); + assert!(t.contains("參數是空的") && t.contains("不是你沒寫") && t.contains("browser_open {url}") && t.contains("browser_press {key}") && !t.contains("沒有給 action"), "{t}"); + } + let t = bad_action(crate::browser::TOOL, "{\"action\": \"type\", \"value\": \"第一行\n第二行\"}"); + assert!(t.contains("不是合法的 JSON") && t.contains("\\n"), "{t}"); + assert!(!bad_action(computer::TOOL, "{}").contains("browser_open"), "the computer tool isn't pointed at the browser's"); // A safety rule's no, again and again, stops the tool for the turn like a failure. let blocked = |n: usize| (0..n).map(|_| ("browser".to_string(), true, "被安全規則擋下:沒有「browser」這個工具".to_string())).collect::>(); assert_eq!(same_failures(&blocked(3), "browser"), SAME_FAILURES_STOP); diff --git a/src/providers.rs b/src/providers.rs index 890c8ec..5f8503e 100644 --- a/src/providers.rs +++ b/src/providers.rs @@ -1514,6 +1514,9 @@ fn stream_openai_with(req: &ChatRequest, effort: Option<&str>, cancel: &AtomicBo let mut out = StepOutput::default(); // Tool calls arrive in pieces keyed by index. let mut pending: Vec<(String, String, String)> = vec![]; + // What the stream said about each call, as it came (a little of it): said in the log when a + // call that needs arguments ends with none (see finish_calls). + let mut raw_calls: Vec = vec![]; let mut error = None; let reader: Box = match (resp, via_hands) { (Some(r), _) => Box::new(r.into_body().into_reader()), @@ -1564,6 +1567,10 @@ fn stream_openai_with(req: &ChatRequest, effort: Option<&str>, cancel: &AtomicBo }; while pending.len() <= i { pending.push(Default::default()); + raw_calls.push(String::new()); + } + if raw_calls[i].len() < RAW_CALL_KEEP { + raw_calls[i].push_str(&c.to_string()); } if let Some(id) = c["id"].as_str() { pending[i].0 = id.to_string(); @@ -1571,8 +1578,12 @@ fn stream_openai_with(req: &ChatRequest, effort: Option<&str>, cancel: &AtomicBo if let Some(n) = c["function"]["name"].as_str() { pending[i].1.push_str(n); } - if let Some(a) = c["function"]["arguments"].as_str() { - pending[i].2.push_str(a); + match &c["function"]["arguments"] { + Value::String(a) => pending[i].2.push_str(a), + // (Some gateways hand the arguments over as an object, not a string: it + // was read as none at all.) + Value::Object(o) if !o.is_empty() => pending[i].2.push_str(&Value::Object(o.clone()).to_string()), + _ => {} } } } @@ -1582,18 +1593,55 @@ fn stream_openai_with(req: &ChatRequest, effort: Option<&str>, cancel: &AtomicBo if let Some(e) = error { return Err(stream_failure(&e)); } - for (i, (id, name, args)) in pending.into_iter().enumerate() { - if name.is_empty() { - continue; - } - let id = if id.is_empty() { format!("call_{i}") } else { id }; - let call = ToolCall { id, name, args, status: ToolStatus::Waiting }; + for call in finish_calls(req, pending, &raw_calls) { send(StreamEvent::ToolCall(call.clone())); out.tool_calls.push(call); } Ok(out) } +/// How much of each call's stream is kept to show in the log (finish_calls). +const RAW_CALL_KEEP: usize = 1500; + +/// The calls a chat-completions stream built up (id, name, arguments), made whole: arguments that +/// came in a slot of their own without a name (a gateway that numbered them apart) go to the call +/// before them when it has none; a `{}` put before the real arguments is dropped. A call that +/// needs arguments and still has none is said in the log with what the stream really carried: +/// jenny-Host's model (OpenCode Go · deepseek-v4.1-flash) sent `browser` with `{}` 395 times in a +/// day while meaning an action every time, and nothing showed where the arguments went. +fn finish_calls(req: &ChatRequest, mut pending: Vec<(String, String, String)>, raw: &[String]) -> Vec { + for i in 1..pending.len() { + let (before, rest) = pending.split_at_mut(i); + let (prev, cur) = (&mut before[i - 1], &mut rest[0]); + if cur.1.is_empty() && !cur.2.trim().is_empty() && !prev.1.is_empty() && matches!(prev.2.trim(), "" | "{}") { + prev.2 = std::mem::take(&mut cur.2); + } + } + let mut out = vec![]; + for (i, (id, name, mut args)) in pending.into_iter().enumerate() { + if name.is_empty() { + continue; + } + if let Some(rest) = args.trim_start().strip_prefix("{}") { + if serde_json::from_str::(rest.trim()).is_ok_and(|v| v.is_object()) { + args = rest.trim().to_string(); + } + } + if matches!(args.trim(), "" | "{}") && needs_arguments(req, &name) { + let seen: String = raw.get(i).map(String::as_str).unwrap_or("").chars().take(RAW_CALL_KEEP).collect(); + log::warn!("AnyBot:模型({} · {})叫 {name} 卻沒帶參數;串流裡這個呼叫的原文:{seen}", req.kind.label(), req.model); + } + let id = if id.is_empty() { format!("call_{i}") } else { id }; + out.push(ToolCall { id, name, args, status: ToolStatus::Waiting }); + } + out +} + +/// Whether the request's tool `name` has fields it can't go without. +fn needs_arguments(req: &ChatRequest, name: &str) -> bool { + req.tools.iter().find(|t| t["name"] == name).is_some_and(|t| t["parameters"]["required"].as_array().is_some_and(|r| !r.is_empty())) +} + // ---------- ChatGPT 方案: the Responses API on the person's plan ---------- /// The chat as Responses API input items (the system prompt goes in `instructions`: the plan's @@ -2058,9 +2106,20 @@ fn stream_anthropic(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(Stream if let Some(b) = blocks.get_mut(i) { if b["type"] == "tool_use" { let raw = partial_json.get(i).cloned().unwrap_or_default(); - let input: Value = if raw.trim().is_empty() { json!({}) } else { serde_json::from_str(&raw).unwrap_or(json!({})) }; - b["input"] = input.clone(); - let call = ToolCall { id: b["id"].as_str().unwrap_or("").into(), name: b["name"].as_str().unwrap_or("").into(), args: input.to_string(), status: ToolStatus::Waiting }; + // No pieces: the input the block started with (some gateways put it all + // there). Pieces that aren't JSON: kept as they are, so the tool says the + // arguments aren't JSON — `{}` in their place read as "you gave none". + let (input, args) = if raw.trim().is_empty() { + let start = if b["input"].is_object() { b["input"].clone() } else { json!({}) }; + (start.clone(), start.to_string()) + } else { + match serde_json::from_str::(&raw) { + Ok(v) => (v.clone(), v.to_string()), + Err(_) => (json!({}), raw.clone()), + } + }; + b["input"] = input; + let call = ToolCall { id: b["id"].as_str().unwrap_or("").into(), name: b["name"].as_str().unwrap_or("").into(), args, status: ToolStatus::Waiting }; send(StreamEvent::ToolCall(call.clone())); out.tool_calls.push(call); } @@ -2421,6 +2480,48 @@ mod tests { assert_eq!(o.tool_calls[0].args, "{\"path\":\"a.txt\"}"); } + /// Gateways that hand a call's arguments over differently: as an object; in a slot of their + /// own after the name came with `{}`; after a `{}`. Each is read as the call meant (they were + /// read as no arguments at all, and the tool said 「you gave no action」). + #[test] + fn a_calls_arguments_arrive_however_a_gateway_sends_them() { + let one = |chunks: &[&str]| -> Vec { + let body: String = chunks.iter().map(|c| format!("data: {{\"choices\":[{{\"delta\":{{\"tool_calls\":[{c}]}}}}]}}\n\n")).collect::() + "data: [DONE]\n\n"; + run(ProviderKind::OpenAi, Box::leak(body.into_boxed_str())).tool_calls + }; + let want = json!({"action": "wait", "seconds": 2}); + let as_object = one(&[r#"{"index":0,"id":"c1","function":{"name":"browser","arguments":{"action":"wait","seconds":2}}}"#]); + assert_eq!(serde_json::from_str::(&as_object[0].args).unwrap(), want); + let apart = one(&[r#"{"index":0,"id":"c1","function":{"name":"browser","arguments":"{}"}}"#, r#"{"index":1,"function":{"arguments":"{\"action\":\"wait\",\"seconds\":2}"}}"#]); + assert_eq!(apart.len(), 1); + assert_eq!((apart[0].name.as_str(), serde_json::from_str::(&apart[0].args).unwrap()), ("browser", want.clone())); + let after = one(&[r#"{"index":0,"id":"c1","function":{"name":"browser","arguments":"{}"}}"#, r#"{"index":0,"function":{"arguments":"{\"action\":\"wait\",\"seconds\":2}"}}"#]); + assert_eq!(serde_json::from_str::(&after[0].args).unwrap(), want); + // Two real calls stay two, each with its own. + let two = one(&[r#"{"index":0,"id":"c1","function":{"name":"read_file","arguments":"{\"path\":\"a\"}"}}"#, r#"{"index":1,"id":"c2","function":{"name":"read_file","arguments":"{\"path\":\"b\"}"}}"#]); + assert_eq!((two.len(), two[0].args.as_str(), two[1].args.as_str()), (2, r#"{"path":"a"}"#, r#"{"path":"b"}"#)); + // Really none: still none (the log says what came). + assert_eq!(one(&[r#"{"index":0,"id":"c1","function":{"name":"browser","arguments":"{}"}}"#])[0].args, "{}"); + } + + /// Anthropic-style: a tool's input given whole at the block's start (no pieces) is the input; + /// pieces that aren't JSON stay as they came, so the tool can say so. + #[test] + fn a_claude_style_input_given_at_the_start_is_kept() { + let ev = |e: &str, d: &str| format!("event: {e}\ndata: {d}\n\n"); + let mut body = ev("message_start", r#"{"type":"message_start"}"#); + body += &ev("content_block_start", r#"{"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"t1","name":"browser","input":{"action":"press","key":"Enter"}}}"#); + body += &ev("content_block_stop", r#"{"type":"content_block_stop","index":0}"#); + body += &ev("content_block_start", r#"{"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"t2","name":"browser","input":{}}}"#); + body += &ev("content_block_delta", "{\"type\":\"content_block_delta\",\"index\":1,\"delta\":{\"type\":\"input_json_delta\",\"partial_json\":\"{\\\"action\\\": \\\"type\\\", \\\"value\\\": \\\"a\"}}"); + body += &ev("content_block_stop", r#"{"type":"content_block_stop","index":1}"#); + body += &ev("message_stop", r#"{"type":"message_stop"}"#); + let o = run(ProviderKind::Anthropic, Box::leak(body.into_boxed_str())); + assert_eq!(serde_json::from_str::(&o.tool_calls[0].args).unwrap(), json!({"action": "press", "key": "Enter"})); + assert_eq!(o.tool_calls[1].args, r#"{"action": "type", "value": "a"#, "kept as it came"); + assert_eq!(o.blocks[1]["input"], json!({}), "the history keeps a valid input"); + } + #[test] fn claude_style_stream() { let body = "event: message_start\ndata: {\"type\":\"message_start\"}\n\nevent: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"thinking\",\"thinking\":\"\"}}\n\nevent: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"thinking_delta\",\"thinking\":\"ok\"}}\n\nevent: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"signature_delta\",\"signature\":\"sig\"}}\n\nevent: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":1,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\nevent: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":1,\"delta\":{\"type\":\"text_delta\",\"text\":\"Hello\"}}\n\nevent: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":2,\"content_block\":{\"type\":\"tool_use\",\"id\":\"tu1\",\"name\":\"list_dir\",\"input\":{}}}\n\nevent: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":2,\"delta\":{\"type\":\"input_json_delta\",\"partial_json\":\"{\\\"path\\\": \\\"x\\\"}\"}}\n\nevent: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":2}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n";