A high-performance inference engine for AI models
chat: keep tool-call parameter text verbatim, type it by the schema (#850)
ry2009ff5b25e5a025
diff --git a/crates/legacy/cli/src/server/chat_completions.rs b/crates/legacy/cli/src/server/chat_completions.rsindex a0a17529d..fcc03c5ca 100644--- a/crates/legacy/cli/src/server/chat_completions.rs+++ b/crates/legacy/cli/src/server/chat_completions.rs@@ -32,8 +32,8 @@ use crate::{ServerState,chat_tool_calls::{OaiTool, OaiToolCall, ToolCallStreamer, ToolParameterTypes, backfill_tool_result_names, choose_tools,- coerce_tool_call, insert_tools_message, oai_tool_call, parse_scalar_text, reply_tool_calls, to_tool_call,- tool_call_result_block, withhold_stream_text,+ coerce_tool_call, insert_tools_message, oai_tool_call, parse_parameter_text, reply_tool_calls,+ to_tool_call, tool_call_result_block, withhold_stream_text,},request_info::RequestInfo,request_log::RequestLog,@@ -638,9 +638,10 @@ fn chunk_json(serde_json::to_string(&chunk).unwrap_or_default()}-/// Schema coercion retypes scalar arguments on the wire, so a client may echo-/// `5` where the session stored `"5"` (or a JSON string where the session-/// stored the value it spells); such pairs must still count as the same prefix.+/// Schema coercion retypes arguments on the wire, so a client may echo `5` or+/// `[1,2]` where the session stored the text `"5"` or `"[1, 2]"` (or a JSON+/// string where the session stored the value it spells); such pairs must still+/// count as the same prefix.fn tool_call_arguments_equivalent(stored: &str,echoed: &str,@@ -667,7 +668,7 @@ fn json_values_equivalent(.all(|(key, value)| right.get(key).is_some_and(|other| json_values_equivalent(value, other)))},(Value::String(text), other) | (other, Value::String(text)) if !other.is_string() => {- parse_scalar_text(text).is_some_and(|parsed| parsed == *other)+ parse_parameter_text(text).is_some_and(|parsed| parsed == *other)},(left, right) => left == right,}@@ -1208,8 +1209,8 @@ pub async fn handle_chat_completions(},};- // The parser cannot type scalar arguments; the declared schemas restore- // the types when replies cross back into the OpenAI wire format.+ // The parser keeps every argument the text the model wrote; the declared+ // schemas restore the types when replies cross back into the OpenAI wire format.let parameter_types = ToolParameterTypes::from_tools(request.tools.as_deref());let id = request_info.id.as_str().to_owned();diff --git a/crates/legacy/cli/src/server/chat_tool_calls.rs b/crates/legacy/cli/src/server/chat_tool_calls.rsindex 8467cded6..49fb765ce 100644--- a/crates/legacy/cli/src/server/chat_tool_calls.rs+++ b/crates/legacy/cli/src/server/chat_tool_calls.rs@@ -1,4 +1,4 @@-use std::collections::HashMap;+use std::collections::{HashMap, HashSet};use serde::{Deserialize, Serialize};use uuid::Uuid;@@ -93,9 +93,9 @@ pub fn choose_tools<'t>(}/// Declared JSON-Schema types of each tool parameter, keyed by function name.-/// Tool-call markup cannot carry scalar types — the parser keeps every scalar-/// parameter a string and types JSON-shaped values by their braces — so the-/// declared schema is what restores the wire types clients validate against.+/// Tool-call markup cannot carry types — the parser keeps every parameter the+/// text the model wrote — so the declared schema is what restores the wire+/// types clients validate against.#[derive(Clone, Default)]pub struct ToolParameterTypes(HashMap<String, HashMap<String, Vec<String>>>);@@ -115,13 +115,7 @@ impl ToolParameterTypes {let parameters = properties.iter().filter_map(|(name, property)| {- let types = match property.get("type")? {- serde_json::Value::String(kind) => vec![kind.clone()],- serde_json::Value::Array(kinds) => {- kinds.iter().filter_map(|kind| kind.as_str().map(str::to_string)).collect()- },- _ => return None,- };+ let types = declared_types(property, &schema, 8);(!types.is_empty()).then(|| (name.clone(), types))}).collect();@@ -139,6 +133,72 @@ impl ToolParameterTypes {}}+// Per parameter: count each queued schema and each entry in a type array.+const MAX_SCHEMA_TRAVERSAL_WORK: usize = 1024;++/// The JSON-Schema types a property schema declares: its `type` keyword, or the+/// union of its `anyOf`/`oneOf` branches, following local `$ref`s (the shape+/// pydantic and schemars clients emit for optional and nested objects).+fn declared_types(+ property: &serde_json::Value,+ root: &serde_json::Value,+ depth: u32,+) -> Vec<String> {+ let mut pending = vec![(property, depth)];+ let mut visited = HashMap::new();+ let mut types = HashSet::new();+ let mut remaining_work = MAX_SCHEMA_TRAVERSAL_WORK - 1;+ while let Some((property, depth)) = pending.pop() {+ if depth == 0 {+ continue;+ }+ let property = match property.get("$ref").and_then(serde_json::Value::as_str) {+ Some(reference) => {+ reference.strip_prefix('#').and_then(|pointer| root.pointer(pointer)).unwrap_or(property)+ },+ None => property,+ };+ // Track identity without hashing the schema's contents. Revisit a shared+ // node only when a shorter path leaves more depth to discover its types.+ let identity = std::ptr::from_ref(property);+ if visited.get(&identity).is_some_and(|seen_depth| *seen_depth >= depth) {+ continue;+ }+ visited.insert(identity, depth);+ match property.get("type") {+ Some(serde_json::Value::String(kind)) => {+ types.insert(kind.as_str());+ },+ Some(serde_json::Value::Array(kinds)) => {+ let Some(remaining) = remaining_work.checked_sub(kinds.len()) else {+ return Vec::new();+ };+ remaining_work = remaining;+ types.extend(kinds.iter().filter_map(serde_json::Value::as_str));+ },+ _ if depth > 1 => {+ for branches in+ ["anyOf", "oneOf"].iter().filter_map(|key| property.get(*key).and_then(serde_json::Value::as_array))+ {+ // Charge work before enqueueing, bounding both visits and+ // pending allocations even for a wide, nonrecursive union.+ let Some(remaining) = remaining_work.checked_sub(branches.len()) else {+ // Partial types may omit a string branch and cause an+ // incorrect coercion, so leave the parameter unchanged.+ return Vec::new();+ };+ remaining_work = remaining;+ pending.extend(branches.iter().map(|branch| (branch, depth - 1)));+ }+ },+ _ => {},+ }+ }+ let mut types: Vec<String> = types.into_iter().map(str::to_string).collect();+ types.sort_unstable();+ types+}+fn matches_declared_type(value: &serde_json::Value,declared: &[String],@@ -155,10 +215,12 @@ fn matches_declared_type(})}-/// Bare scalar text is strict JSON, plus the Python-style booleans some models-/// emit in tool markup (qwen3.5 writes `True`/`False`).-pub fn parse_scalar_text(text: &str) -> Option<serde_json::Value> {- if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(text) {+/// Parameter text read as JSON: strict first, then with the bounded repair of+/// control characters and bare quotes models leave inside string values, plus+/// the Python-style booleans some models emit in tool markup (qwen3.5 writes+/// `True`/`False`).+pub fn parse_parameter_text(text: &str) -> Option<serde_json::Value> {+ if let Some(parsed) = parse_lenient_json(text) {return Some(parsed);}match text.trim() {@@ -174,23 +236,23 @@ fn coerce_parameter_value() -> Option<serde_json::Value> {let declares_string = declared.iter().any(|kind| kind == "string");match value {- // The parser kept the bare markup text as a string; restore the- // declared type when the text reads as it. A union that includes- // "string" stays a string: the text is already schema-valid and the- // intended type is unknowable.+ // The parser kept the markup text as a string; restore the declared+ // type when the text reads as it. A union that includes "string" stays+ // a string: the text is already schema-valid and the intended type is+ // unknowable.serde_json::Value::String(text) if !declares_string => {- let parsed = parse_scalar_text(text)?;+ let parsed = parse_parameter_text(text)?;matches_declared_type(&parsed, declared).then_some(parsed)},- // JSON-shaped markup text was typed by its braces although the- // parameter is a plain string.+ // A JSON-format parser typed a value although the parameter is a+ // plain string.value if declared == ["string"] && !value.is_string() => Some(serde_json::Value::String(value.to_string())),_ => None,}}-/// Restores the declared scalar types the markup could not carry. Applied only-/// at the OpenAI boundary: the session keeps the parser's values so its stored+/// Restores the declared types the markup could not carry. Applied only at+/// the OpenAI boundary: the session keeps the parser's values so its stored/// history stays consistent with what the template renders.pub fn coerce_tool_call(tool_call: &ToolCall,@@ -400,31 +462,14 @@ fn parse_framed_call(raw: &str) -> FramedCall {}}-// Mirrors the parser's synthesis rule composed with the schema coercion the-// final call goes through: values starting with `{` or `[` are typed JSON-// unless the parameter is declared a plain string, bare scalars take a-// declared non-string type when they parse as it, everything else is a string.+// A completed parameter serializes exactly as coerce_tool_call serializes it in+// the final call, so the streamed prefix is a prefix of the final text.fn serialize_param_value(value: &str,declared: Option<&[String]>,) -> String {- let trimmed = value.trim_start();- let json_shaped = trimmed.starts_with('{') || trimmed.starts_with('[');- if json_shaped && let Some(parsed) = parse_lenient_json(value) {- if declared.is_some_and(|declared| declared == ["string"]) {- return serde_json::Value::String(parsed.to_string()).to_string();- }- return parsed.to_string();- }- if !json_shaped- && let Some(declared) = declared- && !declared.iter().any(|kind| kind == "string")- && let Some(parsed) = parse_scalar_text(value)- && matches_declared_type(&parsed, declared)- {- return parsed.to_string();- }- serde_json::Value::String(value.to_string()).to_string()+ let text = serde_json::Value::String(value.to_string());+ declared.and_then(|declared| coerce_parameter_value(&text, declared)).unwrap_or(text).to_string()}// The longest suffix of `content` that could be the start of the parameter close tag is@@ -456,18 +501,13 @@ fn open_arguments_text(let serialized = match param {FramedParam::Complete(value) => serialize_param_value(value, declared),FramedParam::Open(content) => {- // an empty value has no known type yet, and typed values (JSON- // starting with `{`/`[`, or declared non-string so the final- // form is a bare literal) can only be serialized once- // complete: either way nothing about the parameter may be emitted+ // an empty value has nothing to emit yet, and a declared non-string+ // value takes its final form (a bare literal) only once complete:+ // either way nothing about the parameter may be emittedlet streamable = withhold_ambiguous_tail(content);let declared_non_string =declared.is_some_and(|declared| !declared.iter().any(|kind| kind == "string"));- if streamable.is_empty()- || streamable.starts_with('{')- || streamable.starts_with('[')- || declared_non_string- {+ if streamable.is_empty() || declared_non_string {break;}let quoted = serde_json::Value::String(streamable.to_string()).to_string();diff --git a/crates/legacy/cli/unit/server/chat_completions_test.rs b/crates/legacy/cli/unit/server/chat_completions_test.rsindex 3ea76baa9..7006185a1 100644--- a/crates/legacy/cli/unit/server/chat_completions_test.rs+++ b/crates/legacy/cli/unit/server/chat_completions_test.rs@@ -467,6 +467,13 @@ fn prefix_match_treats_coerced_arguments_as_equal() {let stored_python = vec![assistant_call(r#"{"metric":"True"}"#)];let echoed_boolean = vec![assistant_call(r#"{"metric":true}"#), ChatMessage::user().with_text("more".to_string())];assert!(messages_have_prefix(&echoed_boolean, &stored_python));++ // the session stores a declared array as the text the model wrote; the+ // client echoes the typed array it received+ let stored_text = vec![assistant_call(r#"{"edits":"[{\"a\": 1}, 2]"}"#)];+ let echoed_array =+ vec![assistant_call(r#"{"edits":[{"a":1},2]}"#), ChatMessage::user().with_text("more".to_string())];+ assert!(messages_have_prefix(&echoed_array, &stored_text));}#[test]diff --git a/crates/legacy/cli/unit/server/chat_tool_calls_test.rs b/crates/legacy/cli/unit/server/chat_tool_calls_test.rsindex f6589cf15..3fafcc13b 100644--- a/crates/legacy/cli/unit/server/chat_tool_calls_test.rs+++ b/crates/legacy/cli/unit/server/chat_tool_calls_test.rs@@ -275,15 +275,17 @@ fn framed_tool_call_streams_arguments_incrementally() {#[test]fn framed_tool_call_withholds_typed_parameter_until_complete() {+ // a declared object parameter is typed from its text, so nothing of it can stream until it is complete+ let types = parameter_types(+ r#"[{"type":"function","function":{"name":"read","description":"Read",+ "parameters":{"type":"object","properties":{"options":{"type":"object"}}}}}]"#,+ );let mut streamer = ToolCallStreamer::new();- let deltas = streamer.update(0, "\n<function=read>\n<parameter=options>\n{\"a\"", &ToolParameterTypes::default());+ let deltas = streamer.update(0, "\n<function=read>\n<parameter=options>\n{\"a\"", &types);assert!(deltas.iter().all(|delta| delta.function.arguments.is_empty()));- let deltas = streamer.update(- 0,- "\n<function=read>\n<parameter=options>\n{\"a\": 1}\n</parameter>\n</function>\n",- &ToolParameterTypes::default(),- );+ let deltas =+ streamer.update(0, "\n<function=read>\n<parameter=options>\n{\"a\": 1}\n</parameter>\n</function>\n", &types);let fragment: String = deltas.iter().map(|delta| delta.function.arguments.as_str()).collect();assert_eq!(fragment, r#"{"options":{"a":1}"#);@@ -346,8 +348,12 @@ fn framed_tool_call_uses_valid_candidate_when_final_call_diverges() {#[test]fn framed_tool_call_with_array_parameter_assembles_exactly() {- // the edit-call shape: a parameter whose value is a JSON array must never be- // string-streamed before its type is known, and the finish must not double it+ // the edit-call shape: a parameter declared as an array must never be+ // string-streamed before its text is complete, and the finish must not double it+ let types = parameter_types(+ r#"[{"type":"function","function":{"name":"edit","description":"Edit",+ "parameters":{"type":"object","properties":{"path":{"type":"string"},"edits":{"type":"array"}}}}}]"#,+ );let final_markup = "\n<function=edit>\n<parameter=path>\nlonodn.md\n</parameter>\n<parameter=edits>\n[{\"oldText\": \"London\", \"newText\": \"Londinium\"}]\n</parameter>\n</function>\n";let final_arguments = serde_json::json!({"path": "lonodn.md",@@ -367,7 +373,7 @@ fn framed_tool_call_with_array_parameter_assembles_exactly() {let chars = final_markup.chars().collect::<Vec<_>>();for i in 0..=chars.len() {let partial: String = chars[..i].iter().collect();- for delta in streamer.update(0, &partial, &ToolParameterTypes::default()) {+ for delta in streamer.update(0, &partial, &types) {fragment_count += 1;fragments.push_str(&delta.function.arguments);}@@ -379,6 +385,155 @@ fn framed_tool_call_with_array_parameter_assembles_exactly() {assert_eq!(parsed, final_arguments);}+#[test]+fn framed_string_parameter_streams_json_shaped_text_verbatim() {+ // a write call whose content is a JSON document and whose edits are a declared array: the string+ // parameter must stream the text the model wrote, not a re-serialization of it, and the streamed+ // fragments must be the exact prefix of the coerced final call so the finish only closes them+ let types = parameter_types(+ r#"[{"type":"function","function":{"name":"write_file","description":"Write",+ "parameters":{"type":"object","properties":{"path":{"type":"string"},"content":{"type":"string"},"edits":{"type":"array"}},+ "required":["path","content"]}}}]"#,+ );+ let content = "{\n \"name\": \"arcade\",\n \"private\": true\n}";+ let edits = "[{\"oldText\": \"London\", \"newText\": \"Londinium\"}]";+ let final_markup = format!(+ "\n<function=write_file>\n<parameter=path>\npackage.json\n</parameter>\n<parameter=content>\n{content}\n</parameter>\n<parameter=edits>\n{edits}\n</parameter>\n</function>\n"+ );+ // the session keeps the parser's text; the server coerces by the schema before finishing the stream+ let session_call = ToolCall {+ identifier: Some("c1".to_string()),+ name: "write_file".to_string(),+ arguments: Value {+ json: serde_json::json!({"path": "package.json", "content": content, "edits": edits}).to_string(),+ },+ };+ let call = coerce_tool_call(&session_call, &types);++ let mut streamer = ToolCallStreamer::new();+ let mut streamed = String::new();+ let mut content_fragments = 0;+ let chars = final_markup.chars().collect::<Vec<_>>();+ for i in 0..=chars.len() {+ let partial: String = chars[..i].iter().collect();+ for delta in streamer.update(0, &partial, &types) {+ if streamed.contains("\"content\":") && !delta.function.arguments.is_empty() {+ content_fragments += 1;+ }+ streamed.push_str(&delta.function.arguments);+ }+ }+ let closing = streamer.finish(0, &call).function.arguments;++ // the coerced final call, not a hand-written literal: a stream that disagreed with it would fall back+ // to the streamer's own candidate and still close with "}", so equality with the call is the check+ let final_arguments: serde_json::Value = serde_json::from_str(&call.arguments.json).expect("final arguments parse");+ let assembled: serde_json::Value =+ serde_json::from_str(&format!("{streamed}{closing}")).expect("assembled arguments parse");+ assert_eq!(assembled, final_arguments);+ assert_eq!(final_arguments["content"], serde_json::json!(content));+ assert!(final_arguments["edits"].is_array());+ assert_eq!(closing, "}", "finish should only close the streamed text");+ assert!(+ content_fragments > 3,+ "a string document must stream before its close tag, got {content_fragments} fragments"+ );+}++#[test]+fn declared_types_follow_refs_and_unions() {+ // pydantic and schemars clients declare nested and optional containers through $ref and anyOf+ let types = parameter_types(+ r##"[{"type":"function","function":{"name":"edit","description":"Edit",+ "parameters":{"type":"object","properties":{+ "edits":{"$ref":"#/$defs/Edits"},+ "options":{"anyOf":[{"$ref":"#/$defs/Options"},{"type":"null"}]},+ "shape":{"oneOf":[{"type":"object"},{"type":"string"}]}+ },"$defs":{"Edits":{"type":"array"},"Options":{"type":"object"}}}}}]"##,+ );+ let call = ToolCall {+ identifier: None,+ name: "edit".to_string(),+ arguments: Value {+ json: serde_json::json!({"edits": "[{\"a\": 1}]", "options": "{\"dry_run\": true}", "shape": "{\"r\": 1}"})+ .to_string(),+ },+ };++ let coerced: serde_json::Value =+ serde_json::from_str(&coerce_tool_call(&call, &types).arguments.json).expect("coerced arguments parse");+ assert_eq!(coerced["edits"], serde_json::json!([{"a": 1}]));+ assert_eq!(coerced["options"], serde_json::json!({"dry_run": true}));+ // a union that includes "string" keeps the text+ assert_eq!(coerced["shape"], serde_json::json!("{\"r\": 1}"));+}++#[test]+fn declared_types_stop_recursive_union_expansion() {+ for keyword in ["anyOf", "oneOf"] {+ let mut branches = vec![serde_json::json!({"type": "object"})];+ branches.extend(std::iter::repeat_n(serde_json::json!({"$ref": "#"}), 32));+ let schema = serde_json::json!({keyword: branches});++ assert_eq!(declared_types(&schema, &schema, 8), ["object"]);+ }+}++#[test]+fn declared_types_reuse_shared_union_nodes() {+ let mut definitions = serde_json::Map::new();+ definitions.insert("0".to_string(), serde_json::json!({"type": ["object", "object", "null"]}));+ for level in 1..=6 {+ let branches = vec![serde_json::json!({"$ref": format!("#/$defs/{}", level - 1)}); 32];+ definitions.insert(level.to_string(), serde_json::json!({"anyOf": branches}));+ }+ let schema = serde_json::json!({"$ref": "#/$defs/6", "$defs": definitions});++ assert_eq!(declared_types(&schema, &schema, 8), ["null", "object"]);+}++#[test]+fn declared_types_revisit_shared_nodes_with_more_depth() {+ let mut nested = serde_json::json!({"$ref": "#/$defs/Shared"});+ for _ in 0..6 {+ nested = serde_json::json!({"anyOf": [nested]});+ }+ let schema = serde_json::json!({+ "$defs": {"Shared": {"anyOf": [{"type": "string"}]}},+ "anyOf": [{"type": "object"}, {"$ref": "#/$defs/Shared"}, nested]+ });++ assert_eq!(declared_types(&schema, &schema, 8), ["object", "string"]);+}++#[test]+fn declared_types_discard_partial_results_when_work_is_exhausted() {+ let leaves = vec![serde_json::json!({"type": "object"}); 32];+ let mut branches = vec![serde_json::json!({"type": "string"})];+ branches.extend(std::iter::repeat_n(serde_json::json!({"anyOf": leaves}), 32));+ let mut kinds = vec!["object"; MAX_SCHEMA_TRAVERSAL_WORK];+ kinds.push("string");++ for property in [serde_json::json!({"anyOf": branches}), serde_json::json!({"type": kinds})] {+ let tools = serde_json::json!([{"function": {+ "name": "read",+ "parameters": {"properties": {"options": property}}+ }}]);+ let types = parameter_types(&tools.to_string());+ assert!(types.declared("read", "options").is_none());++ let call = ToolCall {+ identifier: None,+ name: "read".to_string(),+ arguments: Value {+ json: serde_json::json!({"options": "{\"a\": 1}"}).to_string(),+ },+ };+ assert_eq!(coerce_tool_call(&call, &types).arguments.json, call.arguments.json);+ assert_eq!(serialize_param_value("{\"a\": 1}", types.declared("read", "options")), r#""{\"a\": 1}""#);+ }+}+fn parameter_types(tools_json: &str) -> ToolParameterTypes {let tools: Vec<OaiTool> = serde_json::from_str(tools_json).expect("valid tools json");ToolParameterTypes::from_tools(Some(&tools))@@ -486,7 +641,7 @@ fn declared_string_keeps_json_shaped_text() {"parameters":{"type":"object","properties":{"path":{"type":"string"},"content":{"type":"string"}},"required":["path","content"]}}}]"#,);- // the parser typed the JSON-shaped content by its braces+ // a JSON-format parser typed the content although the parameter is a stringlet call = ToolCall {identifier: None,name: "write_file".to_string(),diff --git a/crates/legacy/hanashi/configs/parsing/qwen3.5.json b/crates/legacy/hanashi/configs/parsing/qwen3.5.jsonindex d551de45f..c51b3d700 100644--- a/crates/legacy/hanashi/configs/parsing/qwen3.5.json+++ b/crates/legacy/hanashi/configs/parsing/qwen3.5.json@@ -71,8 +71,7 @@"arguments": [{"type": "regex_capture_object",- "pattern": "<parameter=(\\w+)>\\n([\\s\\S]*?)\\n</parameter>",- "parse_json_values": true+ "pattern": "<parameter=(\\w+)>\\n([\\s\\S]*?)\\n</parameter>"}]}diff --git a/crates/legacy/hanashi/configs/parsing/qwen3.6.json b/crates/legacy/hanashi/configs/parsing/qwen3.6.jsonindex d551de45f..c51b3d700 100644--- a/crates/legacy/hanashi/configs/parsing/qwen3.6.json+++ b/crates/legacy/hanashi/configs/parsing/qwen3.6.json@@ -71,8 +71,7 @@"arguments": [{"type": "regex_capture_object",- "pattern": "<parameter=(\\w+)>\\n([\\s\\S]*?)\\n</parameter>",- "parse_json_values": true+ "pattern": "<parameter=(\\w+)>\\n([\\s\\S]*?)\\n</parameter>"}]}diff --git a/crates/legacy/hanashi/tests/test_continuation.rs b/crates/legacy/hanashi/tests/test_continuation.rsindex a1fbf611b..ebc5cbc9a 100644--- a/crates/legacy/hanashi/tests/test_continuation.rs+++ b/crates/legacy/hanashi/tests/test_continuation.rs@@ -87,6 +87,7 @@ fn history() -> Vec<ChatMessage> {fn add_tool_result(encoding: &HanashiEncodingImpl,history: &mut Vec<ChatMessage>,+ options: &str,) {let mut assistant = encoding.state().messages.last().unwrap().clone();let ChatContentBlock::ToolCall {@@ -97,7 +98,7 @@ fn add_tool_result(};assert_eq!(serde_json::from_str::<serde_json::Value>(&value.arguments.json).unwrap(),- serde_json::json!({"options": {"a": 1, "b": 2}})+ serde_json::json!({"options": options}));// Nagare assigns an ID after parsing; it is absent from the sampled encoding.value.identifier = Some(format!("call-{}", history.len()));@@ -118,14 +119,16 @@ fn formatting_and_sampled_token_ids_survive_repeated_tool_continuations() {let mut history = history();encoding.encode(history.clone()).unwrap();for _ in 0..3 {- decode(&mut encoding, &(tool_call(options) + "<|im_end|>"));+ // Parameter text is preserved verbatim; extra message whitespace+ // still makes the sampled prefix differ from canonical rendering.+ decode(&mut encoding, &(tool_call(options) + " <|im_end|>"));let sampled = encoding.state().tokens.clone();let sampled_text = encoding.state().text();assert_ne!(sampled.iter().map(|token| token.id).collect::<Vec<_>>(),encoding.tokenize(&sampled_text).unwrap());- add_tool_result(&encoding, &mut history);+ add_tool_result(&encoding, &mut history, options);let canonical = canonical_text(config.clone(), history.clone());assert!(!canonical.starts_with(&sampled_text));@@ -151,8 +154,9 @@ fn edited_history_and_render_context_are_rejected_without_mutation() {let mut encoding = encoding(HanashiConfig::Qwen38);let mut history = history();encoding.encode(history.clone()).unwrap();- decode(&mut encoding, &(tool_call(r#"{"a":1, "b": 2}"#) + "<|im_end|>"));- add_tool_result(&encoding, &mut history);+ let options = r#"{"a":1, "b": 2}"#;+ decode(&mut encoding, &(tool_call(options) + "<|im_end|>"));+ add_tool_result(&encoding, &mut history, options);let original = encoding.state().clone();let mut edited = history.clone();edited[2] = ChatMessage::user().with_text("Different request.".to_string());@@ -247,8 +251,9 @@ fn reasoning_mode_change_that_only_affects_suffix_can_reuse_prefix() {let mut encoding = encoding(HanashiConfig::Qwen35);let mut history = history();encoding.encode(history.clone()).unwrap();- decode(&mut encoding, &(tool_call(r#"{"a":1, "b": 2}"#) + "<|im_end|>"));- add_tool_result(&encoding, &mut history);+ let options = r#"{"a":1, "b": 2}"#;+ decode(&mut encoding, &(tool_call(options) + "<|im_end|>"));+ add_tool_result(&encoding, &mut history, options);history[0] = ChatMessage::system().with_reasoning_effort(ReasoningEffort::Default);let sampled = encoding.state().tokens.clone();assert!(encoding.try_append(&history).unwrap().is_some());@@ -262,8 +267,9 @@ fn unicode_survives_prefix_boundary_detection() {let mut history = history();history[2] = ChatMessage::user().with_text("Проверь репозиторий 🦀".to_string());encoding.encode(history.clone()).unwrap();- decode(&mut encoding, &(tool_call(r#"{"a":1, "b": 2}"#) + "<|im_end|>"));- add_tool_result(&encoding, &mut history);+ let options = r#"{"a":1, "b": 2}"#;+ decode(&mut encoding, &(tool_call(options) + "<|im_end|>"));+ add_tool_result(&encoding, &mut history, options);let sampled = encoding.state().tokens.clone();assert!(encoding.try_append(&history).unwrap().is_some());assert_eq!(&encoding.state().tokens[..sampled.len()], sampled);diff --git a/crates/legacy/nagare/src/tool/func_def.rs b/crates/legacy/nagare/src/tool/func_def.rsindex 93f87f694..ac6cd553b 100644--- a/crates/legacy/nagare/src/tool/func_def.rs+++ b/crates/legacy/nagare/src/tool/func_def.rs@@ -1,6 +1,7 @@use std::{error::Error, future::Future, sync::Arc};pub use shoji::types::basic::Value;+use shoji::types::basic::parse_lenient_json;pub type ErrorFuture = Box<dyn Error + Send + Sync>;pub type FunctionFuture = dyn Fn(Value) -> Box<dyn Future<Output = Result<Value, ErrorFuture>> + Send> + Send + Sync;@@ -39,9 +40,10 @@ impl ToolDescriptor {Box::into_pin((self.func)(args)).await}- // Small models often mistype scalar tool arguments (e.g. Llama 3.2 1B passes "37" for a number parameter);- // coerce argument values to their schema-declared scalar types instead of failing the call — an error result- // makes such models retry the same call indefinitely.+ // Markup parsers keep every argument the text the model wrote, and small models mistype scalars even in JSON+ // markup (e.g. Llama 3.2 1B passes "37" for a number parameter); coerce argument values to their+ // schema-declared types instead of failing the call — an error result makes such models retry the same call+ // indefinitely.fn coerce_arguments(&self,args: Value,@@ -112,6 +114,24 @@ fn coerce_to_schema_with_root({return coerce_to_schema_with_root(value, non_null_schema, root_schema);}+ // A union of shapes: container text goes to the first branch it parses as. Unlike the OpenAI boundary, which+ // keeps the text when the union admits a string, a tool implementation deserializes what it declared, so the+ // container branch wins here.+ if let Json::String(text) = &value+ && let Some(branches) = schema.get("anyOf").or_else(|| schema.get("oneOf")).and_then(Json::as_array)+ {+ for branch in branches {+ let branch = resolve_local_schema(branch, root_schema);+ let parses = match branch.get("type").and_then(Json::as_str) {+ Some("object") => parse_lenient_json(text).is_some_and(|parsed| parsed.is_object()),+ Some("array") => parse_lenient_json(text).is_some_and(|parsed| parsed.is_array()),+ _ => false,+ };+ if parses {+ return coerce_to_schema_with_root(value, branch, root_schema);+ }+ }+ }let schema_type = match schema.get("type") {Some(Json::String(schema_type)) => Some(schema_type.as_str()),@@ -124,6 +144,17 @@ fn coerce_to_schema_with_root(_ => None,};+ // an object or array parameter arrives as text from the markup parsers; read it when it parses as that shape+ let value = match (schema_type, value) {+ (Some("object"), Json::String(text)) => {+ parse_lenient_json(&text).filter(Json::is_object).unwrap_or(Json::String(text))+ },+ (Some("array"), Json::String(text)) => {+ parse_lenient_json(&text).filter(Json::is_array).unwrap_or(Json::String(text))+ },+ (_, value) => value,+ };+match schema_type {Some("object") => match value {Json::Object(map) => Json::Object(@@ -210,3 +241,52 @@ fn resolve_local_schema<'a>(}schema}++#[cfg(test)]+mod tests {+ use super::coerce_to_schema;++ #[test]+ fn coerce_to_schema_parses_container_text_and_keeps_string_text() {+ let schema = serde_json::json!({+ "type": "object",+ "properties": {+ "content": {"type": "string"},+ "options": {"type": "object", "properties": {"retries": {"type": "integer"}}},+ "tags": {"type": ["array", "null"], "items": {"type": "integer"}}+ }+ });+ // markup parsers keep every parameter as text; containers are parsed by the schema, strings never are+ let coerced = coerce_to_schema(+ serde_json::json!({+ "content": "{\"name\": \"arcade\"}",+ "options": "{\"retries\": \"3\"}",+ "tags": "[\"1\", 2]"+ }),+ &schema,+ );+ assert_eq!(+ coerced,+ serde_json::json!({"content": "{\"name\": \"arcade\"}", "options": {"retries": 3}, "tags": [1, 2]})+ );++ let kept = coerce_to_schema(serde_json::json!({"options": "{ broken", "tags": "not a list"}), &schema);+ assert_eq!(kept, serde_json::json!({"options": "{ broken", "tags": "not a list"}));+ }++ #[test]+ fn coerce_to_schema_reads_container_text_through_refs_and_unions() {+ // the shapes schemars emits for Option<Box<T>> and for a data enum+ let schema = serde_json::json!({+ "type": "object",+ "properties": {+ "child": {"anyOf": [{"$ref": "#/$defs/Child"}, {"type": "null"}]},+ "shape": {"oneOf": [{"type": "object", "properties": {"r": {"type": "number"}}}, {"type": "string"}]}+ },+ "$defs": {"Child": {"type": "object", "properties": {"n": {"type": "integer"}}}}+ });+ let coerced =+ coerce_to_schema(serde_json::json!({"child": "{\"n\": \"2\"}", "shape": "{\"r\": \"1.5\"}"}), &schema);+ assert_eq!(coerced, serde_json::json!({"child": {"n": 2}, "shape": {"r": 1.5}}));+ }+}diff --git a/crates/legacy/token-stream-parser/tests/test_token_stream_parser_qwen3_5.rs b/crates/legacy/token-stream-parser/tests/test_token_stream_parser_qwen3_5.rsindex 3527777b8..88d1d1d8b 100644--- a/crates/legacy/token-stream-parser/tests/test_token_stream_parser_qwen3_5.rs+++ b/crates/legacy/token-stream-parser/tests/test_token_stream_parser_qwen3_5.rs@@ -72,3 +72,35 @@ fn test_token_stream_parser_qwen35_preserves_ambiguous_string_arguments() {},);}++#[test]+fn test_token_stream_parser_qwen35_keeps_object_parameter_text_verbatim() {+ // a parameter's text is delivered as written, spacing included; the schema types it at the boundary+ let suite = qwen35_suite();+ let data = TestData {+ prompt: "<|im_start|>user\nWeather?<|im_end|>\n<|im_start|>assistant\n".into(),+ completion: "<tool_call>\n<function=get_weather>\n<parameter=location>\n{\"city\": \"London\", \"country\": \"United Kingdom\"}\n</parameter>\n<parameter=notes>\n[Home](/) and [Games](/games) are the two pages.\n</parameter>\n</function>\n</tool_call><|im_end|>".into(),+ };++ run_parser_test(+ &suite,+ &data,+ &TestExpectations {+ framing: None,+ reduction: None,+ extraction: suite.expect_extraction(json!([+ {"role": "user", "content": [{"type": "$text", "value": "\nWeather?"}]},+ {"role": "assistant", "content": [+ {"type": "$text", "value": "\n"},+ {"type": "tool_call", "value": {+ "name": "get_weather",+ "arguments": {+ "location": "{\"city\": \"London\", \"country\": \"United Kingdom\"}",+ "notes": "[Home](/) and [Games](/games) are the two pages."+ }+ }}+ ]}+ ])),+ },+ );+}