Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 25 additions & 5 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `</parameter>` is closed by the next parameter or function boundary.
Literal outer closing tool tags (`</tool_call>` or `<tool_call|>`) appearing
inside open non-JSON argument values (`<arg_value>...</arg_value>`,
`<parameter=...>...</parameter>`, 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
Expand Down Expand Up @@ -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
Expand Down
33 changes: 24 additions & 9 deletions helios/src/frontend/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
214 changes: 200 additions & 14 deletions helios/src/output/argument_tags.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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<Option<Vec<(String, String)>>> {
fn parse_body(body: &str, tools: &[Value], eos: bool) -> Result<Candidate> {
let body = body.trim();
let split = body.find("<arg_key>").unwrap_or(body.len());
let name = body[..split].trim();
Expand Down Expand Up @@ -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("</arg_value>")
Expand All @@ -86,17 +82,20 @@ impl ArgumentTags {
rest = next;
continue;
}
let (value, tail) = value
.split_once("</arg_value>")
.ok_or("unterminated GLM argument value")?;
let Some((value, tail)) = value.split_once("</arg_value>") 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 {
arguments.insert_value(key.to_owned(), &parameter_value(value, schema)?)?;
}
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 {
Expand All @@ -106,13 +105,29 @@ impl ToolDialect for ArgumentTags {
const CLOSE: &'static str = "</tool_call>";

fn parse(body: &str, tools: &[Value]) -> Result<Vec<(String, String)>> {
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<Option<Vec<(String, String)>>> {
fn parse_candidate(body: &str, tools: &[Value]) -> Result<Candidate> {
Self::parse_body(body, tools, false)
}
fn scan_value_end(tail: &str) -> std::result::Result<usize, usize> {
const CLOSE: &str = "</arg_value>";
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<Vec<(String, String)>> {
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<bool> {
// Calls continue with the function name and an argument key or closing tag;
Expand Down Expand Up @@ -746,4 +761,175 @@ mod tests {
})
);
}

#[test]
fn literal_closing_tool_tag_inside_argument_values_parses_across_every_split() {
let cases: &[(&str, &[(&str, Value)])] = &[
(
"</think><tool_call>run<arg_key>text</arg_key><arg_value>grep </tool_call> pattern</arg_value></tool_call>",
&[("run", json!({"text": "grep </tool_call> pattern"}))],
),
(
"</think><tool_call>run<arg_key>text</arg_key><arg_value></tool_call></arg_value></tool_call>",
&[("run", json!({"text": "</tool_call>"}))],
),
(
r#"</think><tool_call>run<arg_key>text</arg_key><arg_value>match "</tool_call>" and '</tool_call>'</arg_value></tool_call>"#,
&[(
"run",
json!({"text": r#"match "</tool_call>" and '</tool_call>'"#}),
)],
),
(
r#"</think><tool_call>run<arg_key>count</arg_key><arg_value>3</arg_value><arg_key>options</arg_key><arg_value>{"end":"</tool_call>"}</arg_value><arg_key>text</arg_key><arg_value>after </tool_call> end</arg_value></tool_call>"#,
&[(
"run",
json!({"count": 3, "options": {"end": "</tool_call>"}, "text": "after </tool_call> end"}),
)],
),
(
"</think><tool_call>run<arg_key>text</arg_key><arg_value>a</tool_call>b</arg_value></tool_call><tool_call>run<arg_key>count</arg_key><arg_value>2</arg_value></tool_call>",
&[
("run", json!({"text": "a</tool_call>b"})),
("run", json!({"count": 2})),
],
),
(
"</think><tool_call>run<arg_key>text</arg_key><arg_value>a</tool_call>b</arg_value>",
&[("run", json!({"text": "a</tool_call>b"}))],
),
];
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 `<arg_value>` followed by `</tool_call>` and EOS still fails.
let unterminated = "</think><tool_call>run<arg_key>text</arg_key><arg_value>unfinished</tool_call>";
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 `</tool_call>` succeeds when closed, fails when outer `</tool_call>` 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 =
"</think><tool_call>strict_run<arg_key>text</arg_key><arg_value>a</tool_call>b</arg_value></tool_call>";
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":"a</tool_call>b"}"#
);

let mut parser = ArgumentTagOutput::new(OutputConfig {
tools: strict_tools,
..config()
});
parser
.push(Input::Text(
"</think><tool_call>strict_run<arg_key>text</arg_key><arg_value>a</tool_call>b</arg_value>",
))
.unwrap();
assert!(parser.finish(Termination::Eos).is_err());

// Single-character streaming handles literal `</tool_call>` inside `<arg_value>`.
let single_char_case =
"</think><tool_call>run<arg_key>text</arg_key><arg_value>grep </tool_call> α</arg_value></tool_call>";
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 </tool_call> α"}"#
);

// Non-EOS termination omits an incomplete call buffered past an inner `</tool_call>`.
for cause in [
Termination::OutputLimit,
Termination::UserStop,
Termination::Cancelled,
Termination::ExecutionError,
] {
let mut parser = ArgumentTagOutput::new(config());
parser
.push(Input::Text(
"</think><tool_call>run<arg_key>text</arg_key><arg_value>grep </tool_call> cut",
))
.unwrap();
assert!(parser.finish(cause).unwrap().is_empty(), "{cause:?}");
}

// Many literal `</tool_call>` markers inside one `<arg_value>` scan linearly without quadratic reparsing.
let repeated = "</tool_call>".repeat(40_000);
let large = format!(
"</think><tool_call>run<arg_key>text</arg_key><arg_value>{repeated}</arg_value></tool_call>"
);
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);
}
}
Loading