Craft Anything: understand how any software works, and craft your own.
Rust
Recover JSON tool calls emitted as text (#554)
Afloat0a0fa2a43a16
diff --git a/crates/ai/src/openai.rs b/crates/ai/src/openai.rsindex 9e92777f..50bdd24f 100644--- a/crates/ai/src/openai.rs+++ b/crates/ai/src/openai.rs@@ -38,7 +38,7 @@ pub struct OpenAi {pub extra_headers: Vec<(&'static str, String)>,/// Use the ReAct text protocol instead of function tools.pub react: bool,- /// Switch to ReAct automatically when the server rejects tools.+ /// Recover JSON text calls automatically, and switch to ReAct when the server rejects tools.pub auto_react: bool,}@@ -126,8 +126,8 @@ impl OpenAi {})?;stop.check()?;let mut r = st.finish(&self.model)?;- if self.react {- react_postprocess(&mut r);+ if self.react || self.auto_react {+ react_postprocess(&mut r, req.tools, self.react);}Ok(r)}@@ -333,8 +333,21 @@ pub enum ReactStep {Text(String),}-/// Parse the model's text according to the ReAct protocol.+/// Parse a ReAct step, accepting a complete JSON call as an alternative.pub fn parse_react(text: &str) -> ReactStep {+ if let Some(step) = json_action(text) {+ return step;+ }+ // Preserve a whole fenced ReAct step, but do not treat markers inside a JSON answer or+ // ordinary code example as instructions.+ let lead = text.trim();+ let fenced_protocol = backtick_fence(lead).is_some_and(|(_, body)| {+ let body = body.trim_start();+ ["Action:", "Thought:", "Final Answer:"].into_iter().any(|marker| body.starts_with(marker))+ });+ if lead.starts_with(['{', '[']) || (lead.starts_with("```") && !fenced_protocol) {+ return ReactStep::Text(text.trim().to_string());+ }if let Some(pos) = text.find("Final Answer:") {return ReactStep::Final(text.get(pos + "Final Answer:".len()..).unwrap_or_default().trim().to_string());}@@ -352,6 +365,68 @@ pub fn parse_react(text: &str) -> ReactStep {if tool.is_empty() { ReactStep::Text(text.trim().to_string()) } else { ReactStep::Action { tool, input } }}+/// A complete backtick fence. Its standalone closing line can be longer than its opener,+/// but an earlier closing line means the remaining text is outside that fence.+fn backtick_fence(text: &str) -> Option<(&str, &str)> {+ let (opening, rest) = text.trim().split_once('\n')?;+ let length = opening.bytes().take_while(|byte| *byte == b'`').count();+ if length < 3 {+ return None;+ }+ let language = opening.get(length..)?.trim();+ if language.contains('`') {+ return None;+ }+ let (body, closing) = rest.rsplit_once('\n')?;+ let closes = |line: &str| {+ let line = line.trim();+ line.len() >= length && line.bytes().all(|byte| byte == b'`')+ };+ if !closes(closing) || body.lines().any(closes) {+ return None;+ }+ Some((language, body))+}++/// Accept a complete call, not a JSON object quoted somewhere in an explanation.+fn json_action(text: &str) -> Option<ReactStep> {+ let text = text.trim();+ let raw = if text.starts_with("```") {+ let (language, body) = backtick_fence(text)?;+ if !matches!(language, "" | "json") {+ return None;+ }+ body.trim()+ } else {+ text+ };+ let value: Value = serde_json::from_str(raw).ok()?;+ let envelope = value.as_object()?;+ if envelope.contains_key("function")+ && (envelope.keys().any(|key| !matches!(key.as_str(), "function" | "type" | "id"))+ || envelope.get("type").is_some_and(|kind| kind.as_str() != Some("function")))+ {+ return None;+ }+ let function = value.get("function").unwrap_or(&value);+ let fields = function.as_object()?;+ if fields.keys().any(|key| !matches!(key.as_str(), "name" | "arguments" | "parameters"))+ || fields.contains_key("arguments") == fields.contains_key("parameters")+ {+ return None;+ }+ let tool = function.get("name")?.as_str()?.trim();+ if tool.is_empty() {+ return None;+ }+ let arguments = function.get("arguments").or_else(|| function.get("parameters"))?;+ let input: Value = match arguments.as_str() {+ Some(encoded) => serde_json::from_str(encoded).ok()?,+ None => arguments.clone(),+ };+ input.is_object().then(|| ReactStep::Action { tool: tool.to_string(), input })+}+/// The first balanced `{…}` in `s`, parsed.fn extract_json_object(s: &str) -> Option<Value> {let start = s.find('{')?;@@ -385,14 +460,22 @@ fn extract_json_object(s: &str) -> Option<Value> {static REACT_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);-/// Turn ReAct text into neutral tool-use blocks.-fn react_postprocess(r: &mut TurnResult) {+/// Recover complete text calls as neutral tool-use blocks.+fn react_postprocess(r: &mut TurnResult, tools: &[ToolDef], react: bool) {+ if !matches!(r.stop, StopReason::EndTurn | StopReason::ToolUse) || !r.message.tool_uses().is_empty() {+ return;+ }let text = r.message.text();- if let ReactStep::Action { tool, input } = parse_react(&text) {+ let json_call = json_action(&text);+ let from_json = json_call.is_some();+ let step = json_call.or_else(|| react.then(|| parse_react(&text)));+ if let Some(ReactStep::Action { tool, input }) = step+ && (!from_json || tools.iter().any(|definition| definition.name == tool))+ {let n = REACT_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);r.message.blocks.push(Block::ToolUse { id: format!("react_{n}"), name: tool, input });r.stop = StopReason::ToolUse;- } else {+ } else if react {r.stop = StopReason::EndTurn;}}@@ -402,6 +485,80 @@ mod tests {use super::*;use crate::model::Effort;+ #[test]+ fn json_text_calls_and_non_calls() {+ for text in [+ r#"{"name":"look","arguments":{"path":"app"}}"#,+ r#"{"name":"look","parameters":{"path":"app"}}"#,+ r#"{"name":"look","arguments":"{\"path\":\"app\"}"}"#,+ r#"{"type":"function","function":{"name":"look","arguments":{"path":"app"}}}"#,+ "```json\n{\"name\":\"look\",\"arguments\":{\"path\":\"app\"}}\n```",+ "```\n{\"name\":\"look\",\"arguments\":{\"path\":\"app\"}}\n```",+ "```json\n{\"name\":\"look\",\"arguments\":{\"path\":\"app\"}}\n````",+ "````json\n{\"name\":\"look\",\"arguments\":{\"path\":\"app\"}}\n````",+ "````\n{\"name\":\"look\",\"arguments\":{\"path\":\"app\"}}\n`````",+ ] {+ assert_eq!(parse_react(text), ReactStep::Action { tool: "look".into(), input: json!({"path": "app"}) }, "{text}");+ }+ for text in [+ r#"{"name":"look","arguments":{"path":"app"}"#,+ r#"{"name":"look","arguments":"not JSON"}"#,+ r#"{"name":"look","arguments":["app"]}"#,+ r#"{"name":"look"}"#,+ r#"{"name":"look","arguments":{},"description":"This is an example"}"#,+ r#"{"name":"look","arguments":{},"parameters":{"path":"different"}}"#,+ r#"{"type":"example","function":{"name":"look","arguments":{}}}"#,+ r#"{"name":"","arguments":{}}"#,+ r#"{"answer":"Action: look\nAction Input: {}"}"#,+ r#"[{"name":"look","arguments":{}}]"#,+ r#"For example, use {"name":"look","arguments":{}}."#,+ "```json\n{\"name\":\"look\",\"arguments\":{}}\n```\nThis is an example.",+ "```json\n{\"name\":\"look\",\"arguments\":{}}```",+ "```json`example\n{\"name\":\"look\",\"arguments\":{}}\n```",+ "````json\n{\"name\":\"look\",\"arguments\":{}}\n```",+ "```json\n{\"name\":\"look\",\"arguments\":{}}\n```\nThis is only an example.\n```",+ ] {+ assert!(matches!(parse_react(text), ReactStep::Text(_)), "{text}");+ }+ assert_eq!(+ parse_react(r#"{"name":"look","arguments":{"text":"Final Answer: is a label"}}"#),+ ReactStep::Action { tool: "look".into(), input: json!({"text":"Final Answer: is a label"}) }+ );+ }++ #[test]+ fn fenced_legacy_react_calls_still_parse() {+ for text in [+ "```\nAction: look\nAction Input: {\"path\":\"app\"}\n```",+ "```text\nAction: look\nAction Input: {\"path\":\"app\"}\n```",+ "```json\nThought: inspect the app\nAction: look\nAction Input: {\"path\":\"app\"}\n```",+ " \n```\r\nAction: look\r\nAction Input: {\"path\":\"app\"}\r\n```\n ",+ "```text\nAction: look\nAction Input: {\"path\":\"app\"}\n ``` \t",+ "```text\nAction: look\nAction Input: {\"path\":\"app\"}\n````",+ "````text\nAction: look\nAction Input: {\"path\":\"app\"}\n````",+ "````text\nAction: look\nAction Input: ```json\n{\"path\":\"app\"}\n```\n````",+ ] {+ assert_eq!(parse_react(text), ReactStep::Action { tool: "look".into(), input: json!({"path": "app"}) }, "{text}");+ }+ for text in [+ "```json\n{\"answer\":\"Action: look\\nAction Input: {}\"}\n```",+ "```\n[\"Action: look\\nAction Input: {}\"]\n```",+ "```python\nprint(\"Action: look\\nAction Input: {}\")\n```",+ "```\nThis is an example.\nAction: look\nAction Input: {}\n```",+ "```\nAction: look\nAction Input: {}",+ "```\nAction: look\nAction Input: {}\n```\nThis is only an example.",+ "```text\nAction: look\nAction Input: {}\n```not a close```",+ "```text\nAction: look\nAction Input: {}```",+ "````text\nAction: look\nAction Input: {}\n```",+ "```text\nAction: look\nAction Input: {}\n```\nThis is only an example.\n```",+ "```text\nAction: look\nAction Input: {}\n````\nThis is only an example.\n```",+ "````text\nAction: look\nAction Input: {}\n````\nThis is only an example.\n````",+ "```json\n{\"name\":\"look\",\"arguments\":{}}```",+ ] {+ assert!(matches!(parse_react(text), ReactStep::Text(_)), "{text}");+ }+ }+#[test]fn react_parsing() {assert_eq!(diff --git a/crates/ai/src/tests.rs b/crates/ai/src/tests.rsindex e43e367e..57eab5e9 100644--- a/crates/ai/src/tests.rs+++ b/crates/ai/src/tests.rs@@ -597,6 +597,172 @@ fn local_server_without_tools_falls_back_to_react() {assert!(last["content"].as_str().unwrap().starts_with("Observation:"));}+#[test]+fn json_text_tool_calls_execute_through_both_protocols() {+ for react in [false, true] {+ for call in [+ r#"{"name":"core_session_show","arguments":{}}"#,+ "```json\n{\"name\":\"core_session_show\",\"arguments\":{}}\n````",+ "````json\n{\"name\":\"core_session_show\",\"arguments\":{}}\n````",+ ] {+ let t1 = chat_sse(&[json!({"choices":[{"delta":{"content":call},"finish_reason":"stop"}]})]);+ let t2 = chat_sse(&[json!({"choices":[{"delta":{"content":"Nothing open."},"finish_reason":"stop"}]})]);+ let (url, seen) = mock(vec![(200, "text/event-stream", t1), (200, "text/event-stream", t2)]);+ let (hub, _dir) = hub();+ let config = BackendConfig {+ name: "Local".into(),+ kind: BackendKind::OpenaiCompatible,+ model: "scripted".into(),+ base_url: Some(url),+ ssh_host: None,+ enabled: true,+ };+ hub.add_backend_with(BackendEntry { config, options: BackendOptions { react_fallback: Some(react), ..Default::default() } }, None).unwrap();+ let mut conversation = hub.start(Some("Local"), true).unwrap();+ let events = run(&mut conversation, "status?");+ assert_eq!(+ events.iter().filter(|e| matches!(e, AgentEvent::ToolFinished { tool, ok: true, .. } if tool == "core_session_show")).count(),+ 1,+ "react={react}, call={call}: {events:?}"+ );+ assert!(events.iter().any(|e| matches!(e, AgentEvent::TextDelta { text } if text == "Nothing open.")), "{events:?}");+ let seen = seen.lock().unwrap();+ assert_eq!(seen.len(), 2);+ let messages = seen[1].body["messages"].as_array().unwrap();+ let result = messages.last().unwrap();+ if react {+ assert_eq!(result["role"], "user");+ assert!(result["content"].as_str().unwrap().starts_with("Observation:"));+ } else {+ assert_eq!(result["role"], "tool");+ assert_eq!(result["tool_call_id"], messages[2]["tool_calls"][0]["id"]);+ assert_eq!(messages[2]["tool_calls"][0]["function"]["name"], "core_session_show");+ }+ }+ }+}++#[test]+fn react_action_errors_still_reach_the_tool_loop() {+ let replies = ["Action: missing_tool\nAction Input: {}", "Action: core_session_show\nAction Input: {}", "Final Answer: Nothing open."]+ .map(|text| (200, "text/event-stream", chat_sse(&[json!({"choices":[{"delta":{"content":text},"finish_reason":"stop"}]})])));+ let (url, seen) = mock(replies.into());+ let (hub, _dir) = hub();+ let config = BackendConfig {+ name: "Local".into(),+ kind: BackendKind::OpenaiCompatible,+ model: "scripted".into(),+ base_url: Some(url),+ ssh_host: None,+ enabled: true,+ };+ hub.add_backend_with(BackendEntry { config, options: BackendOptions { react_fallback: Some(true), ..Default::default() } }, None).unwrap();+ let mut conversation = hub.start(Some("Local"), true).unwrap();+ let events = run(&mut conversation, "status?");+ assert!(events.iter().any(|e| matches!(e, AgentEvent::ToolFinished { tool, ok: false, .. } if tool == "missing_tool")), "{events:?}");+ assert!(events.iter().any(|e| matches!(e, AgentEvent::ToolFinished { tool, ok: true, .. } if tool == "core_session_show")), "{events:?}");+ let seen = seen.lock().unwrap();+ assert_eq!(seen.len(), 3);+ let correction = seen[1].body["messages"].as_array().unwrap().last().unwrap()["content"].as_str().unwrap();+ assert!(correction.starts_with("Observation (error):") && correction.contains("No tool named missing_tool"), "{correction}");+}++#[test]+fn fenced_legacy_react_calls_still_execute() {+ for call in [+ "```text\nAction: core_session_show\nAction Input: {}\n```",+ "```text\nAction: core_session_show\nAction Input: {}\n````",+ "````text\nAction: core_session_show\nAction Input: {}\n````",+ "````text\nAction: core_session_show\nAction Input: ```json\n{}\n```\n````",+ ] {+ let replies = [call, "Final Answer: Nothing open."]+ .map(|text| (200, "text/event-stream", chat_sse(&[json!({"choices":[{"delta":{"content":text},"finish_reason":"stop"}]})])));+ let (url, seen) = mock(replies.into());+ let (hub, _dir) = hub();+ let config = BackendConfig {+ name: "Local".into(),+ kind: BackendKind::OpenaiCompatible,+ model: "scripted".into(),+ base_url: Some(url),+ ssh_host: None,+ enabled: true,+ };+ hub.add_backend_with(BackendEntry { config, options: BackendOptions { react_fallback: Some(true), ..Default::default() } }, None).unwrap();+ let mut conversation = hub.start(Some("Local"), true).unwrap();+ let events = run(&mut conversation, "status?");+ assert_eq!(+ events.iter().filter(|e| matches!(e, AgentEvent::ToolFinished { tool, ok: true, .. } if tool == "core_session_show")).count(),+ 1,+ "the fenced legacy call must execute exactly once: {events:?}"+ );+ assert!(events.iter().any(|e| matches!(e, AgentEvent::TextDelta { text } if text == "Final Answer: Nothing open.")), "{events:?}");+ let seen = seen.lock().unwrap();+ assert_eq!(seen.len(), 2);+ let observation = seen[1].body["messages"].as_array().unwrap().last().unwrap()["content"].as_str().unwrap();+ assert!(observation.starts_with("Observation:"), "{observation}");+ }+}++#[test]+fn json_text_recovery_preserves_non_actions_and_stop_reasons() {+ use crate::model::{Effort, Msg, Stop, StopReason, ToolDef, TurnRequest};+ let tools = [ToolDef { name: "look".into(), description: "Look at a file".into(), schema: json!({"type":"object"}) }];+ let messages = [Msg::user_text("check")];+ let request = TurnRequest { system: "S", messages: &messages, tools: &tools, effort: Effort::Low, max_tokens: 100 };+ for react in [false, true] {+ for (text, finish, expected) in [+ (r#"{"name":"unknown","arguments":{}}"#, "stop", StopReason::EndTurn),+ (r#"{"name":"look","arguments":{}}"#, "length", StopReason::MaxTokens),+ (r#"{"name":"look","arguments":{}}"#, "content_filter", StopReason::Refusal),+ (r#"{"name":"look","arguments":{}"#, "stop", StopReason::EndTurn),+ (r#"{"answer":42}"#, "stop", StopReason::EndTurn),+ (r#"For example: {"name":"look","arguments":{}}"#, "stop", StopReason::EndTurn),+ ("```text\nAction: look\nAction Input: {}\n```not a close```", "stop", StopReason::EndTurn),+ ("```json\n{\"name\":\"look\",\"arguments\":{}}```", "stop", StopReason::EndTurn),+ ("```text\nAction: look\nAction Input: {}```", "stop", StopReason::EndTurn),+ ("````text\nAction: look\nAction Input: {}\n```", "stop", StopReason::EndTurn),+ ("```text\nAction: look\nAction Input: {}\n```\nThis is only an example.\n```", "stop", StopReason::EndTurn),+ ] {+ let reply = chat_sse(&[json!({"choices":[{"delta":{"content":text},"finish_reason":finish}]})]);+ let (url, _seen) = mock(vec![(200, "text/event-stream", reply)]);+ let mut model = openai::OpenAi::compatible("Local", &url, None, "scripted");+ model.react = react;+ let result = model.turn(&request, &mut |_| {}, &Stop::default()).unwrap();+ assert!(result.message.tool_uses().is_empty(), "{result:?}");+ assert_eq!(result.stop, expected, "{text}");+ }+ }+ let call = r#"{"name":"look","arguments":{}}"#;+ for (automatic, offered) in [(false, tools.as_slice()), (true, &[])] {+ let reply = chat_sse(&[json!({"choices":[{"delta":{"content":call},"finish_reason":"stop"}]})]);+ let (url, _seen) = mock(vec![(200, "text/event-stream", reply)]);+ let mut model = openai::OpenAi::compatible("Local", &url, None, "scripted");+ model.auto_react = automatic;+ let request = TurnRequest { system: "S", messages: &messages, tools: offered, effort: Effort::Low, max_tokens: 100 };+ assert!(model.turn(&request, &mut |_| {}, &Stop::default()).unwrap().message.tool_uses().is_empty());+ }+}++#[test]+fn native_tool_calls_are_not_duplicated_by_json_text() {+ use crate::model::{Effort, Msg, Stop, StopReason, ToolDef, TurnRequest};+ let tools = [ToolDef { name: "look".into(), description: "Look at a file".into(), schema: json!({"type":"object"}) }];+ let messages = [Msg::user_text("check")];+ let request = TurnRequest { system: "S", messages: &messages, tools: &tools, effort: Effort::Low, max_tokens: 100 };+ for react in [false, true] {+ let reply = chat_sse(&[json!({"choices":[{"delta":{+ "content":r#"{"name":"look","arguments":{}}"#,+ "tool_calls":[{"index":0,"id":"native_call","type":"function","function":{"name":"look","arguments":"{}"}}]+ },"finish_reason":"tool_calls"}]})]);+ let (url, _seen) = mock(vec![(200, "text/event-stream", reply)]);+ let mut model = openai::OpenAi::compatible("Local", &url, None, "scripted");+ model.react = react;+ let result = model.turn(&request, &mut |_| {}, &Stop::default()).unwrap();+ assert_eq!(result.message.tool_uses(), vec![("native_call".into(), "look".into(), json!({}))]);+ assert_eq!(result.stop, StopReason::ToolUse);+ }+}+#[test]fn hub_config_keys_and_test_backend() {let t = sse(&[diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex 7212e1e3..b11e051b 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -194,7 +194,7 @@ been run live.STATUS.md which models it worked with. Do this first: it shows which of the lines below matter- [ ] An assistant turn with no text sends `content: null` (`openai.rs`), which likely causes #403's`invalid message content type: <nil>`: send an empty string-- [ ] Understand a tool call a model writes as JSON in its text (#417). The fallback protocol reads+- [x] Understand a tool call a model writes as JSON in its text (#417; implementation `dfe9a4db2dcb3e27edbd67311cbb4202584e7af6`). The fallback protocol readsonly `Action:` and `Action Input:` lines, so anything else ends the turn with nothing done- [x] Preserve `length` and `content_filter` stop reasons on native tool-call streams; a parsedcall must not override truncation or refusal and execute tools. Pair other retaineddiff --git a/docs/STATUS.md b/docs/STATUS.mdindex 4353a8b5..f5824289 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -127,6 +127,24 @@ not been rechecked for this change; Windows runtime validation remains on the roThe full workspace gates (`cargo xtask ci`) passed in [hosted CI for #541](https://github.com/storytold/craft-anything/actions/runs/41584228995).+### Tool calls written as JSON++The text fallback accepts complete bare or fenced JSON calls with `name` and `arguments`+(`parameters` also accepted), including a `function` wrapper and JSON-encoded arguments.+Automatic recovery also handles these responses when native tool calling was offered. A call+must name a tool offered in that turn; ordinary JSON answers and JSON examples surrounded by+prose are left as text. Native calls are kept once; text-call recovery skips truncated or refused replies.+Complete backtick-fenced legacy ReAct steps remain supported when their body begins with an explicit+protocol marker. Both parsers use the same fence boundaries: at least three opening backticks and a+standalone closing line of at least that length, with no earlier matching closing fence. Shorter+backtick lines inside a longer fence remain content. Ordinary fenced code, malformed fences and non-call+JSON objects or examples containing protocol markers remain text; valid call arguments may contain those markers.+The parser regressions failed on the previous guards and passed with their corrections.+Fenced JSON calls also use these boundaries during automatic recovery and accept only an empty or `json` info string.+Checked with parser fixtures, HTTP/SSE stand-ins exercising real engine tool execution in both+protocols, and non-action, stop-reason and duplicate-call controls. No live local-model build+was run; other text-call formats remain unsupported.+## Known limits- Locks: every mutex but the browser viewer's goes through `platform::sync`. A deadlock on one thread or acrossdiff --git a/docs/pitfalls.md b/docs/pitfalls.mdindex 6d48b305..839f5dfa 100644--- a/docs/pitfalls.md+++ b/docs/pitfalls.md@@ -495,3 +495,10 @@ naming a tool.branch; `git stash` keeps only tracked files, so a new file stayed in the tree and `git add -A`put it into the other PR. Use `git stash -u` (or commit the work in progress on its own branch),and read `git status` before `git add -A`.++**Fence checks that disagreed about tool calls.** Suffix checks accepted malformed closing text,+while requiring exactly three closing backticks rejected valid longer fences. Share one boundary+parser between JSON recovery and ReAct: count the opener, require a standalone closing line at+least that long, and reject an earlier matching close followed by more text. Shorter backtick+lines inside a longer fence are content. Test both paths and the next HTTP request, including+malformed suffixes and non-call JSON examples whose strings contain protocol markers.