interplane-mv
INTERPLANE: open interoperability protocol between AI models and agent runtimes. Models express intent. Runtimes retain authority.
Brought by drakestapleton
interplane-mv / rust / crates / interplane-lenshift / src / qwen35.rs
| 1 | //! Dialect `qwen35` (version 1): the Qwen3.5 chat-template tool-call grammar as text. |
| 2 | use interplane_core::{ErrorCode, ToolRequest, ToolResult}; |
| 3 | use serde_json::{Map, Value}; |
| 4 | |
| 5 | use crate::*; |
| 6 | |
| 7 | pub struct Qwen35; |
| 8 | |
| 9 | const TC_OPEN: &str = "<tool_call>"; |
| 10 | const TC_CLOSE: &str = "</tool_call>"; |
| 11 | |
| 12 | /// How a body parse can fail. |
| 13 | enum BodyError { |
| 14 | Truncated, |
| 15 | Malformed(String), |
| 16 | } |
| 17 | |
| 18 | struct Call { |
| 19 | name: String, |
| 20 | args: Map<String, Value>, |
| 21 | hermes: bool, |
| 22 | } |
| 23 | |
| 24 | /// Strip exactly one leading and one trailing newline (the template emits `\n` + value + `\n`). |
| 25 | fn strip_one_newline(v: &str) -> &str { |
| 26 | let v = v.strip_prefix('\n').unwrap_or(v); |
| 27 | v.strip_suffix('\n').unwrap_or(v) |
| 28 | } |
| 29 | |
| 30 | fn json_guess(v: &str) -> Value { |
| 31 | match serde_json::from_str::<Value>(v) { |
| 32 | Ok(Value::String(_)) | Err(_) => Value::String(v.to_string()), |
| 33 | Ok(parsed) => parsed, |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | fn parse_body(body: &str) -> Result<Call, BodyError> { |
| 38 | let b = body.trim(); |
| 39 | if let Some(rest) = b.strip_prefix("<function=") { |
| 40 | let gt = rest.find('>').ok_or(BodyError::Truncated)?; |
| 41 | let name = rest[..gt].trim().to_string(); |
| 42 | if name.is_empty() { |
| 43 | return Err(BodyError::Malformed("empty function name".into())); |
| 44 | } |
| 45 | let mut rest = &rest[gt + 1..]; |
| 46 | let mut args = Map::new(); |
| 47 | loop { |
| 48 | rest = rest.trim_start(); |
| 49 | if rest.starts_with("</function>") { |
| 50 | return Ok(Call { |
| 51 | name, |
| 52 | args, |
| 53 | hermes: false, |
| 54 | }); |
| 55 | } |
| 56 | if let Some(p) = rest.strip_prefix("<parameter=") { |
| 57 | let gt = p.find('>').ok_or(BodyError::Truncated)?; |
| 58 | let key = p[..gt].trim().to_string(); |
| 59 | let after = &p[gt + 1..]; |
| 60 | let end = after.find("</parameter>").ok_or(BodyError::Truncated)?; |
| 61 | if key.is_empty() { |
| 62 | return Err(BodyError::Malformed("empty parameter name".into())); |
| 63 | } |
| 64 | if args.contains_key(&key) { |
| 65 | return Err(BodyError::Malformed(format!("duplicate parameter: {key}"))); |
| 66 | } |
| 67 | args.insert(key, json_guess(strip_one_newline(&after[..end]))); |
| 68 | rest = &after[end + "</parameter>".len()..]; |
| 69 | } else if rest.is_empty() { |
| 70 | return Err(BodyError::Truncated); |
| 71 | } else { |
| 72 | return Err(BodyError::Malformed( |
| 73 | "unexpected content in function body".into(), |
| 74 | )); |
| 75 | } |
| 76 | } |
| 77 | } |
| 78 | if b.starts_with('{') { |
| 79 | let v: Value = serde_json::from_str(b) |
| 80 | .map_err(|_| BodyError::Malformed("tool call body is not valid JSON".into()))?; |
| 81 | let name = v |
| 82 | .get("name") |
| 83 | .and_then(Value::as_str) |
| 84 | .unwrap_or("") |
| 85 | .trim() |
| 86 | .to_string(); |
| 87 | if name.is_empty() { |
| 88 | return Err(BodyError::Malformed("missing tool name".into())); |
| 89 | } |
| 90 | let args = match v.get("arguments") { |
| 91 | None | Some(Value::Null) => Map::new(), |
| 92 | Some(Value::Object(m)) => m.clone(), |
| 93 | Some(Value::String(s)) => match serde_json::from_str::<Value>(s) { |
| 94 | Ok(Value::Object(m)) => m, |
| 95 | _ => return Err(BodyError::Malformed("arguments is not an object".into())), |
| 96 | }, |
| 97 | Some(_) => return Err(BodyError::Malformed("arguments is not an object".into())), |
| 98 | }; |
| 99 | return Ok(Call { |
| 100 | name, |
| 101 | args, |
| 102 | hermes: true, |
| 103 | }); |
| 104 | } |
| 105 | if b.starts_with("<function") { |
| 106 | // `<function=` never completed. |
| 107 | return Err(BodyError::Truncated); |
| 108 | } |
| 109 | Err(BodyError::Malformed("unrecognized tool call body".into())) |
| 110 | } |
| 111 | |
| 112 | impl Dialect for Qwen35 { |
| 113 | fn name(&self) -> &str { |
| 114 | "qwen35" |
| 115 | } |
| 116 | fn version(&self) -> &str { |
| 117 | "1" |
| 118 | } |
| 119 | |
| 120 | fn parse(&self, input: &Value, ctx: &ParseContext) -> LenshiftTurn { |
| 121 | let mut turn = LenshiftTurn { |
| 122 | dialect: "qwen35".into(), |
| 123 | dialect_version: "1".into(), |
| 124 | parser_version: PARSER_VERSION.into(), |
| 125 | model: ctx.model.clone(), |
| 126 | text: String::new(), |
| 127 | reasoning_digest: None, |
| 128 | intents: vec![], |
| 129 | rejected: vec![], |
| 130 | partial: false, |
| 131 | intent_indices: vec![], |
| 132 | }; |
| 133 | let Some(full) = input.as_str() else { |
| 134 | turn.rejected.push(RejectedCall { |
| 135 | index: 0, |
| 136 | code: ErrorCode::MalformedToolCall, |
| 137 | message: "input is not text".into(), |
| 138 | source_digest: Some(interplane_core::digest(input)), |
| 139 | request_id: assign_request_id(None, ctx, 0), |
| 140 | }); |
| 141 | return turn; |
| 142 | }; |
| 143 | |
| 144 | // 1. Remove <think>...</think> blocks; digest the first one's content. |
| 145 | let mut visible = String::new(); |
| 146 | let mut rest = full; |
| 147 | let mut first_think: Option<&str> = None; |
| 148 | while let Some(s) = rest.find("<think>") { |
| 149 | let after = &rest[s + "<think>".len()..]; |
| 150 | match after.find("</think>") { |
| 151 | Some(e) => { |
| 152 | visible.push_str(&rest[..s]); |
| 153 | first_think.get_or_insert(&after[..e]); |
| 154 | rest = &after[e + "</think>".len()..]; |
| 155 | } |
| 156 | None => break, |
| 157 | } |
| 158 | } |
| 159 | visible.push_str(rest); |
| 160 | turn.reasoning_digest = first_think |
| 161 | .map(|t| t.trim_matches('\n')) |
| 162 | .filter(|t| !t.trim().is_empty()) |
| 163 | .map(text_digest); |
| 164 | |
| 165 | // 2. Walk tool calls. |
| 166 | let mut text = String::new(); |
| 167 | let mut rest = visible.as_str(); |
| 168 | let mut index = 0usize; |
| 169 | let mut trailing = false; |
| 170 | while let Some(s) = rest.find(TC_OPEN) { |
| 171 | text.push_str(&rest[..s]); |
| 172 | let from_open = &rest[s..]; |
| 173 | let request_id = assign_request_id(None, ctx, index); |
| 174 | let Some(e) = from_open.find(TC_CLOSE) else { |
| 175 | turn.partial = true; |
| 176 | turn.rejected.push(RejectedCall { |
| 177 | index, |
| 178 | code: ErrorCode::MalformedToolCall, |
| 179 | message: "truncated tool call".into(), |
| 180 | source_digest: Some(text_digest(from_open)), |
| 181 | request_id, |
| 182 | }); |
| 183 | rest = ""; |
| 184 | break; |
| 185 | }; |
| 186 | let block = &from_open[..e + TC_CLOSE.len()]; |
| 187 | let body = &block[TC_OPEN.len()..block.len() - TC_CLOSE.len()]; |
| 188 | let src = text_digest(block); |
| 189 | match parse_body(body) { |
| 190 | Ok(call) => match canonical_tool(&call.name) { |
| 191 | Some(tool) => { |
| 192 | let (ver, coercion) = if call.hermes { |
| 193 | ("hermes_json", "none") |
| 194 | } else { |
| 195 | ("1", "json_guess") |
| 196 | }; |
| 197 | turn.intents.push(make_intent( |
| 198 | "qwen35", ver, ctx, request_id, tool, call.args, None, src, &call.name, |
| 199 | coercion, |
| 200 | )); |
| 201 | turn.intent_indices.push(index); |
| 202 | } |
| 203 | None => turn.rejected.push(RejectedCall { |
| 204 | index, |
| 205 | code: ErrorCode::MalformedToolCall, |
| 206 | message: "invalid tool name".into(), |
| 207 | source_digest: Some(src), |
| 208 | request_id, |
| 209 | }), |
| 210 | }, |
| 211 | Err(err) => { |
| 212 | let message = match err { |
| 213 | BodyError::Truncated => { |
| 214 | turn.partial = true; |
| 215 | "truncated tool call".to_string() |
| 216 | } |
| 217 | BodyError::Malformed(m) => m, |
| 218 | }; |
| 219 | turn.rejected.push(RejectedCall { |
| 220 | index, |
| 221 | code: ErrorCode::MalformedToolCall, |
| 222 | message, |
| 223 | source_digest: Some(src), |
| 224 | request_id, |
| 225 | }); |
| 226 | } |
| 227 | } |
| 228 | index += 1; |
| 229 | rest = &from_open[e + TC_CLOSE.len()..]; |
| 230 | trailing = !rest.contains(TC_OPEN) && !rest.trim().is_empty(); |
| 231 | } |
| 232 | text.push_str(rest); |
| 233 | turn.text = text.trim().to_string(); |
| 234 | if trailing { |
| 235 | for i in &mut turn.intents { |
| 236 | i.provenance |
| 237 | .extensions |
| 238 | .insert("trailing_text".into(), Value::Bool(true)); |
| 239 | } |
| 240 | } |
| 241 | turn |
| 242 | } |
| 243 | |
| 244 | fn render_result(&self, result: &ToolResult, _intent: Option<&ToolRequest>) -> Value { |
| 245 | Value::String(format!( |
| 246 | "<tool_response>\n{}\n</tool_response>", |
| 247 | serialize_result(result) |
| 248 | )) |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | #[cfg(test)] |
| 253 | mod tests { |
| 254 | use super::*; |
| 255 | use interplane_core::{digest_bytes, ResultStatus}; |
| 256 | use serde_json::json; |
| 257 | |
| 258 | fn ctx() -> ParseContext { |
| 259 | ParseContext { |
| 260 | trace_id: "tr".into(), |
| 261 | turn: 0, |
| 262 | model: "Qwen/Qwen3.5-9B".into(), |
| 263 | } |
| 264 | } |
| 265 | fn p(s: &str) -> LenshiftTurn { |
| 266 | Qwen35.parse(&json!(s), &ctx()) |
| 267 | } |
| 268 | const CALL: &str = "<tool_call>\n<function=read_file>\n<parameter=path>\n/a.txt\n</parameter>\n</function>\n</tool_call>"; |
| 269 | |
| 270 | #[test] |
| 271 | fn valid_single_call_and_source_digest() { |
| 272 | let t = p(&format!("Let me look.\n\n{CALL}")); |
| 273 | assert_eq!(t.text, "Let me look."); |
| 274 | assert_eq!(t.intents.len(), 1); |
| 275 | let i = &t.intents[0]; |
| 276 | assert_eq!(i.tool.name, "read_file"); |
| 277 | assert_eq!(i.arguments["path"], json!("/a.txt")); |
| 278 | assert_eq!( |
| 279 | i.provenance.source_digest.as_deref(), |
| 280 | Some(digest_bytes(CALL.as_bytes()).as_str()) |
| 281 | ); |
| 282 | assert_eq!(i.provenance.coercion.as_deref(), Some("json_guess")); |
| 283 | assert_eq!(i.request_id, "tr:t0:c0"); |
| 284 | assert!(!t.partial && t.rejected.is_empty()); |
| 285 | } |
| 286 | #[test] |
| 287 | fn multiple_calls_and_indices() { |
| 288 | let t = p(&format!("{CALL}\n{CALL}")); |
| 289 | assert_eq!(t.intents.len(), 2); |
| 290 | assert_eq!(t.intent_indices, vec![0, 1]); |
| 291 | assert_eq!(t.intents[1].request_id, "tr:t0:c1"); |
| 292 | } |
| 293 | #[test] |
| 294 | fn json_guess_and_multiline() { |
| 295 | let t = p("<tool_call>\n<function=f>\n<parameter=n>\n42\n</parameter>\n<parameter=b>\ntrue\n</parameter>\n<parameter=s>\n\"quoted\"\n</parameter>\n<parameter=l>\nline1\nline2\n</parameter>\n<parameter=o>\n{\"a\": [1]}\n</parameter>\n<parameter=bad>\n{oops\n</parameter>\n</function>\n</tool_call>"); |
| 296 | let a = &t.intents[0].arguments; |
| 297 | assert_eq!(a["n"], json!(42)); |
| 298 | assert_eq!(a["b"], json!(true)); |
| 299 | assert_eq!(a["s"], json!("\"quoted\"")); |
| 300 | assert_eq!(a["l"], json!("line1\nline2")); |
| 301 | assert_eq!(a["o"], json!({"a": [1]})); |
| 302 | assert_eq!(a["bad"], json!("{oops")); |
| 303 | } |
| 304 | #[test] |
| 305 | fn reasoning_removed_and_digested() { |
| 306 | let t = p(&format!( |
| 307 | "<think>\nI should read.\n</think>\n\nOK\n\n{CALL}" |
| 308 | )); |
| 309 | assert_eq!(t.text, "OK"); |
| 310 | assert_eq!(t.reasoning_digest, Some(text_digest("I should read."))); |
| 311 | let t = p("<think>\n\n</think>\n\nhello"); |
| 312 | assert_eq!((t.text.as_str(), t.reasoning_digest), ("hello", None)); |
| 313 | } |
| 314 | #[test] |
| 315 | fn truncated_variants_are_partial_and_rejected() { |
| 316 | for s in [ |
| 317 | "<tool_call>\n<function=f>\n<parameter=a>\nx", |
| 318 | "<tool_call>\n<function=f>\n<parameter=a>\nx\n</parameter>\n</tool_call>", |
| 319 | "<tool_call>\n<function=f>\n</tool_call>", |
| 320 | "text <tool_call>", |
| 321 | ] { |
| 322 | let t = p(s); |
| 323 | assert!(t.partial, "{s}"); |
| 324 | assert!(t.intents.is_empty(), "{s}"); |
| 325 | assert_eq!(t.rejected.len(), 1, "{s}"); |
| 326 | assert_eq!(t.rejected[0].message, "truncated tool call"); |
| 327 | } |
| 328 | } |
| 329 | #[test] |
| 330 | fn duplicate_key_and_empty_names_are_malformed_not_partial() { |
| 331 | let t = p("<tool_call>\n<function=f>\n<parameter=a>\n1\n</parameter>\n<parameter=a>\n2\n</parameter>\n</function>\n</tool_call>"); |
| 332 | assert_eq!(t.rejected[0].message, "duplicate parameter: a"); |
| 333 | let t = p("<tool_call>\n<function=f>\n<parameter=a>\n1\n</parameter>\n<parameter=a>\n2\n</parameter>\n</function>\n</tool_call>"); |
| 334 | assert!(!t.partial && t.rejected.len() == 1); |
| 335 | let t = p("<tool_call>\n<function=>\n</function>\n</tool_call>"); |
| 336 | assert_eq!(t.rejected.len(), 1); |
| 337 | let t = p( |
| 338 | "<tool_call>\n<function=f>\n<parameter=>\n1\n</parameter>\n</function>\n</tool_call>", |
| 339 | ); |
| 340 | assert_eq!(t.rejected.len(), 1); |
| 341 | let t = p("<tool_call>garbage</tool_call>"); |
| 342 | assert_eq!(t.rejected[0].code, ErrorCode::MalformedToolCall); |
| 343 | } |
| 344 | #[test] |
| 345 | fn hermes_json_variant() { |
| 346 | let t = p("<tool_call>\n{\"name\": \"filesystem.read\", \"arguments\": {\"path\": \"/x\", \"n\": 1}}\n</tool_call>"); |
| 347 | assert_eq!(t.dialect_version, "1"); |
| 348 | let i = &t.intents[0]; |
| 349 | assert_eq!(i.provenance.dialect_version.as_deref(), Some("hermes_json")); |
| 350 | assert_eq!(i.tool.namespace.as_deref(), Some("filesystem")); |
| 351 | assert_eq!(i.arguments["n"], json!(1)); |
| 352 | assert_eq!(i.provenance.coercion.as_deref(), Some("none")); |
| 353 | } |
| 354 | #[test] |
| 355 | fn trailing_text_noted_not_an_error() { |
| 356 | let t = p(&format!("{CALL}\nafter")); |
| 357 | assert_eq!(t.text, "after"); |
| 358 | assert_eq!( |
| 359 | t.intents[0].provenance.extensions["trailing_text"], |
| 360 | json!(true) |
| 361 | ); |
| 362 | assert!(t.rejected.is_empty()); |
| 363 | } |
| 364 | #[test] |
| 365 | fn plain_and_unknown_tool_parse_fine() { |
| 366 | let t = p("The answer is 4."); |
| 367 | assert_eq!((t.text.as_str(), t.intents.len()), ("The answer is 4.", 0)); |
| 368 | let t = p("<tool_call>\n<function=nonexistent.thing>\n</function>\n</tool_call>"); |
| 369 | assert_eq!(t.intents[0].tool.name, "thing"); |
| 370 | assert_eq!(Qwen35.parse(&json!(5), &ctx()).rejected.len(), 1); |
| 371 | } |
| 372 | #[test] |
| 373 | fn render_wraps_in_tool_response() { |
| 374 | let r = ToolResult::ok("r", json!({"a": 1})); |
| 375 | assert_eq!( |
| 376 | Qwen35.render_result(&r, None), |
| 377 | json!("<tool_response>\n{\"a\":1}\n</tool_response>") |
| 378 | ); |
| 379 | let e = ToolResult::failed( |
| 380 | Some("r"), |
| 381 | ResultStatus::Rejected, |
| 382 | ErrorCode::MalformedToolCall, |
| 383 | "m", |
| 384 | ); |
| 385 | assert!(Qwen35 |
| 386 | .render_result(&e, None) |
| 387 | .as_str() |
| 388 | .unwrap() |
| 389 | .contains("\"status\":\"rejected\"")); |
| 390 | } |
| 391 | } |