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
105 changes: 105 additions & 0 deletions helios/src/grammar/strict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3816,6 +3816,111 @@ mod tests {
}
}

#[test]
fn tml_strict_parser_preserves_30_digit_integers() {
let tokenizer = byte_tokenizer_with(&CONTROL_MARKERS);
let controls: Vec<_> = CONTROL_MARKERS
.iter()
.map(|marker| (tokenizer.token_to_id(marker).unwrap(), (*marker).to_owned()))
.collect();
let compiler = GrammarCompiler::new(&tokenizer, 320, &[256, 257], &controls).unwrap();
let big = "123456789012345678901234567890";
let big_schema = json!({
"type": "object",
"$defs": {"BigInt": {"type": "integer"}},
"properties": {
"top": {"type": "integer"},
"via_any": {"anyOf": [{"type": "integer"}, {"type": "null"}]},
"via_ref": {"$ref": "#/$defs/BigInt"},
"nested": {
"type": "object",
"properties": {
"id": {"type": "integer"},
"arr": {"type": "array", "items": {"type": "integer"}}
},
"required": ["id", "arr"],
"additionalProperties": false
}
},
"required": ["top", "via_any", "via_ref", "nested"],
"additionalProperties": false
});
let validator = validate_strict_tool_schema(&compiler, "audit", &big_schema).unwrap();
let mut syn = crate::model::testing::metadata().frontend;
syn.reasoning = None;
syn.tools = Some(ToolParser {
kind: ToolParserKind::TmlJson,
wrapping_newlines: 0,
tag_separator: String::new(),
});
let mut cfg = OutputConfig {
syntax: syn,
control_tokens: controls.clone(),
content: TaggedConfig {
structured: false,
start: OutputStart::RecipientHeader,
tools: vec![json!({
"type": "function",
"function": {"name": "audit", "strict": true, "parameters": big_schema}
})],
},
};
let env = OutputPipeline::grammar_envelope(&cfg).unwrap();
let plan = ToolGrammarPlan {
tools: vec![StrictToolSpec {
name: "audit".into(),
strict_schema: Some(&big_schema),
}],
syntax: Some((ToolParserKind::TmlJson, 0, String::new())),
dsml_token: None,
allow_undeclared: false,
require_call: true,
single_call: true,
};
let mut grammar = compiler
.compile_presented_strict_tools(None, Some(&env), &plan, Some(&mut cfg.content))
.unwrap();
let invoke_id = tokenizer.token_to_id("<|content_invoke_tool_json|>").unwrap();
let end_id = tokenizer.token_to_id("<|end_message|>").unwrap();
let payload = format!(
r#"{{"name":"audit","args":{{"top":{big},"via_any":{big},"via_ref":{big},"nested":{{"id":{big},"arr":[{big}]}}}}}}"#
);
for token in b"audit"
.iter()
.copied()
.map(u32::from)
.chain([invoke_id])
.chain(payload.bytes().map(u32::from))
.chain([end_id, 256])
{
grammar.advance(token).unwrap();
}
assert!(grammar.is_stopped());

let mut pipe = OutputPipeline::new(cfg);
let mut evs = pipe.push(Input::Text("audit")).unwrap();
evs.extend(pipe.push(Input::Token(invoke_id)).unwrap());
evs.extend(pipe.push(Input::Text("<|content_invoke_tool_json|>")).unwrap());
evs.extend(pipe.push(Input::Text(&payload)).unwrap());
evs.extend(pipe.push(Input::Token(end_id)).unwrap());
evs.extend(pipe.push(Input::Text("<|end_message|>")).unwrap());
evs.extend(pipe.finish(Termination::Eos).unwrap());

let raw_args = evs
.into_iter()
.find_map(|ev| match ev {
Event::ToolArguments { text, .. } => Some(text),
_ => None,
})
.expect("expected TML strict tool arguments");
validator.validate(&raw_args).unwrap();
assert_eq!(
raw_args.matches(big).count(),
5,
"TmlJson lost 30-digit precision: {raw_args}"
);
}

#[test]
fn glm_required_parallel_grammar_rejects_prose_and_accepts_multiple_calls() {
let compiler = GrammarCompiler::new(&byte_tokenizer(), 320, &[256, 257], &[]).unwrap();
Expand Down
51 changes: 41 additions & 10 deletions helios/src/output/tml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ use super::{
tagged::{OutputConfig, OutputStart},
};
use crate::Result;
use serde_json::Value;
use serde::Deserialize;
use serde_json::{Value, value::RawValue};
use std::collections::VecDeque;

const MODEL: &str = "<|message_model|>";
Expand Down Expand Up @@ -339,16 +340,22 @@ impl TmlOutput {
}

fn call(&mut self, body: &str) -> Option<Vec<Event>> {
let value: Value = serde_json::from_str(body).ok()?;
let object = value.as_object()?;
let name = object.get("name")?.as_str()?;
let args = object.get("args").filter(|v| v.is_object())?;
if object.len() != 2
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawCall<'a> {
name: String,
#[serde(borrow)]
args: &'a RawValue,
}

let parsed: RawCall<'_> = serde_json::from_str(body).ok()?;
let args = parsed.args.get().trim();
if !args.starts_with('{')
|| !self
.tools
.iter()
.any(|tool| tool["function"]["name"] == name)
|| self.name.as_ref().is_some_and(|header| header != name)
.any(|tool| tool["function"]["name"] == parsed.name)
|| self.name.as_ref().is_some_and(|header| header != &parsed.name)
{
return None;
}
Expand All @@ -357,12 +364,12 @@ impl TmlOutput {
Some(vec![
Event::ToolBegin {
index,
name: name.to_owned(),
name: parsed.name,
id: None,
},
Event::ToolArguments {
index,
text: args.to_string(),
text: args.to_owned(),
},
Event::ToolEnd { index },
])
Expand Down Expand Up @@ -609,4 +616,28 @@ mod tests {
.expect("oversized TML header must fail");
assert!(error.to_string().contains("1 MiB"), "{error}");
}

#[test]
fn call_preserves_raw_json_arguments_including_arbitrary_precision_integers() {
let big = "123456789012345678901234567890";
let args = format!(r#"{{"z":{big},"a":-999999999999999999999999999999,"nested":{{"id":{big}}}}}"#);
let payload = format!(r#"{{"args":{args},"name":"lookup"}}"#);
let parsed = run(
OutputStart::RecipientFrame,
&[MODEL, "lookup", JSON_CALL, &payload, END],
Termination::Eos,
);
assert_eq!(parsed.2, vec![("lookup".into(), args)]);

let duplicate = r#"{"name":"lookup","name":"lookup","args":{}}"#;
assert_eq!(
run(
OutputStart::RecipientFrame,
&[MODEL, "lookup", JSON_CALL, duplicate, END],
Termination::Eos,
)
.1,
duplicate
);
}
}
91 changes: 91 additions & 0 deletions tests/server/test_inkling2.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,97 @@ def test_tml_tool_call_and_result(service):
assert "21" in answer(result)


def test_strict_tml_tool_calls_and_truncation(service):
url = os.environ["FLARE_INKLING2_TEST_URL"].rstrip("/")
model_id = json.load(urllib.request.urlopen(url + "/v1/models", timeout=10))["data"][0]["id"]
big = "123456789012345678901234567890"
schema = dict(
type="object",
properties=dict(big_id=dict(type="integer"), city=dict(type="string", minLength=2)),
required=["big_id", "city"],
additionalProperties=False,
)
chat_tools = [dict(type="function", function=dict(
name="record_city", description="Record an audit ID and city.", strict=True, parameters=schema))]
prompt = f"Call record_city with big_id={big} and city='Paris'."

# Chat Completions buffered: preserves 30-digit integer verbatim and property order.
buffered = service(prompt, tools=chat_tools, tool_choice="required")
call, = buffered["choices"][0]["message"]["tool_calls"]
assert call["function"]["name"] == "record_city"
assert big in call["function"]["arguments"]
parsed = json.loads(call["function"]["arguments"])
assert list(parsed.keys()) == ["big_id", "city"] and parsed["city"] == "Paris"

# Chat Completions streamed: buffers strict arguments into one validated delta.
events = service(prompt, tools=chat_tools, tool_choice="required", stream=True)
arg_chunks = [
tc["function"]["arguments"]
for event in events
for choice in event.get("choices", [])
for tc in choice.get("delta", {}).get("tool_calls") or []
if tc.get("function", {}).get("arguments")
]
assert len(arg_chunks) == 1 and big in arg_chunks[0], arg_chunks

# Chat Completions max_tokens truncation omits unfinished strict calls cleanly.
trunc_req = urllib.request.Request(
url + "/v1/chat/completions",
json.dumps(dict(
model=model_id,
messages=[dict(role="user", content=prompt)],
tools=chat_tools,
tool_choice="auto",
reasoning_effort="none",
max_tokens=10,
seed=1234,
)).encode(),
{"Content-Type": "application/json"},
)
with urllib.request.urlopen(trunc_req, timeout=120) as resp:
trunc = json.load(resp)
assert trunc["choices"][0]["finish_reason"] == "length"
assert not trunc["choices"][0]["message"].get("tool_calls")

# Responses buffered + max_output_tokens truncation.
resp_tools = [dict(type="function", name="record_city", description="Record an audit ID and city.",
strict=True, parameters=schema)]
resp_req = urllib.request.Request(
url + "/v1/responses",
json.dumps(dict(
model=model_id,
input=prompt,
tools=resp_tools,
tool_choice="required",
reasoning=dict(effort="none"),
max_output_tokens=256,
)).encode(),
{"Content-Type": "application/json"},
)
with urllib.request.urlopen(resp_req, timeout=120) as resp:
resp_body = json.load(resp)
assert resp_body["status"] == "completed"
fcalls = [item for item in resp_body["output"] if item["type"] == "function_call"]
assert len(fcalls) == 1 and big in fcalls[0]["arguments"]

resp_trunc_req = urllib.request.Request(
url + "/v1/responses",
json.dumps(dict(
model=model_id,
input=prompt,
tools=resp_tools,
tool_choice="auto",
reasoning=dict(effort="none"),
max_output_tokens=10,
)).encode(),
{"Content-Type": "application/json"},
)
with urllib.request.urlopen(resp_trunc_req, timeout=120) as resp:
resp_trunc = json.load(resp)
assert resp_trunc["status"] == "incomplete"
assert not [item for item in resp_trunc["output"] if item["type"] == "function_call"]


def test_structured_response(service):
schema = dict(type="object", properties=dict(result=dict(type="integer")), required=["result"],
additionalProperties=False)
Expand Down