diff --git a/docs/api.md b/docs/api.md index 2942b388e..fd46b4083 100644 --- a/docs/api.md +++ b/docs/api.md @@ -618,6 +618,11 @@ JSON string literals remain part of the body. Strict function tool schemas `response_format` JSON schemas remain supported. DeepSeek DSML and XTML are parsed by their own parsers rather than this path. A missing `` is closed by the next parameter or function boundary. +Literal outer closing tool tags (`` or ``) appearing +inside open non-JSON argument values (`...`, +`...`, or `<|"|>...<|"|>`) stay argument text while +the parser scans linearly for the value terminator, preserving the 1 MiB tool +buffer bound and strict validation. When a non-strict tagged call omits its closing wrapper tag at natural completion, each dialect accepts it only when its argument body is self-delimited with no trailing non-whitespace: GLM requires at least one closed @@ -968,11 +973,26 @@ also select effort: up to 5,000 map to low effort, up to 20,000 to high effort, and larger budgets to maximum effort; explicit `output_config.effort` wins. Messages budgets above the 32-bit output limit are accepted and never trigger a cut. Responses and Anthropic named effort settings -(`reasoning.effort` and `output_config.effort`) accept named levels and map into -the same neutral levels. They do not accept numeric scores. The frontend resolves -those levels against the effort vocabulary accepted by the prepared template: for example Qwen uses -`low/medium/xhigh`. Native DeepSeek V4 and V4.1 prompt encoders accept -`low/high/xhigh/max` and default to thinking enabled and high effort. +(`reasoning.effort` and `output_config.effort`) accept named levels (`none`, +`minimal`, `low`, `medium`, `high`, `xhigh`, `max`) and map into neutral effort +levels; they do not accept numeric scores. On `POST /v1/chat/completions`, +assistant messages accept prior reasoning text under `reasoning_content`, +`thinking`, or `reasoning` (in that precedence order, rejecting non-string +values with HTTP 400); non-assistant roles ignore `thinking` and `reasoning`. +Chat Completions also accepts nested `reasoning.effort` (with the same named +validation as Responses) when top-level `reasoning_effort` is absent or null, +and normalizes top-level named `reasoning_effort` values `none` (sets +`enable_thinking=false`), `minimal`, `low`, `medium`, `high`, and `max` against +the prepared template or native encoder vocabulary while passing through +`xhigh`, numeric scores, and `chat_template_kwargs` overrides directly. The +frontend resolves neutral effort levels against the vocabulary accepted by the +prepared encoder: for example Qwen uses `low/medium/xhigh` (so `high` resolves +to `medium` and `max` to `xhigh`), GLM and Kimi templates use `low/high/max` +(so `minimal` resolves to `low` and `medium` to `high`), and TMLv0 (`Inkling 2`) +preserves its native `medium` (`0.7`) on Chat Completions while mapping +Responses `reasoning.effort: "medium"` to `high` (`0.9`). Native DeepSeek V4 +and V4.1 prompt encoders accept `low/high/xhigh/max` and default to thinking +enabled and high effort. DeepSeek V4 rejects numeric effort. DeepSeek V4.1 additionally accepts a JSON integer from **1 through 100** in the native `reasoning_effort` option, either at the request's top level or in `chat_template_kwargs`. Its named levels map diff --git a/helios/src/frontend/mod.rs b/helios/src/frontend/mod.rs index b0136cf3a..40313b061 100644 --- a/helios/src/frontend/mod.rs +++ b/helios/src/frontend/mod.rs @@ -850,17 +850,32 @@ impl Frontend { context.insert("thinking_mode".into(), "thinking".into()); context.insert("add_generation_prompt".into(), true.into()); context.insert("continue_final_message".into(), false.into()); - ["low", "medium", "high", "xhigh", "max"] + let render = |effort: &str| { + let mut probe = context.clone(); + probe.insert("reasoning_effort".into(), effort.into()); + self.template + .as_ref() + .unwrap() + .render(&probe, &[]) + .ok() + .map(|rendered| rendered.text) + }; + let fallback = render("__flare_unknown_effort__"); + let rendered: Vec<(&str, String)> = ["low", "medium", "high", "xhigh", "max"] .into_iter() - .filter(|effort| { - context.insert("reasoning_effort".into(), (*effort).into()); - self.template - .as_ref() - .unwrap() - .render(&context, &[]) - .is_ok() + .filter_map(|effort| render(effort).map(|out| (effort, out))) + .collect(); + let has_distinct = fallback + .as_deref() + .is_some_and(|fb| rendered.iter().any(|(_, out)| out != fb)); + rendered + .into_iter() + .filter(|(effort, out)| { + !has_distinct + || *effort != "medium" + || fallback.as_deref() != Some(out.as_str()) }) - .map(str::to_owned) + .map(|(effort, _)| effort.to_owned()) .collect() }); candidates diff --git a/helios/src/output/argument_tags.rs b/helios/src/output/argument_tags.rs index 9b44dcb39..d00a15fa1 100644 --- a/helios/src/output/argument_tags.rs +++ b/helios/src/output/argument_tags.rs @@ -8,7 +8,7 @@ use crate::{ Result, - output::tagged::{RawArguments, ToolDialect, parameter_value, strict_nonstring_raw}, + output::tagged::{Candidate, RawArguments, ToolDialect, parameter_value, strict_nonstring_raw}, }; use serde_json::Value; @@ -22,11 +22,7 @@ pub(crate) const ARGUMENT_MARKERS: [&str; 4] = pub struct ArgumentTags; impl ArgumentTags { - fn parse_body( - body: &str, - tools: &[Value], - eos: bool, - ) -> Result>> { + fn parse_body(body: &str, tools: &[Value], eos: bool) -> Result { let body = body.trim(); let split = body.find("").unwrap_or(body.len()); let name = body[..split].trim(); @@ -77,7 +73,7 @@ impl ArgumentTags { let Ok(container) = super::tagged::container_parameter(value, schema.filter(|_| strict)) else { - return Ok(None); + return Ok(Candidate::InJsonString); }; if let Some((parsed, remaining)) = container && let Some(next) = remaining.strip_prefix("") @@ -86,9 +82,9 @@ impl ArgumentTags { rest = next; continue; } - let (value, tail) = value - .split_once("") - .ok_or("unterminated GLM argument value")?; + let Some((value, tail)) = value.split_once("") else { + return Ok(Candidate::IncompleteValue); + }; if let Some(raw_json) = strict_nonstring_raw(value, schema.filter(|_| strict)) { arguments.insert(key.to_owned(), raw_json); } else { @@ -96,7 +92,10 @@ impl ArgumentTags { } rest = tail; } - Ok(Some(vec![(name.to_owned(), arguments.to_json_string()?)])) + Ok(Candidate::Complete(vec![( + name.to_owned(), + arguments.to_json_string()?, + )])) } } impl ToolDialect for ArgumentTags { @@ -106,13 +105,29 @@ impl ToolDialect for ArgumentTags { const CLOSE: &'static str = ""; fn parse(body: &str, tools: &[Value]) -> Result> { - Self::parse_candidate(body, tools)?.ok_or_else(|| "incomplete JSON argument".into()) + match Self::parse_body(body, tools, false)? { + Candidate::Complete(calls) => Ok(calls), + Candidate::InJsonString => Err("incomplete JSON argument".into()), + Candidate::IncompleteValue => Err("unterminated GLM argument value".into()), + } } - fn parse_candidate(body: &str, tools: &[Value]) -> Result>> { + fn parse_candidate(body: &str, tools: &[Value]) -> Result { Self::parse_body(body, tools, false) } + fn scan_value_end(tail: &str) -> std::result::Result { + const CLOSE: &str = ""; + match tail.find(CLOSE) { + Some(at) => Ok(at + CLOSE.len()), + None => Err(tail.len() - super::tagged::partial_marker(tail, &[CLOSE])), + } + } fn parse_eos(body: &str, tools: &[Value]) -> Result> { - Self::parse_body(body, tools, true)?.ok_or_else(|| "incomplete GLM tool call".into()) + match Self::parse_body(body, tools, true)? { + Candidate::Complete(calls) => Ok(calls), + Candidate::InJsonString | Candidate::IncompleteValue => { + Err("incomplete GLM tool call".into()) + } + } } fn starts_call(text: &str) -> Option { // Calls continue with the function name and an argument key or closing tag; @@ -746,4 +761,175 @@ mod tests { }) ); } + + #[test] + fn literal_closing_tool_tag_inside_argument_values_parses_across_every_split() { + let cases: &[(&str, &[(&str, Value)])] = &[ + ( + "runtextgrep pattern", + &[("run", json!({"text": "grep pattern"}))], + ), + ( + "runtext", + &[("run", json!({"text": ""}))], + ), + ( + r#"runtextmatch "" and ''"#, + &[( + "run", + json!({"text": r#"match "" and ''"#}), + )], + ), + ( + r#"runcount3options{"end":""}textafter end"#, + &[( + "run", + json!({"count": 3, "options": {"end": ""}, "text": "after end"}), + )], + ), + ( + "runtextabruncount2", + &[ + ("run", json!({"text": "ab"})), + ("run", json!({"count": 2})), + ], + ), + ( + "runtextab", + &[("run", json!({"text": "ab"}))], + ), + ]; + for &(text, expected_calls) in cases { + for split in text.char_indices().map(|(at, _)| at).chain([text.len()]) { + let mut parser = ArgumentTagOutput::new(config()); + let mut output = Accumulator::new("literal-close".into()); + for part in [&text[..split], &text[split..]] { + output + .apply(parser.push(Input::Text(part)).unwrap()) + .unwrap(); + } + output + .apply(parser.finish(Termination::Eos).unwrap()) + .unwrap(); + output.finish().unwrap(); + let message = output.message(); + let calls = message["tool_calls"].as_array().unwrap(); + assert_eq!(calls.len(), expected_calls.len(), "{text:?} split {split}"); + for ((name, expected_args), call) in expected_calls.iter().zip(calls.iter()) { + assert_eq!(call["function"]["name"], *name, "{text:?} split {split}"); + let args: Value = + serde_json::from_str(call["function"]["arguments"].as_str().unwrap()) + .unwrap(); + assert_eq!(&args, expected_args, "{text:?} split {split}"); + } + } + } + + // Unterminated `` followed by `` and EOS still fails. + let unterminated = "runtextunfinished"; + for split in unterminated.char_indices().map(|(at, _)| at) { + let mut parser = ArgumentTagOutput::new(config()); + let pushed = parser + .push(Input::Text(&unterminated[..split])) + .and_then(|_| parser.push(Input::Text(&unterminated[split..]))); + assert!( + pushed.is_err() || parser.finish(Termination::Eos).is_err(), + "{unterminated:?} split {split}" + ); + } + + // Strict tool with literal `` succeeds when closed, fails when outer `` is missing at EOS. + let strict_tools = vec![json!({"type":"function", "function": { + "name":"strict_run", "strict":true, + "parameters":{"type":"object", "additionalProperties":false, "required":["text"], + "properties":{"text":{"type":"string"}}} + }})]; + let strict_closed = + "strict_runtextab"; + let mut parser = ArgumentTagOutput::new(OutputConfig { + tools: strict_tools.clone(), + ..config() + }); + let mut output = Accumulator::new("strict-closed".into()); + output + .apply(parser.push(Input::Text(strict_closed)).unwrap()) + .unwrap(); + output + .apply(parser.finish(Termination::Eos).unwrap()) + .unwrap(); + output.finish().unwrap(); + assert_eq!( + output.message()["tool_calls"][0]["function"]["arguments"], + r#"{"text":"ab"}"# + ); + + let mut parser = ArgumentTagOutput::new(OutputConfig { + tools: strict_tools, + ..config() + }); + parser + .push(Input::Text( + "strict_runtextab", + )) + .unwrap(); + assert!(parser.finish(Termination::Eos).is_err()); + + // Single-character streaming handles literal `` inside ``. + let single_char_case = + "runtextgrep α"; + let mut parser = ArgumentTagOutput::new(config()); + let mut output = Accumulator::new("char-by-char".into()); + let mut char_buf = [0u8; 4]; + for ch in single_char_case.chars() { + let s = ch.encode_utf8(&mut char_buf); + output.apply(parser.push(Input::Text(s)).unwrap()).unwrap(); + } + output + .apply(parser.finish(Termination::Eos).unwrap()) + .unwrap(); + output.finish().unwrap(); + assert_eq!( + output.message()["tool_calls"][0]["function"]["arguments"], + r#"{"text":"grep α"}"# + ); + + // Non-EOS termination omits an incomplete call buffered past an inner ``. + for cause in [ + Termination::OutputLimit, + Termination::UserStop, + Termination::Cancelled, + Termination::ExecutionError, + ] { + let mut parser = ArgumentTagOutput::new(config()); + parser + .push(Input::Text( + "runtextgrep cut", + )) + .unwrap(); + assert!(parser.finish(cause).unwrap().is_empty(), "{cause:?}"); + } + + // Many literal `` markers inside one `` scan linearly without quadratic reparsing. + let repeated = "".repeat(40_000); + let large = format!( + "runtext{repeated}" + ); + let mut parser = ArgumentTagOutput::new(config()); + let mut output = Accumulator::new("linear-scan".into()); + for chunk in large.as_bytes().chunks(4096) { + let s = std::str::from_utf8(chunk).unwrap(); + output.apply(parser.push(Input::Text(s)).unwrap()).unwrap(); + } + output + .apply(parser.finish(Termination::Eos).unwrap()) + .unwrap(); + output.finish().unwrap(); + let args: Value = serde_json::from_str( + output.message()["tool_calls"][0]["function"]["arguments"] + .as_str() + .unwrap(), + ) + .unwrap(); + assert_eq!(args["text"].as_str().unwrap(), repeated); + } } diff --git a/helios/src/output/chatml.rs b/helios/src/output/chatml.rs index 7d3df81d0..4fbda7e20 100644 --- a/helios/src/output/chatml.rs +++ b/helios/src/output/chatml.rs @@ -9,7 +9,7 @@ pub use crate::output::tagged::OutputConfig; use crate::{ Result, - output::tagged::{RawArguments, TaggedOutput, ToolDialect, strict_nonstring_raw}, + output::tagged::{Candidate, RawArguments, TaggedOutput, ToolDialect, strict_nonstring_raw}, }; use serde_json::Value; @@ -22,13 +22,31 @@ impl ToolDialect for FunctionTags = Some(("")); const TOOL_ENDS_REASONING: bool = true; fn parse(body: &str, tools: &[Value]) -> Result> { - Ok(vec![parse_tool(body, tools, WRAPPING_NEWLINES, false)?]) + parse_tool(body, tools, WRAPPING_NEWLINES, false) } - fn parse_candidate(body: &str, tools: &[Value]) -> Result>> { - Ok(parse_tool_candidate(body, tools, WRAPPING_NEWLINES, true)?.map(|call| vec![call])) + fn parse_candidate(body: &str, tools: &[Value]) -> Result { + parse_tool_candidate(body, tools, WRAPPING_NEWLINES, true) + } + fn scan_value_end(tail: &str) -> std::result::Result { + for (at, _) in tail.match_indices('<') { + let suffix = &tail[at..]; + if let Some(rest) = parameter_end(suffix) { + return Ok(at + suffix.len() - rest.len()); + } + if parameter_start(suffix).is_some() || suffix.starts_with("") { + return Ok(at); + } + if possible_parameter_end(suffix) + || possible_parameter_start(suffix) + || "".starts_with(suffix) + { + return Err(at); + } + } + Err(tail.len()) } fn parse_eos(body: &str, tools: &[Value]) -> Result> { - Ok(vec![parse_tool(body, tools, WRAPPING_NEWLINES, true)?]) + parse_tool(body, tools, WRAPPING_NEWLINES, true) } fn starts_call(text: &str) -> Option { // Calls continue with `` and a parameter or closing tag; quoted @@ -79,6 +97,27 @@ fn possible_parameter_start(text: &str) -> bool { text.is_empty() || text.starts_with('=') } +fn possible_parameter_end(text: &str) -> bool { + let Some(text) = text.strip_prefix('<') else { + return false; + }; + let text = text.trim_start(); + if text.is_empty() { + return true; + } + let Some(text) = text.strip_prefix('/') else { + return false; + }; + let text = text.trim_start(); + if "parameter".starts_with(text) { + return true; + } + let Some(text) = text.strip_prefix("parameter") else { + return false; + }; + text.trim_start().is_empty() +} + pub type ChatMlOutput = TaggedOutput>; pub type CompactChatMlOutput = TaggedOutput>; @@ -87,9 +126,12 @@ fn parse_tool( tools: &[Value], wrapped_parameters: bool, allow_unclosed_function: bool, -) -> Result<(String, String)> { - parse_tool_candidate(body, tools, wrapped_parameters, allow_unclosed_function)? - .ok_or_else(|| "incomplete JSON parameter".into()) +) -> Result> { + match parse_tool_candidate(body, tools, wrapped_parameters, allow_unclosed_function)? { + Candidate::Complete(calls) => Ok(calls), + Candidate::InJsonString => Err("incomplete JSON parameter".into()), + Candidate::IncompleteValue => Err("unterminated tool parameter value".into()), + } } fn parse_tool_candidate( @@ -97,7 +139,7 @@ fn parse_tool_candidate( tools: &[Value], wrapped_parameters: bool, allow_unclosed_function: bool, -) -> Result> { +) -> Result { let body = body .trim() .strip_prefix("") { - Some((at, 0)) - } else { - None - } - }) - .ok_or("unterminated tool parameter value")?; + let Some((end, consumed)) = tail.match_indices('<').find_map(|(at, _)| { + let suffix = &tail[at..]; + if let Some(rest) = parameter_end(suffix) { + Some((at, suffix.len() - rest.len())) + } else if parameter_start(suffix).is_some() || suffix.starts_with("") { + Some((at, 0)) + } else { + None + } + }) else { + return Ok(Candidate::IncompleteValue); + }; let (value, tail) = (&tail[..end], &tail[end + consumed..]); let value = if wrapped_parameters { let value = value.strip_prefix('\n').unwrap_or(value); @@ -179,7 +220,10 @@ fn parse_tool_candidate( } rest = tail; } - Ok(Some((name.into(), arguments.to_json_string()?))) + Ok(Candidate::Complete(vec![( + name.into(), + arguments.to_json_string()?, + )])) } fn parameter_start(text: &str) -> Option<(&str, &str)> { @@ -1377,4 +1421,159 @@ mod tests { json!({"items": [3, 4], "const_num": 5, "nested": [{"n": 6}]}) ); } + + #[test] + fn literal_closing_tool_tag_inside_parameter_value_parses_across_every_split() { + let cases: &[(&str, &[(&str, Value)])] = &[ + ( + "grep pattern", + &[("lookup", json!({"city": "grep pattern"}))], + ), + ( + "ab", + &[("lookup", json!({"city": "ab"}))], + ), + ( + "ab", + &[("lookup", json!({"city": "ab"}))], + ), + ( + "abc", + &[ + ("lookup", json!({"city": "ab"})), + ("lookup", json!({"city": "c"})), + ], + ), + ]; + for &(text, expected_calls) in cases { + for split in text.char_indices().map(|(at, _)| at).chain([text.len()]) { + for compact in [false, true] { + let mut output = Accumulator::new("chatml-literal-close".into()); + if compact { + let mut parser = CompactChatMlOutput::new(config()); + for part in [&text[..split], &text[split..]] { + output + .apply(parser.push(Input::Text(part)).unwrap()) + .unwrap(); + } + output + .apply(parser.finish(Termination::Eos).unwrap()) + .unwrap(); + } else { + let mut parser = ChatMlOutput::new(config()); + for part in [&text[..split], &text[split..]] { + output + .apply(parser.push(Input::Text(part)).unwrap()) + .unwrap(); + } + output + .apply(parser.finish(Termination::Eos).unwrap()) + .unwrap(); + } + output.finish().unwrap(); + let message = output.message(); + let calls = message["tool_calls"].as_array().unwrap(); + assert_eq!(calls.len(), expected_calls.len(), "split {split} compact {compact}"); + for ((name, expected_args), call) in expected_calls.iter().zip(calls.iter()) { + assert_eq!(call["function"]["name"], *name, "split {split} compact {compact}"); + let args: Value = serde_json::from_str( + call["function"]["arguments"].as_str().unwrap(), + ) + .unwrap(); + assert_eq!(&args, expected_args, "split {split} compact {compact}"); + } + } + } + } + + // Single-character streaming handles literal `` inside ``. + let mut parser = ChatMlOutput::new(config()); + let mut output = Accumulator::new("chatml-char-by-char".into()); + let mut char_buf = [0u8; 4]; + for ch in cases[0].0.chars() { + let s = ch.encode_utf8(&mut char_buf); + output.apply(parser.push(Input::Text(s)).unwrap()).unwrap(); + } + output + .apply(parser.finish(Termination::Eos).unwrap()) + .unwrap(); + output.finish().unwrap(); + let args: Value = serde_json::from_str( + output.message()["tool_calls"][0]["function"]["arguments"] + .as_str() + .unwrap(), + ) + .unwrap(); + assert_eq!(args, json!({"city": "grep pattern"})); + + // Unterminated `` followed by `` and EOS still fails. + let mut parser = ChatMlOutput::new(config()); + let pushed = parser.push(Input::Text( + "unfinished", + )); + assert!(pushed.is_err() || parser.finish(Termination::Eos).is_err()); + + // Strict tool with literal `` succeeds when closed and fails when unclosed at EOS. + let strict_tools = vec![json!({"type":"function", "function": { + "name":"strict_lookup", "strict":true, + "parameters":{"type":"object", "additionalProperties":false, "required":["city"], + "properties":{"city":{"type":"string"}}} + }})]; + let mut parser = ChatMlOutput::new(OutputConfig { + tools: strict_tools.clone(), + ..config() + }); + let mut output = Accumulator::new("chatml-strict-closed".into()); + output + .apply( + parser + .push(Input::Text( + "ab", + )) + .unwrap(), + ) + .unwrap(); + output + .apply(parser.finish(Termination::Eos).unwrap()) + .unwrap(); + output.finish().unwrap(); + assert_eq!( + output.message()["tool_calls"][0]["function"]["arguments"], + r#"{"city":"ab"}"# + ); + + let mut parser = ChatMlOutput::new(OutputConfig { + tools: strict_tools, + ..config() + }); + parser + .push(Input::Text( + "ab", + )) + .unwrap(); + assert!(parser.finish(Termination::Eos).is_err()); + + // Many literal `` markers inside one `` scan linearly. + let repeated = "".repeat(40_000); + let large = format!( + "{repeated}" + ); + let mut parser = ChatMlOutput::new(config()); + let mut output = Accumulator::new("chatml-linear".into()); + for chunk in large.as_bytes().chunks(4096) { + let s = std::str::from_utf8(chunk).unwrap(); + output.apply(parser.push(Input::Text(s)).unwrap()).unwrap(); + } + output + .apply(parser.finish(Termination::Eos).unwrap()) + .unwrap(); + output.finish().unwrap(); + let args: Value = serde_json::from_str( + output.message()["tool_calls"][0]["function"]["arguments"] + .as_str() + .unwrap(), + ) + .unwrap(); + assert_eq!(args["city"].as_str().unwrap(), repeated); + } } diff --git a/helios/src/output/gemma_call.rs b/helios/src/output/gemma_call.rs index 1e9ad47ac..b3a0da31e 100644 --- a/helios/src/output/gemma_call.rs +++ b/helios/src/output/gemma_call.rs @@ -5,12 +5,23 @@ //! Brace-delimited calls with bare keys and `<|"|>`-quoted strings. -use crate::Result; +use crate::{Result, output::tagged::Candidate}; use serde_json::{Map, Value}; const QUOTE: &str = "<|\"|>"; -fn quoted<'a>(text: &mut &'a str) -> Option> { +enum ParseError { + UnterminatedQuote, + Other(crate::Error), +} + +impl From<&str> for ParseError { + fn from(message: &str) -> Self { + Self::Other(message.into()) + } +} + +fn quoted<'a>(text: &mut &'a str) -> Option> { let current: &'a str = text; let body = current.strip_prefix(QUOTE)?; Some(match body.split_once(QUOTE) { @@ -18,11 +29,15 @@ fn quoted<'a>(text: &mut &'a str) -> Option> { *text = rest; Ok(value) } - None => Err("unterminated tool call string".into()), + None => Err(ParseError::UnterminatedQuote), }) } -fn value(text: &mut &str, schema: Option<&Value>, depth: usize) -> Result { +fn value( + text: &mut &str, + schema: Option<&Value>, + depth: usize, +) -> std::result::Result { if depth > 128 { return Err("tool call arguments exceed the nesting bound".into()); } @@ -106,7 +121,7 @@ fn value(text: &mut &str, schema: Option<&Value>, depth: usize) -> Result pub struct GemmaCall; impl GemmaCall { - fn parse_body(body: &str, tools: &[Value], eos: bool) -> Result> { + fn parse_body(body: &str, tools: &[Value], eos: bool) -> Result { let body = body.trim_start(); let call = body .strip_prefix("call:") @@ -128,11 +143,18 @@ impl GemmaCall { return Err("incomplete strict Gemma call tool call".into()); } let schema = function.and_then(|function| function.get("parameters")); - let arguments = value(&mut rest, schema, 0)?; + let arguments = match value(&mut rest, schema, 0) { + Ok(arguments) => arguments, + Err(ParseError::UnterminatedQuote) => return Ok(Candidate::IncompleteValue), + Err(ParseError::Other(error)) => return Err(error), + }; if !rest.trim().is_empty() { return Err("unexpected content after tool call arguments".into()); } - Ok(vec![(name.to_owned(), arguments.to_string())]) + Ok(Candidate::Complete(vec![( + name.to_owned(), + arguments.to_string(), + )])) } } impl super::tagged::ToolDialect for GemmaCall { @@ -142,10 +164,27 @@ impl super::tagged::ToolDialect for GemmaCall { const CLOSE: &'static str = ""; fn parse(body: &str, tools: &[Value]) -> Result> { + match Self::parse_body(body, tools, false)? { + Candidate::Complete(calls) => Ok(calls), + Candidate::IncompleteValue => Err("unterminated tool call string".into()), + Candidate::InJsonString => Err("incomplete JSON argument".into()), + } + } + fn parse_candidate(body: &str, tools: &[Value]) -> Result { Self::parse_body(body, tools, false) } + fn scan_value_end(tail: &str) -> std::result::Result { + match tail.find(QUOTE) { + Some(at) => Ok(at + QUOTE.len()), + None => Err(tail.len() - super::tagged::partial_marker(tail, &[QUOTE])), + } + } fn parse_eos(body: &str, tools: &[Value]) -> Result> { - Self::parse_body(body, tools, true) + match Self::parse_body(body, tools, true)? { + Candidate::Complete(calls) => Ok(calls), + Candidate::IncompleteValue => Err("unterminated tool call string".into()), + Candidate::InJsonString => Err("incomplete JSON argument".into()), + } } } @@ -323,4 +362,107 @@ mod tests { assert!(parser.finish(cause).unwrap().is_empty(), "{cause:?}"); } } + + #[test] + fn literal_closing_tool_tag_inside_quoted_string_parses_across_splits() { + use crate::output::{ + Input, ModelOutput, Termination, + tagged::{OutputConfig, OutputStart, TaggedOutput}, + }; + use crate::server::output::Accumulator; + + let tools = vec![json!({"function":{"name":"lookup","parameters":{"properties":{ + "q":{"type":"string"},"items":{"type":"array","items":{"type":"string"}} + }}}})]; + let text = "<|tool_call>call:lookup{q:<|\"|>grep pattern<|\"|>,items:[<|\"|>ab<|\"|>]}"; + for split in text.char_indices().map(|(at, _)| at).chain([text.len()]) { + let mut parser = TaggedOutput::::new(OutputConfig { + structured: false, + start: OutputStart::Content, + tools: tools.clone(), + }); + let mut output = Accumulator::new("gemma-literal-close".into()); + for part in [&text[..split], &text[split..]] { + output + .apply(parser.push(Input::Text(part)).unwrap()) + .unwrap(); + } + output + .apply(parser.finish(Termination::Eos).unwrap()) + .unwrap(); + output.finish().unwrap(); + let calls = output.message()["tool_calls"].as_array().unwrap().clone(); + assert_eq!(calls.len(), 1, "split {split}"); + let args: Value = + serde_json::from_str(calls[0]["function"]["arguments"].as_str().unwrap()).unwrap(); + assert_eq!( + args, + json!({"q": "grep pattern", "items": ["ab"]}), + "split {split}" + ); + } + + // Single-character streaming also preserves literal ``. + let mut parser = TaggedOutput::::new(OutputConfig { + structured: false, + start: OutputStart::Content, + tools: tools.clone(), + }); + let mut output = Accumulator::new("gemma-char-by-char".into()); + let mut char_buf = [0u8; 4]; + for ch in text.chars() { + let s = ch.encode_utf8(&mut char_buf); + output.apply(parser.push(Input::Text(s)).unwrap()).unwrap(); + } + output + .apply(parser.finish(Termination::Eos).unwrap()) + .unwrap(); + output.finish().unwrap(); + let args: Value = serde_json::from_str( + output.message()["tool_calls"][0]["function"]["arguments"] + .as_str() + .unwrap(), + ) + .unwrap(); + assert_eq!( + args, + json!({"q": "grep pattern", "items": ["ab"]}) + ); + + // Unterminated `<|"|>` string followed by `` and EOS still fails. + let mut parser = TaggedOutput::::new(OutputConfig { + structured: false, + start: OutputStart::Content, + tools: tools.clone(), + }); + let pushed = parser.push(Input::Text( + "<|tool_call>call:lookup{q:<|\"|>unfinished", + )); + assert!(pushed.is_err() || parser.finish(Termination::Eos).is_err()); + + // Many literal `` markers inside one `<|"|>` string scan linearly. + let repeated = "".repeat(40_000); + let large = format!("<|tool_call>call:lookup{{q:<|\"|>{repeated}<|\"|>}}"); + let mut parser = TaggedOutput::::new(OutputConfig { + structured: false, + start: OutputStart::Content, + tools, + }); + let mut output = Accumulator::new("gemma-linear".into()); + for chunk in large.as_bytes().chunks(4096) { + let s = std::str::from_utf8(chunk).unwrap(); + output.apply(parser.push(Input::Text(s)).unwrap()).unwrap(); + } + output + .apply(parser.finish(Termination::Eos).unwrap()) + .unwrap(); + output.finish().unwrap(); + let args: Value = serde_json::from_str( + output.message()["tool_calls"][0]["function"]["arguments"] + .as_str() + .unwrap(), + ) + .unwrap(); + assert_eq!(args["q"].as_str().unwrap(), repeated); + } } diff --git a/helios/src/output/minimax_xml.rs b/helios/src/output/minimax_xml.rs index 3843d235d..122a318c2 100644 --- a/helios/src/output/minimax_xml.rs +++ b/helios/src/output/minimax_xml.rs @@ -197,8 +197,8 @@ impl super::tagged::ToolDialect for MiniMaxXml { fn parse(body: &str, tools: &[Value]) -> Result> { Self::parse_body(body, tools, false) } - fn parse_candidate(body: &str, tools: &[Value]) -> Result>> { - Self::parse_body(body, tools, true).map(Some) + fn parse_candidate(body: &str, tools: &[Value]) -> Result { + Self::parse_body(body, tools, true).map(super::tagged::Candidate::Complete) } fn parse_eos(body: &str, tools: &[Value]) -> Result> { Self::parse_body(body, tools, true) @@ -440,4 +440,46 @@ mod tests { json!({"value": ["user_input"], "plain": "hello", "empty_list": []}) ); } + + #[test] + fn plain_closing_tool_tag_in_element_text_parses_without_matching_namespaced_closer() { + use crate::output::{ + Input, ModelOutput, Termination, + tagged::{OutputConfig, OutputStart, TaggedOutput}, + }; + use crate::server::output::Accumulator; + + let open = MiniMaxXml::OPEN; + let close = MiniMaxXml::CLOSE; + let text = format!( + "{open}{INVOKE}'lookup'>{ELEMENT}q>grep pattern{NAMESPACE}{INVOKE_END}{close}" + ); + let tools = vec![json!({"function":{"name":"lookup","parameters":{"properties":{ + "q":{"type":"string"} + }}}})]; + for split in text.char_indices().map(|(at, _)| at).chain([text.len()]) { + let mut parser = TaggedOutput::::new(OutputConfig { + structured: false, + start: OutputStart::Content, + tools: tools.clone(), + }); + let mut output = Accumulator::new("minimax-plain-close".into()); + for part in [&text[..split], &text[split..]] { + output + .apply(parser.push(Input::Text(part)).unwrap()) + .unwrap(); + } + output + .apply(parser.finish(Termination::Eos).unwrap()) + .unwrap(); + output.finish().unwrap(); + let args: Value = serde_json::from_str( + output.message()["tool_calls"][0]["function"]["arguments"] + .as_str() + .unwrap(), + ) + .unwrap(); + assert_eq!(args, json!({"q": "grep pattern"}), "split {split}"); + } + } } diff --git a/helios/src/output/tagged.rs b/helios/src/output/tagged.rs index 77ba64eed..313987094 100644 --- a/helios/src/output/tagged.rs +++ b/helios/src/output/tagged.rs @@ -28,6 +28,14 @@ pub struct OutputConfig { pub tools: Vec, } +#[derive(Debug, PartialEq, Eq)] +pub enum Candidate { + Complete(Vec<(String, String)>), + InJsonString, + /// Apparent closing tag appeared inside an open non-JSON argument value. + IncompleteValue, +} + pub trait ToolDialect { const NAME: &'static str; const TRIM_NEWLINES: bool; @@ -39,9 +47,19 @@ pub trait ToolDialect { /// JSON string boundaries incrementally in O(n) rather than rescanning from byte 0. const JSON_BODY: bool = false; fn parse(body: &str, tools: &[Value]) -> Result>; - /// `None` means the apparent closing tag is text inside a JSON string. - fn parse_candidate(body: &str, tools: &[Value]) -> Result>> { - Self::parse(body, tools).map(Some) + /// Evaluates whether `body` before a candidate closing tag completes a call, + /// sits inside an open JSON string (`Candidate::InJsonString`), or sits inside + /// an open non-JSON argument value (`Candidate::IncompleteValue`). + fn parse_candidate(body: &str, tools: &[Value]) -> Result { + Self::parse(body, tools).map(Candidate::Complete) + } + /// Advances linearly across an open non-JSON argument value after + /// `Candidate::IncompleteValue`. Returns `Ok(advance)` when a value-ending + /// boundary appears at `tail[..advance]` (resuming closer scanning at + /// `tail[advance..]`), or `Err(safe_advance)` to advance `search_from` past + /// bytes that cannot start a value-ending boundary and wait for more input. + fn scan_value_end(_tail: &str) -> std::result::Result { + Ok(0) } /// Parse an unclosed call body at natural end-of-sequence (`Termination::Eos`). /// Accepts only structurally complete, self-delimited, non-strict calls. @@ -220,6 +238,7 @@ pub struct TaggedTools { close: String, search_from: usize, in_json_string: bool, + in_value: bool, escaped: bool, confirmed: bool, outer_closed: bool, @@ -270,7 +289,7 @@ impl TaggedTools { | Termination::OutputLimit ) { EosDecision::Omit - } else if !self.confirmed || self.in_json_string { + } else if !self.confirmed || self.in_json_string || self.in_value { EosDecision::Reject } else { EosDecision::ParseEos @@ -328,6 +347,18 @@ impl ToolCallParser for TaggedTools { return Ok(Progress::default()); } } + if self.in_value { + match D::scan_value_end(&self.buffer[self.search_from..]) { + Ok(advance) => { + self.search_from += advance; + self.in_value = false; + } + Err(advance) => { + self.search_from += advance; + return Ok(Progress::default()); + } + } + } let tail = &self.buffer[self.search_from..]; let (inner, inner_len) = match D::FUNCTION { Some((_, close)) => (tail.find(close), close.len()), @@ -361,15 +392,19 @@ impl ToolCallParser for TaggedTools { continue; } } - if let Some(calls) = D::parse_candidate(&self.buffer[..end], &self.tools)? { - self.buffer.drain(..self.search_from); - self.search_from = 0; - self.in_json_string = false; - self.escaped = false; - self.outer_closed = outer_closed; - break calls; + match D::parse_candidate(&self.buffer[..end], &self.tools)? { + Candidate::Complete(calls) => { + self.buffer.drain(..self.search_from); + self.search_from = 0; + self.in_json_string = false; + self.in_value = false; + self.escaped = false; + self.outer_closed = outer_closed; + break calls; + } + Candidate::InJsonString => self.in_json_string = true, + Candidate::IncompleteValue => self.in_value = true, } - self.in_json_string = true; }; Ok(Progress { events: self.emit_calls(calls), @@ -381,6 +416,7 @@ impl ToolCallParser for TaggedTools { let body = std::mem::take(&mut self.buffer); self.search_from = 0; self.in_json_string = false; + self.in_value = false; self.escaped = false; match decision { EosDecision::Omit => Ok(vec![]), @@ -515,6 +551,7 @@ impl ModelOutput for TaggedOutput { close: D::CLOSE.to_owned(), search_from: 0, in_json_string: false, + in_value: false, escaped: false, confirmed: true, outer_closed: false, @@ -849,6 +886,7 @@ impl TaggedOutput { close: self.tool_close.clone(), search_from: 0, in_json_string: false, + in_value: false, escaped: false, confirmed, outer_closed: false, @@ -918,7 +956,7 @@ impl TaggedOutput { } } -fn partial_marker(text: &str, markers: &[&str]) -> usize { +pub(super) fn partial_marker(text: &str, markers: &[&str]) -> usize { let mut best = 0; for marker in markers { let mut len = text.len().min(marker.len().saturating_sub(1)); @@ -1242,6 +1280,7 @@ mod tests { close: MultiCallDialect::CLOSE.into(), search_from: 0, in_json_string: true, + in_value: false, escaped: false, confirmed: true, outer_closed: false, diff --git a/helios/src/output/tagged/kani_proofs.rs b/helios/src/output/tagged/kani_proofs.rs index db8d649c8..4f0384b8f 100644 --- a/helios/src/output/tagged/kani_proofs.rs +++ b/helios/src/output/tagged/kani_proofs.rs @@ -96,6 +96,7 @@ fn tagged_tools_eos_decision_enforces_termination_and_confirmation() { }; let confirmed: bool = kani::any(); let in_json_string: bool = kani::any(); + let in_value: bool = kani::any(); let tools = TaggedTools:: { dialect: std::marker::PhantomData, @@ -103,6 +104,7 @@ fn tagged_tools_eos_decision_enforces_termination_and_confirmation() { close: String::new(), search_from: 0, in_json_string, + in_value, escaped: kani::any(), confirmed, outer_closed: kani::any(), @@ -113,7 +115,7 @@ fn tagged_tools_eos_decision_enforces_termination_and_confirmation() { let decision = tools.eos_decision(cause); let expected = if cause != Termination::Eos { EosDecision::Omit - } else if !confirmed || in_json_string { + } else if !confirmed || in_json_string || in_value { EosDecision::Reject } else { EosDecision::ParseEos @@ -121,13 +123,17 @@ fn tagged_tools_eos_decision_enforces_termination_and_confirmation() { assert_eq!(decision, expected); kani::cover!(decision == EosDecision::Omit, "non-eos omits"); kani::cover!( - cause == Termination::Eos && !confirmed && !in_json_string, + cause == Termination::Eos && !confirmed && !in_json_string && !in_value, "unconfirmed rejected at eos" ); kani::cover!( - cause == Termination::Eos && confirmed && in_json_string, + cause == Termination::Eos && confirmed && in_json_string && !in_value, "unclosed json string rejected at eos" ); + kani::cover!( + cause == Termination::Eos && confirmed && !in_json_string && in_value, + "unclosed argument value rejected at eos" + ); kani::cover!(decision == EosDecision::ParseEos, "confirmed eos parses"); // Isolate borrowed `eos_decision` from `Arc<[serde_json::Value]>` drop unwinding. std::mem::forget(tools); diff --git a/helios/src/server/inference.rs b/helios/src/server/inference.rs index 961c4eb10..ba421b53d 100644 --- a/helios/src/server/inference.rs +++ b/helios/src/server/inference.rs @@ -118,6 +118,8 @@ pub enum Effort { /// Below low. Prompt formats without a minimal level render low effort. Minimal, Low, + /// Between low and high. Prompt formats without a distinct medium level render high effort. + Medium, High, Max, } diff --git a/helios/src/server/protocol/decode.rs b/helios/src/server/protocol/decode.rs index bffd0378e..c144aff2a 100644 --- a/helios/src/server/protocol/decode.rs +++ b/helios/src/server/protocol/decode.rs @@ -181,10 +181,19 @@ fn chat_messages(body: &Value) -> Result> { let role = serde_json::from_value(v["role"].clone()) .map_err(|_| "unsupported message role")?; let mut parts = vec![]; - if let Some(text) = v.get("reasoning_content").filter(|v| !v.is_null()) { + let reasoning_field = if role == Role::Assistant { + ["reasoning_content", "thinking", "reasoning"] + .into_iter() + .find_map(|key| v.get(key).filter(|v| !v.is_null()).map(|value| (key, value))) + } else { + v.get("reasoning_content") + .filter(|v| !v.is_null()) + .map(|value| ("reasoning_content", value)) + }; + if let Some((key, text)) = reasoning_field { parts.push(Part::Reasoning( text.as_str() - .ok_or("reasoning_content must be text")? + .ok_or_else(|| format!("{key} must be text"))? .into(), )); } @@ -584,10 +593,19 @@ fn options(body: &Value, protocol: Protocol) -> Result<(Options, Option)> } options.constraint = Some(Constraint::Lark(field(body, "grammar")?.into())); } + let chat_nested_effort = protocol == Protocol::Chat + && !present(body, "reasoning_effort") + && present(&body["reasoning"], "effort"); let effort = if protocol == Protocol::Responses { body["reasoning"].get("effort") } else if protocol == Protocol::Messages { body["output_config"].get("effort") + } else if protocol == Protocol::Chat { + if chat_nested_effort { + body["reasoning"].get("effort") + } else { + body.get("reasoning_effort").filter(|v| v.is_string()) + } } else { None }; @@ -601,8 +619,12 @@ fn options(body: &Value, protocol: Protocol) -> Result<(Options, Option)> } Some("minimal") => Some(Effort::Minimal), Some("low") => Some(Effort::Low), + Some("medium") if protocol == Protocol::Chat && !chat_nested_effort => { + Some(Effort::Medium) + } Some("medium" | "high") => Some(Effort::High), Some("xhigh" | "max") => Some(Effort::Max), + _ if protocol == Protocol::Chat && !chat_nested_effort => None, _ => return Err("unsupported reasoning effort".into()), }; if let Some(native) = native { @@ -652,6 +674,12 @@ fn options(body: &Value, protocol: Protocol) -> Result<(Options, Option)> }); } } + let withheld_chat_effort = protocol == Protocol::Chat + && (chat_nested_effort + || matches!( + body.get("reasoning_effort").and_then(Value::as_str), + Some("none" | "minimal" | "low" | "medium" | "high" | "max") + )); for key in [ "documents", "enable_thinking", @@ -659,6 +687,9 @@ fn options(body: &Value, protocol: Protocol) -> Result<(Options, Option)> "continue_final_message", "add_generation_prompt", ] { + if key == "reasoning_effort" && withheld_chat_effort { + continue; + } if let Some(value) = body.get(key) { options.template.insert(key.into(), value.clone()); } @@ -2400,4 +2431,330 @@ mod native_prompt_tests { } } } + + #[test] + fn chat_preserves_assistant_reasoning_aliases_across_jinja_and_native_encoders() { + let jinja_template = "{% for m in messages %}{% if m.reasoning_content is defined %}{{ m.reasoning_content }}{% endif %}{{ m.content }}{% mark %}{% endfor %}"; + let (jinja_frontend, jinja_compiler, mut jinja_config) = renderer( + PromptEncoder::Jinja, + Some(jinja_template), + TemplateEncoding::Text, + ); + jinja_config.contract.frontend.rejected_tokens.clear(); + let (ds_frontend, ds_compiler, ds_config) = native(PromptEncoder::DeepseekV41); + + let render = |frontend: &Frontend, + compiler: &GrammarCompiler, + config: &crate::server::ModelConfig, + assistant: Value| { + let decoded = decode( + Protocol::Chat, + json!({ + "tools": [{ + "type": "function", + "function": { + "name": "grep", + "parameters": {"type": "object", "properties": {"pattern": {"type": "string"}}} + } + }], + "messages": [ + {"role": "user", "content": "Find the bug."}, + assistant, + {"role": "tool", "tool_call_id": "call_1", "content": "line 42"} + ] + }), + false, + ) + .unwrap(); + crate::server::request::prepare_inference( + frontend, None, compiler, config, &decoded.request, 0, false, + ) + .unwrap() + .rendered_prompt + }; + + for (frontend, compiler, config) in [ + (&jinja_frontend, &jinja_compiler, &jinja_config), + (&ds_frontend, &ds_compiler, &ds_config), + ] { + let base = || { + json!({ + "role": "assistant", + "content": "", + "tool_calls": [{ + "id": "call_1", + "type": "function", + "function": {"name": "grep", "arguments": "{\"pattern\":\"bug\"}"} + }] + }) + }; + let mut canonical_msg = base(); + canonical_msg["reasoning_content"] = json!("Inspect callers first."); + let canonical = render(frontend, compiler, config, canonical_msg); + assert!(canonical.contains("Inspect callers first.")); + + for alias in ["thinking", "reasoning"] { + let mut msg = base(); + msg[alias] = json!("Inspect callers first."); + assert_eq!(render(frontend, compiler, config, msg), canonical, "{alias}"); + + // Null primary field falls through to the alias. + let mut null_primary = base(); + null_primary["reasoning_content"] = Value::Null; + null_primary[alias] = json!("Inspect callers first."); + assert_eq!( + render(frontend, compiler, config, null_primary), + canonical, + "null primary -> {alias}" + ); + } + + // Explicit reasoning_content takes precedence over aliases. + let mut both = base(); + both["reasoning_content"] = json!("Inspect callers first."); + both["reasoning"] = json!("Ignored fallback."); + assert_eq!(render(frontend, compiler, config, both), canonical); + } + + // Non-string alias values on assistant messages are rejected with the offending field name. + for key in ["reasoning_content", "thinking", "reasoning"] { + let mut msg = json!({"role": "assistant", "content": "ok"}); + msg[key] = json!(123); + let err = decode(Protocol::Chat, json!({"messages": [msg]}), false) + .err() + .unwrap() + .to_string(); + assert!(err.contains(key), "{key}: {err}"); + } + + // Generic `thinking` and `reasoning` keys on non-assistant roles do not inject Part::Reasoning. + let decoded = decode( + Protocol::Chat, + json!({ + "messages": [ + {"role": "user", "content": "Run", "thinking": "ignored", "reasoning": 42}, + {"role": "assistant", "content": "", "tool_calls": [{ + "id": "call_1", + "type": "function", + "function": {"name": "grep", "arguments": "{}"} + }]}, + {"role": "tool", "tool_call_id": "call_1", "content": "ok", "thinking": "meta", "reasoning": {"nested": true}} + ] + }), + false, + ) + .unwrap(); + let Input::Conversation(messages) = decoded.request.input else { + panic!("expected chat messages"); + }; + assert!( + !messages[0] + .parts + .iter() + .any(|p| matches!(p, Part::Reasoning(_))) + ); + assert!( + !messages[2] + .parts + .iter() + .any(|p| matches!(p, Part::Reasoning(_))) + ); + } + + #[test] + fn chat_normalizes_reasoning_effort_across_glm_qwen_tml_and_deepseek() { + // 1. GLM-style fallback template (`['low', 'high'] else 'max'`). + let glm_template = concat!( + "{%- set eff = reasoning_effort if reasoning_effort is defined and reasoning_effort in ['low', 'high'] else 'max' -%}", + "effort={{ eff }};think={% if enable_thinking is defined and not enable_thinking %}false{% else %}true{% endif %};", + "{% for m in messages %}{{ m.content }}{% mark %}{% endfor %}" + ); + let (glm_frontend, glm_compiler, mut glm_config) = renderer( + PromptEncoder::Jinja, + Some(glm_template), + TemplateEncoding::Text, + ); + glm_config.contract.frontend.rejected_tokens.clear(); + + let prepare_jinja = |frontend: &Frontend, + compiler: &GrammarCompiler, + config: &crate::server::ModelConfig, + extra: Value| { + let mut body = json!({"messages": [{"role": "user", "content": "Hello"}]}); + body.as_object_mut() + .unwrap() + .extend(extra.as_object().unwrap().clone()); + let decoded = decode(Protocol::Chat, body, false).unwrap(); + crate::server::request::prepare_inference( + frontend, None, compiler, config, &decoded.request, 0, false, + ) + .unwrap() + .rendered_prompt + }; + + assert!(prepare_jinja(&glm_frontend, &glm_compiler, &glm_config, json!({})).starts_with("effort=max;think=true;")); + assert!(prepare_jinja(&glm_frontend, &glm_compiler, &glm_config, json!({"reasoning_effort": "low"})).starts_with("effort=low;")); + assert!(prepare_jinja(&glm_frontend, &glm_compiler, &glm_config, json!({"reasoning_effort": "minimal"})).starts_with("effort=low;")); + assert!(prepare_jinja(&glm_frontend, &glm_compiler, &glm_config, json!({"reasoning_effort": "medium"})).starts_with("effort=high;")); + assert!(prepare_jinja(&glm_frontend, &glm_compiler, &glm_config, json!({"reasoning_effort": "high"})).starts_with("effort=high;")); + assert!(prepare_jinja(&glm_frontend, &glm_compiler, &glm_config, json!({"reasoning_effort": "xhigh"})).starts_with("effort=max;")); + assert!(prepare_jinja(&glm_frontend, &glm_compiler, &glm_config, json!({"reasoning_effort": "max"})).starts_with("effort=max;")); + assert!(prepare_jinja(&glm_frontend, &glm_compiler, &glm_config, json!({"reasoning_effort": "none"})).starts_with("effort=max;think=false;")); + assert!( + prepare_jinja(&glm_frontend, &glm_compiler, &glm_config, json!({"reasoning_effort": "none", "enable_thinking": true})) + .starts_with("effort=max;think=true;") + ); + assert!( + prepare_jinja(&glm_frontend, &glm_compiler, &glm_config, json!({ + "reasoning_effort": "none", + "chat_template_kwargs": {"enable_thinking": true} + })) + .starts_with("effort=max;think=true;") + ); + + // Nested OpenAI/Responses-style reasoning.effort works on Chat Completions when top-level is absent or null. + assert!(prepare_jinja(&glm_frontend, &glm_compiler, &glm_config, json!({"reasoning": {"effort": "low"}})).starts_with("effort=low;")); + assert!(prepare_jinja(&glm_frontend, &glm_compiler, &glm_config, json!({"reasoning": {"effort": "minimal"}})).starts_with("effort=low;")); + assert!(prepare_jinja(&glm_frontend, &glm_compiler, &glm_config, json!({"reasoning": {"effort": "medium"}})).starts_with("effort=high;")); + assert!(prepare_jinja(&glm_frontend, &glm_compiler, &glm_config, json!({"reasoning": {"effort": "high"}})).starts_with("effort=high;")); + assert!(prepare_jinja(&glm_frontend, &glm_compiler, &glm_config, json!({"reasoning": {"effort": "max"}})).starts_with("effort=max;")); + assert!( + prepare_jinja(&glm_frontend, &glm_compiler, &glm_config, json!({"reasoning": {"effort": "none"}})) + .starts_with("effort=max;think=false;") + ); + assert!( + prepare_jinja(&glm_frontend, &glm_compiler, &glm_config, json!({"reasoning_effort": null, "reasoning": {"effort": "high"}})) + .starts_with("effort=high;") + ); + assert!( + prepare_jinja(&glm_frontend, &glm_compiler, &glm_config, json!({"reasoning_effort": "low", "reasoning": {"effort": "high"}})) + .starts_with("effort=low;") + ); + assert!( + prepare_jinja(&glm_frontend, &glm_compiler, &glm_config, json!({ + "reasoning": {"effort": "high"}, + "chat_template_kwargs": {"reasoning_effort": "low"} + })) + .starts_with("effort=low;") + ); + + for bad in [json!("bogus"), json!(50)] { + assert!( + decode( + Protocol::Chat, + json!({"messages": [{"role": "user", "content": "Hi"}], "reasoning": {"effort": bad}}), + false, + ) + .is_err() + ); + } + + // 2. Qwen3.8-style strict Jinja template accepting only `low`, `medium`, `xhigh`. + let qwen_template = concat!( + "{%- set eff = reasoning_effort | default('xhigh') -%}", + "{%- if eff not in ['low', 'medium', 'xhigh'] -%}{{ raise_exception('Unexpected reasoning effort ' ~ eff) }}{%- endif -%}", + "effort={{ eff }};think={% if enable_thinking is defined and not enable_thinking %}false{% else %}true{% endif %};", + "{% for m in messages %}{{ m.content }}{% mark %}{% endfor %}" + ); + let (qwen_frontend, qwen_compiler, mut qwen_config) = renderer( + PromptEncoder::Jinja, + Some(qwen_template), + TemplateEncoding::Text, + ); + qwen_config.contract.frontend.rejected_tokens.clear(); + assert!(prepare_jinja(&qwen_frontend, &qwen_compiler, &qwen_config, json!({"reasoning_effort": "minimal"})).starts_with("effort=low;")); + assert!(prepare_jinja(&qwen_frontend, &qwen_compiler, &qwen_config, json!({"reasoning_effort": "low"})).starts_with("effort=low;")); + assert!(prepare_jinja(&qwen_frontend, &qwen_compiler, &qwen_config, json!({"reasoning_effort": "medium"})).starts_with("effort=medium;")); + assert!(prepare_jinja(&qwen_frontend, &qwen_compiler, &qwen_config, json!({"reasoning_effort": "high"})).starts_with("effort=medium;")); + assert!(prepare_jinja(&qwen_frontend, &qwen_compiler, &qwen_config, json!({"reasoning_effort": "xhigh"})).starts_with("effort=xhigh;")); + assert!(prepare_jinja(&qwen_frontend, &qwen_compiler, &qwen_config, json!({"reasoning_effort": "max"})).starts_with("effort=xhigh;")); + assert!(prepare_jinja(&qwen_frontend, &qwen_compiler, &qwen_config, json!({"reasoning_effort": "none"})).starts_with("effort=xhigh;think=false;")); + + // 3. TMLv0 (`Inkling 2`): Chat `medium` preserves native `0.7` while Responses `medium` stays `0.9`. + let tml_frontend = tml_frontend(false); + let mut tml_config = + crate::frontend::test_support::model_config(crate::model::testing::metadata()); + tml_config.contract.vocabulary = tml_frontend.tokenizer().get_vocab_size(true); + tml_config.contract.input_vocabulary = tml_config.contract.vocabulary; + let contracts_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/support/contracts/inkling2_frontend.json"); + let contracts: Value = + serde_json::from_slice(&std::fs::read(contracts_path).unwrap()).unwrap(); + tml_config.contract.frontend = serde_json::from_value(contracts["text"].clone()).unwrap(); + tml_config.eos_token_ids = vec![ + tml_frontend + .tokenizer() + .token_to_id("<|content_model_end_sampling|>") + .unwrap(), + ]; + let tml_compiler = GrammarCompiler::new( + tml_frontend.tokenizer(), + tml_config.contract.vocabulary, + &tml_config.eos_token_ids, + &crate::model::reasoning_delimiter_tokens(&tml_frontend, &tml_config.contract.frontend) + .unwrap(), + ) + .unwrap(); + let prepare_tml = |protocol: Protocol, body: Value| { + let decoded = decode(protocol, body, false).unwrap(); + crate::server::request::prepare_inference( + &tml_frontend, None, &tml_compiler, &tml_config, &decoded.request, 0, false, + ) + .unwrap() + .rendered_prompt + }; + let chat_tml = |extra: Value| { + let mut body = json!({"messages": [{"role": "user", "content": "Hello"}]}); + body.as_object_mut() + .unwrap() + .extend(extra.as_object().unwrap().clone()); + prepare_tml(Protocol::Chat, body) + }; + assert_eq!(chat_tml(json!({"reasoning_effort": "none"})), chat_tml(json!({"reasoning_effort": 0}))); + assert_eq!(chat_tml(json!({"reasoning_effort": "minimal"})), chat_tml(json!({"reasoning_effort": 0.1}))); + assert_eq!(chat_tml(json!({"reasoning_effort": "low"})), chat_tml(json!({"reasoning_effort": 0.2}))); + assert_eq!(chat_tml(json!({"reasoning_effort": "medium"})), chat_tml(json!({"reasoning_effort": 0.7}))); + assert_eq!(chat_tml(json!({"reasoning_effort": "high"})), chat_tml(json!({"reasoning_effort": 0.9}))); + assert_eq!(chat_tml(json!({"reasoning_effort": "xhigh"})), chat_tml(json!({"reasoning_effort": 0.99}))); + assert_eq!(chat_tml(json!({"reasoning_effort": "max"})), chat_tml(json!({"reasoning_effort": 0.99}))); + assert_eq!( + prepare_tml( + Protocol::Responses, + json!({"input": "Hello", "reasoning": {"effort": "medium"}}) + ), + chat_tml(json!({"reasoning_effort": 0.9})) + ); + + // 4. DeepSeek-V4.1 native encoder accepts normalized efforts, nested reasoning.effort, and numeric scores. + let (ds_frontend, ds_compiler, ds_config) = native(PromptEncoder::DeepseekV41); + let prepare_ds = |extra: Value| { + let mut body = json!({"messages": [{"role": "user", "content": "Hello"}]}); + body.as_object_mut() + .unwrap() + .extend(extra.as_object().unwrap().clone()); + let decoded = decode(Protocol::Chat, body, false).unwrap(); + crate::server::request::prepare_inference( + &ds_frontend, None, &ds_compiler, &ds_config, &decoded.request, 0, false, + ) + .unwrap() + .rendered_prompt + }; + let ds_none = prepare_ds(json!({"reasoning_effort": "none"})); + assert!(!ds_none.ends_with("")); + assert_eq!(prepare_ds(json!({"reasoning": {"effort": "none"}})), ds_none); + let ds_low = prepare_ds(json!({"reasoning_effort": "low"})); + assert_eq!(prepare_ds(json!({"reasoning_effort": "minimal"})), ds_low); + assert_eq!(prepare_ds(json!({"reasoning": {"effort": "minimal"}})), ds_low); + assert_eq!(prepare_ds(json!({"reasoning_effort": 50})), ds_low); + let ds_high = prepare_ds(json!({"reasoning_effort": "high"})); + assert_eq!(prepare_ds(json!({"reasoning_effort": "medium"})), ds_high); + assert_eq!(prepare_ds(json!({"reasoning": {"effort": "medium"}})), ds_high); + assert_eq!(prepare_ds(json!({"reasoning": {"effort": "high"}})), ds_high); + let ds_xhigh = prepare_ds(json!({"reasoning_effort": "xhigh"})); + assert!(ds_xhigh.contains("Reasoning Effort: 75")); + let ds_max = prepare_ds(json!({"reasoning_effort": "max"})); + assert!(ds_max.contains("Reasoning Effort: 100")); + assert_eq!(prepare_ds(json!({"reasoning": {"effort": "xhigh"}})), ds_max); + assert_eq!(prepare_ds(json!({"reasoning": {"effort": "max"}})), ds_max); + } } diff --git a/helios/src/server/request.rs b/helios/src/server/request.rs index 399e9fe3e..3cc9ea9e7 100644 --- a/helios/src/server/request.rs +++ b/helios/src/server/request.rs @@ -518,6 +518,7 @@ pub(super) fn template_inputs<'a>( let candidates: &[&str] = match effort { Effort::Minimal => &["minimal", "low"], Effort::Low => &["low"], + Effort::Medium => &["medium", "high"], Effort::High => &["high", "medium"], Effort::Max => &["max", "xhigh", "high", "medium"], };