Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/aien-serve-http/src/tools.rs # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-serve-http / src / tools.rs` 561 lines ยท 23153 bytes Raw Blame History 1 //! Tool calling in the model's own chat format, rendered exactly as its chat template does it (the 2 //! `tools` system block, assistant `tool_calls`, and `tool` messages folded into one user turn of 3 //! `` blocks), and the reply parsed back into OpenAI `tool_calls`. Two formats: 4 //! Qwen3.6/3.8 qwen3_coder XML (``) and the Hermes JSON of Qwen3-2507 5 //! (`{"name": .., "arguments": ..}`); [`ToolFormat::from_model_dir`] picks one from the template. 6 //! Drake 2026-10-21: "make it support tool use ... build it in". 7 8 use std::path::Path; 9 10 use serde_json::{Map, Value}; 11 12 /// The tool-calling layout of a model's chat template. 13 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] 14 pub enum ToolFormat { 15 /// Qwen3.6-35B-A3B / Qwen3.8-27B (`qwen3_coder`): XML function and parameter tags; the 16 /// tools block comes before the system text. 17 #[default] 18 Qwen3CoderXml, 19 /// Qwen3-2507 Instruct (e.g. Qwen3-30B-A3B-Instruct-2507): Hermes JSON inside ``; 20 /// the system text comes before the tools block. 21 HermesJson, 22 } 23 24 /// The sentence only the Hermes tools block carries. 25 const HERMES_MARKER: &str = "You may call one or more functions to assist with the user query."; 26 const HERMES_HEAD: &str = "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within XML tags:\n"; 27 const HERMES_TAIL: &str = "\n\n\nFor each function call, return a json object with function name and arguments within XML tags:\n\n{\"name\": , \"arguments\": }\n"; 28 29 impl ToolFormat { 30 /// Hermes JSON when the template carries the Hermes tools instruction, qwen3_coder XML otherwise. 31 pub fn detect(template_text: &str) -> Self { 32 if template_text.contains(HERMES_MARKER) { 33 Self::HermesJson 34 } else { 35 Self::Qwen3CoderXml 36 } 37 } 38 39 /// Reads the template from the sources `ChatTokenizer::from_model_dir` renders with, in its 40 /// order: `tokenizer_config.json` `chat_template`, else `chat_template.jinja`. No template: 41 /// qwen3_coder XML. 42 pub fn from_model_dir(dir: &Path) -> Result { 43 let read = 44 |p: &Path| std::fs::read_to_string(p).map_err(|e| format!("{}: {e}", p.display())); 45 let config = dir.join("tokenizer_config.json"); 46 if config.exists() { 47 let v: Value = serde_json::from_str(&read(&config)?) 48 .map_err(|e| format!("{}: {e}", config.display()))?; 49 if let Some(t) = v.get("chat_template").and_then(Value::as_str) { 50 return Ok(Self::detect(t)); 51 } 52 } 53 let jinja = dir.join("chat_template.jinja"); 54 if jinja.exists() { 55 return Ok(Self::detect(&read(&jinja)?)); 56 } 57 Ok(Self::Qwen3CoderXml) 58 } 59 60 pub fn system_with_tools(self, tools: &[Value], system: Option<&str>) -> String { 61 match self { 62 Self::Qwen3CoderXml => system_with_tools(tools, system), 63 Self::HermesJson => hermes_system_with_tools(tools, system), 64 } 65 } 66 67 pub fn assistant_with_calls(self, content: &str, calls: &[Value]) -> String { 68 match self { 69 Self::Qwen3CoderXml => assistant_with_calls(content, calls), 70 Self::HermesJson => hermes_assistant_with_calls(content, calls), 71 } 72 } 73 } 74 75 /// The chat turns of a request in this format: `msgs` are `(role, text, tool_calls)` with roles 76 /// already normalized to system/user/assistant/tool. Runs of `tool` messages fold into one user 77 /// turn; with tools, the first system turn carries the tools block (one is added when absent). 78 /// Both templates fold tool results the same way. 79 pub fn fold_turns( 80 format: ToolFormat, 81 tool_defs: &[Value], 82 msgs: Vec<(&str, String, Option<&[Value]>)>, 83 ) -> Vec<(String, String)> { 84 let mut turns: Vec<(String, String)> = Vec::with_capacity(msgs.len() + 1); 85 let mut pending_tool: Vec = Vec::new(); 86 for (role, text, calls) in msgs { 87 if role == "tool" { 88 pending_tool.push(text); 89 continue; 90 } 91 if !pending_tool.is_empty() { 92 turns.push(("user".into(), tool_responses(&pending_tool))); 93 pending_tool.clear(); 94 } 95 let text = match (role, calls) { 96 ("assistant", Some(calls)) if !calls.is_empty() => { 97 format.assistant_with_calls(&text, calls) 98 } 99 _ => text, 100 }; 101 turns.push((role.to_string(), text)); 102 } 103 if !pending_tool.is_empty() { 104 turns.push(("user".into(), tool_responses(&pending_tool))); 105 } 106 if !tool_defs.is_empty() { 107 match turns.first_mut() { 108 Some((r, c)) if r == "system" => { 109 *c = format.system_with_tools(tool_defs, Some(c.as_str())); 110 } 111 _ => turns.insert( 112 0, 113 ("system".into(), format.system_with_tools(tool_defs, None)), 114 ), 115 } 116 } 117 turns 118 } 119 120 const TOOLS_HEAD: &str = "# Tools\n\nYou have access to the following functions:\n\n"; 121 const TOOLS_TAIL: &str = "\n\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n"; 122 123 pub const OPEN: &str = ""; 124 const CLOSE: &str = ""; 125 126 /// Python `json.dumps`-style text (", " and ": " separators), which is what jinja's `tojson` emits 127 /// for the template. Keys come out sorted (serde_json without preserve_order); the model reads either order. 128 pub fn tojson(v: &Value) -> String { 129 match v { 130 Value::Object(m) => { 131 let parts: Vec = m 132 .iter() 133 .map(|(k, v)| format!("{}: {}", Value::String(k.clone()), tojson(v))) 134 .collect(); 135 format!("{{{}}}", parts.join(", ")) 136 } 137 Value::Array(a) => format!("[{}]", a.iter().map(tojson).collect::>().join(", ")), 138 other => other.to_string(), 139 } 140 } 141 142 /// qwen3_coder: the system turn's content when tools are present: the tools block, then the 143 /// request's own system text after a blank line (the template trims it and drops it when empty). 144 pub fn system_with_tools(tools: &[Value], system: Option<&str>) -> String { 145 let mut s = String::from(TOOLS_HEAD); 146 for t in tools { 147 s.push('\n'); 148 s.push_str(&tojson(t)); 149 } 150 s.push_str(TOOLS_TAIL); 151 if let Some(sys) = system.map(str::trim).filter(|x| !x.is_empty()) { 152 s.push_str("\n\n"); 153 s.push_str(sys); 154 } 155 s 156 } 157 158 /// qwen3_coder: an assistant turn's content with its `tool_calls` appended in the template's layout. 159 pub fn assistant_with_calls(content: &str, calls: &[Value]) -> String { 160 let mut s = content.to_string(); 161 for (i, call) in calls.iter().enumerate() { 162 let f = call.get("function").unwrap_or(call); 163 let name = f.get("name").and_then(Value::as_str).unwrap_or(""); 164 if i == 0 { 165 if content.trim().is_empty() { 166 s.push_str("\n\n\n\n"); 175 // OpenAI sends arguments as a JSON string; the template iterates a mapping. 176 let args = match f.get("arguments") { 177 Some(Value::String(t)) => serde_json::from_str::(t).unwrap_or(Value::Null), 178 Some(v) => v.clone(), 179 None => Value::Null, 180 }; 181 if let Value::Object(m) = args { 182 for (k, v) in m { 183 s.push_str("\n"); 186 match v { 187 Value::String(t) => s.push_str(&t), 188 other => s.push_str(&tojson(&other)), 189 } 190 s.push_str("\n\n"); 191 } 192 } 193 s.push_str("\n"); 194 } 195 s 196 } 197 198 /// Hermes: the system turn's content when tools are present: the request's system text verbatim 199 /// and a blank line (the template neither trims nor drops it), then the tools block, one 200 /// `tojson` line per tool. 201 pub fn hermes_system_with_tools(tools: &[Value], system: Option<&str>) -> String { 202 let mut s = String::new(); 203 if let Some(sys) = system { 204 s.push_str(sys); 205 s.push_str("\n\n"); 206 } 207 s.push_str(HERMES_HEAD); 208 for t in tools { 209 s.push('\n'); 210 s.push_str(&tojson(t)); 211 } 212 s.push_str(HERMES_TAIL); 213 s 214 } 215 216 /// Hermes: an assistant turn's content with each call as `\n{"name": "N", "arguments": 217 /// A}\n`, a newline before every call but a first one with empty content. String 218 /// arguments (the OpenAI form) go in verbatim, others through `tojson`, as the template does. 219 pub fn hermes_assistant_with_calls(content: &str, calls: &[Value]) -> String { 220 let mut s = content.to_string(); 221 for (i, call) in calls.iter().enumerate() { 222 if i > 0 || !content.is_empty() { 223 s.push('\n'); 224 } 225 let f = call.get("function").unwrap_or(call); 226 s.push_str("\n{\"name\": \""); 227 s.push_str(f.get("name").and_then(Value::as_str).unwrap_or("")); 228 s.push_str("\", \"arguments\": "); 229 match f.get("arguments") { 230 Some(Value::String(t)) => s.push_str(t), 231 Some(v) => s.push_str(&tojson(v)), 232 None => s.push_str("null"), 233 } 234 s.push_str("}\n"); 235 } 236 s 237 } 238 239 /// A run of consecutive `tool` messages as one user turn's content. 240 pub fn tool_responses(contents: &[String]) -> String { 241 let mut s = String::new(); 242 for (i, c) in contents.iter().enumerate() { 243 if i > 0 { 244 s.push('\n'); 245 } 246 s.push_str("\n"); 247 s.push_str(c); 248 s.push_str("\n"); 249 } 250 s 251 } 252 253 /// Splits a reply into its text before the first `` and the parsed calls 254 /// (OpenAI shape: `{id, type: "function", function: {name, arguments: }}`). 255 pub fn parse_reply(text: &str, id_base: &str) -> (String, Vec) { 256 let Some(first) = text.find(OPEN) else { 257 return (text.to_string(), Vec::new()); 258 }; 259 let content = text[..first].trim_end().to_string(); 260 let mut calls = Vec::new(); 261 let mut rest = &text[first..]; 262 while let Some(p) = rest.find(OPEN) { 263 let body_start = p + OPEN.len(); 264 let (body, next) = match rest[body_start..].find(CLOSE) { 265 Some(e) => ( 266 &rest[body_start..body_start + e], 267 &rest[body_start + e + CLOSE.len()..], 268 ), 269 None => (&rest[body_start..], ""), 270 }; 271 if let Some((name, args)) = parse_call(body) { 272 calls.push(serde_json::json!({ 273 "id": format!("call_{id_base}_{}", calls.len()), 274 "type": "function", 275 "function": {"name": name, "arguments": Value::Object(args).to_string()}, 276 })); 277 } 278 rest = next; 279 } 280 (content, calls) 281 } 282 283 fn parse_call(body: &str) -> Option<(String, Map)> { 284 let b = body.trim(); 285 // XML form: \nV\n ... 286 if let Some(fs) = b.find("") { 292 inner = &inner[..fe]; 293 } 294 let mut args = Map::new(); 295 let mut r = inner; 296 while let Some(ps) = r.find("") { 302 Some(e) => (&v_all[..e], &v_all[e + "".len()..]), 303 None => match v_all.find(" (&v_all[..e], &v_all[e..]), 305 None => (v_all, ""), 306 }, 307 }; 308 let raw = raw.strip_prefix('\n').unwrap_or(raw); 309 let raw = raw.strip_suffix('\n').unwrap_or(raw); 310 args.insert(key, value_of(raw)); 311 r = next; 312 } 313 return Some((name, args)); 314 } 315 // JSON form: {"name": ..., "arguments": {...}} 316 let v: Value = serde_json::from_str(b).ok()?; 317 let name = v.get("name")?.as_str()?.to_string(); 318 let args = match v.get("arguments").or_else(|| v.get("parameters")) { 319 Some(Value::Object(m)) => m.clone(), 320 Some(Value::String(s)) => match serde_json::from_str::(s) { 321 Ok(Value::Object(m)) => m, 322 _ => Map::new(), 323 }, 324 _ => Map::new(), 325 }; 326 Some((name, args)) 327 } 328 329 /// A parameter value: JSON when it parses as a number, bool, null, object or array; else the text. 330 fn value_of(raw: &str) -> Value { 331 let t = raw.trim(); 332 let looks_json = t.starts_with('{') 333 || t.starts_with('[') 334 || t == "true" 335 || t == "false" 336 || t == "null" 337 || t.parse::().is_ok(); 338 if looks_json { 339 if let Ok(v) = serde_json::from_str::(t) { 340 return v; 341 } 342 } 343 Value::String(raw.to_string()) 344 } 345 346 /// Streaming guard: how many bytes at the end of `buf` could be the start of `` 347 /// (held back so a split tag is never streamed as content). 348 pub fn partial_open_len(buf: &str) -> usize { 349 let max = OPEN.len().min(buf.len()); 350 for n in (1..=max).rev() { 351 if buf.is_char_boundary(buf.len() - n) && OPEN.starts_with(&buf[buf.len() - n..]) { 352 return n; 353 } 354 } 355 0 356 } 357 358 #[cfg(test)] 359 mod tests { 360 use super::*; 361 362 #[test] 363 fn parses_xml_call_with_text_before() { 364 let r = "Let me check.\n\n\n\n\n/tmp/a.txt\n\n\n20\n\n\n"; 365 let (c, calls) = parse_reply(r, "x"); 366 assert_eq!(c, "Let me check."); 367 assert_eq!(calls.len(), 1); 368 assert_eq!(calls[0]["function"]["name"], "read_file"); 369 let a: Value = 370 serde_json::from_str(calls[0]["function"]["arguments"].as_str().unwrap()).unwrap(); 371 assert_eq!(a["path"], "/tmp/a.txt"); 372 assert_eq!(a["limit"], 20); 373 } 374 375 #[test] 376 fn parses_two_calls_and_multiline_value() { 377 let r = "\n\n\nline1\nline2\n\n\n\n\n\n\n"; 378 let (c, calls) = parse_reply(r, "x"); 379 assert_eq!(c, ""); 380 assert_eq!(calls.len(), 2); 381 let a: Value = 382 serde_json::from_str(calls[0]["function"]["arguments"].as_str().unwrap()).unwrap(); 383 assert_eq!(a["s"], "line1\nline2"); 384 assert_eq!(calls[1]["function"]["name"], "b"); 385 } 386 387 #[test] 388 fn parses_json_form() { 389 let (_, calls) = parse_reply( 390 "\n{\"name\": \"f\", \"arguments\": {\"x\": 1}}\n", 391 "x", 392 ); 393 assert_eq!(calls[0]["function"]["name"], "f"); 394 } 395 396 #[test] 397 fn plain_reply_has_no_calls() { 398 let (c, calls) = parse_reply("Hello there.", "x"); 399 assert_eq!(c, "Hello there."); 400 assert!(calls.is_empty()); 401 } 402 403 #[test] 404 fn renders_round_trip_layout() { 405 let call = serde_json::json!({"id": "c", "type": "function", "function": {"name": "f", "arguments": "{\"p\": \"v\", \"n\": 2}"}}); 406 let s = assistant_with_calls("", &[call]); 407 // serde_json maps are key-sorted here (no preserve_order): n before p. 408 assert_eq!(s, "\n\n\n2\n\n\nv\n\n\n"); 409 let (_, calls) = parse_reply(&s, "y"); 410 let a: Value = 411 serde_json::from_str(calls[0]["function"]["arguments"].as_str().unwrap()).unwrap(); 412 assert_eq!(a["p"], "v"); 413 assert_eq!(a["n"], 2); 414 } 415 416 #[test] 417 fn tool_responses_fold() { 418 assert_eq!( 419 tool_responses(&["a".into(), "b".into()]), 420 "\na\n\n\nb\n" 421 ); 422 } 423 424 #[test] 425 fn tojson_matches_python_separators() { 426 let v: Value = serde_json::from_str( 427 "{\"type\":\"function\",\"function\":{\"name\":\"f\",\"p\":[1,2]}}", 428 ) 429 .unwrap(); 430 assert_eq!( 431 tojson(&v), 432 "{\"function\": {\"name\": \"f\", \"p\": [1, 2]}, \"type\": \"function\"}" 433 ); 434 } 435 436 #[test] 437 fn partial_open_hold_back() { 438 assert_eq!(partial_open_len("hello /tokenizer_config.json"))["chat_template"]) 461 /// .render(messages=req["messages"], tools=req["tools"], add_generation_prompt=True) 462 /// The request's keys are sorted at every level, so key order is the same in both renderers. 463 const HERMES_EXPECTED: &str = include_str!("tools/hermes_expected.txt"); 464 465 /// The full prompt for the fixture request, through the same fold as `server::prepare` and 466 /// the engine's own ChatML renderer for the 2507 template. 467 fn render_fixture(format: ToolFormat) -> String { 468 let req: Value = serde_json::from_str(HERMES_REQUEST).unwrap(); 469 let msgs = req["messages"] 470 .as_array() 471 .unwrap() 472 .iter() 473 .map(|m| { 474 ( 475 m["role"].as_str().unwrap(), 476 m["content"].as_str().unwrap_or("").to_string(), 477 m.get("tool_calls") 478 .and_then(Value::as_array) 479 .map(Vec::as_slice), 480 ) 481 }) 482 .collect(); 483 let turns = fold_turns(format, req["tools"].as_array().unwrap(), msgs); 484 let refs: Vec<(&str, &str)> = turns 485 .iter() 486 .map(|(r, c)| (r.as_str(), c.as_str())) 487 .collect(); 488 let template = 489 aien_inference_abi::tokenizer::ChatTemplate::detect(QWEN3_2507_TEMPLATE).unwrap(); 490 template.try_render(&refs).unwrap() 491 } 492 493 #[test] 494 fn hermes_render_matches_the_2507_template_byte_for_byte() { 495 assert_eq!(render_fixture(ToolFormat::HermesJson), HERMES_EXPECTED); 496 } 497 498 /// Negative control: the qwen3_coder renderer does not produce the Hermes prompt. 499 #[test] 500 fn xml_render_does_not_match_the_hermes_expected() { 501 let xml = render_fixture(ToolFormat::Qwen3CoderXml); 502 assert_ne!(xml, HERMES_EXPECTED); 503 assert!(xml.contains("\n\n/tmp/a.txt\n")); 504 } 505 506 #[test] 507 fn detects_format_from_template_text() { 508 assert_eq!( 509 ToolFormat::detect(QWEN3_2507_TEMPLATE), 510 ToolFormat::HermesJson 511 ); 512 assert_eq!( 513 ToolFormat::detect(QWEN36_TEMPLATE), 514 ToolFormat::Qwen3CoderXml 515 ); 516 assert_eq!( 517 ToolFormat::detect(QWEN38_TEMPLATE), 518 ToolFormat::Qwen3CoderXml 519 ); 520 } 521 522 #[test] 523 fn detects_format_from_model_dir() { 524 let dir = std::env::temp_dir().join(format!("aien-tools-fmt-{}", std::process::id())); 525 let _ = std::fs::remove_dir_all(&dir); 526 std::fs::create_dir_all(&dir).unwrap(); 527 assert_eq!( 528 ToolFormat::from_model_dir(&dir).unwrap(), 529 ToolFormat::Qwen3CoderXml 530 ); 531 std::fs::write(dir.join("chat_template.jinja"), QWEN3_2507_TEMPLATE).unwrap(); 532 assert_eq!( 533 ToolFormat::from_model_dir(&dir).unwrap(), 534 ToolFormat::HermesJson 535 ); 536 // tokenizer_config.json's template wins, as in ChatTokenizer::from_model_dir. 537 let cfg = serde_json::json!({"chat_template": QWEN36_TEMPLATE}); 538 std::fs::write(dir.join("tokenizer_config.json"), cfg.to_string()).unwrap(); 539 assert_eq!( 540 ToolFormat::from_model_dir(&dir).unwrap(), 541 ToolFormat::Qwen3CoderXml 542 ); 543 std::fs::remove_dir_all(&dir).unwrap(); 544 } 545 546 #[test] 547 fn hermes_reply_parses_back() { 548 let s = hermes_assistant_with_calls( 549 "", 550 &[serde_json::json!({"function": {"name": "f", "arguments": {"x": 1}}})], 551 ); 552 assert_eq!( 553 s, 554 "\n{\"name\": \"f\", \"arguments\": {\"x\": 1}}\n" 555 ); 556 let (c, calls) = parse_reply(&s, "h"); 557 assert_eq!(c, ""); 558 assert_eq!(calls[0]["function"]["name"], "f"); 559 assert_eq!(calls[0]["function"]["arguments"], "{\"x\":1}"); 560 } 561 }