diff --git a/helios/src/grammar.rs b/helios/src/grammar.rs index 278c79c93..15420e44f 100644 --- a/helios/src/grammar.rs +++ b/helios/src/grammar.rs @@ -378,6 +378,17 @@ impl GrammarCompiler { self.marker("<|content_thinking|>"), self.marker("<|content_text|>"))); grammar.grammars[0].name = Some("answer".into()); let mut tools = vec![]; + if !envelope.tools.is_empty() { + let mut payload = TopLevelGrammar::from_json_schema(serde_json::json!({ + "type":"object", "properties":{"name":{"enum":&envelope.tools},"args":{"type":"object"}}, + "required":["name","args"], "additionalProperties":false, + })).grammars.remove(0); + payload.name = Some("payload_any".into()); + grammar.grammars.push(payload); + rules.push_str(&format!("tool_unnamed: {} @payload_any {end}\n", + self.marker("<|content_invoke_tool_json|>"))); + tools.push("tool_unnamed".into()); + } for (index, name) in envelope.tools.iter().enumerate() { let mut payload = TopLevelGrammar::from_json_schema(serde_json::json!({ "type":"object", "properties":{"name":{"const":name},"args":{"type":"object"}}, @@ -389,9 +400,9 @@ impl GrammarCompiler { self.marker(name), self.marker("<|content_invoke_tool_json|>"))); tools.push(format!("tool_{index}")); } - let ending = if tools.is_empty() { "answer" } else { + let ending = if tools.is_empty() { "answer".to_owned() } else { rules.push_str(&format!("tool: {}\ntools: tool ({restart} thinking* tool)* ({restart} thinking* answer)?\n", tools.join(" | "))); - "(answer | tools)" + format!("(answer ({restart} thinking* tool)* | tools)") }; rules.push_str(&format!("tail: thinking* {ending}\n")); match envelope.start { @@ -1916,6 +1927,74 @@ pub(crate) mod tests { } } } + + #[test] + fn content_headers_grammar_allows_preamble_before_tools() { + use crate::model::contract::ToolParserKind; + use crate::output::tagged::OutputStart; + + let markers = [ + "<|message_model|>", + "<|content_thinking|>", + "<|content_text|>", + "<|content_invoke_tool_json|>", + "<|end_message|>", + ]; + let tokenizer = byte_tokenizer_with(&markers); + let controls: Vec<_> = 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 envelope = OutputEnvelope { + recipient: Some(RecipientEnvelope { + syntax: ToolParserKind::TmlJson, + start: OutputStart::RecipientFrame, + tools: vec!["bash".into()], + }), + reasoning_end: None, + tool: None, + function: None, + tool_ends_reasoning: false, + tool_body_start: false, + response: None, + message_close: None, + }; + let thinking = "<|message_model|><|content_thinking|>Plan.<|end_message|>"; + let answer = "<|message_model|><|content_text|>Checking branch.<|end_message|>"; + let named_call = "<|message_model|>bash<|content_invoke_tool_json|>{\"name\":\"bash\",\"args\":{\"cmd\":\"git status\"}}<|end_message|>"; + let unnamed_call = "<|message_model|><|content_invoke_tool_json|>{\"name\":\"bash\",\"args\":{\"cmd\":\"git status\"}}<|end_message|>"; + let bad_unnamed_call = "<|message_model|><|content_invoke_tool_json|>{\"name\":\"other\",\"args\":{}}<|end_message|>"; + let bad_named_call = "<|message_model|>other<|content_invoke_tool_json|>{\"name\":\"bash\",\"args\":{}}<|end_message|>"; + for (text, valid) in [ + (answer.to_owned(), true), + (named_call.to_owned(), true), + (unnamed_call.to_owned(), true), + (format!("{named_call}{answer}"), true), + (format!("{unnamed_call}{answer}"), true), + (format!("{answer}{named_call}"), true), + (format!("{answer}{unnamed_call}"), true), + (format!("{thinking}{answer}{unnamed_call}"), true), + (format!("{answer}{thinking}{named_call}{unnamed_call}"), true), + (bad_unnamed_call.to_owned(), false), + (bad_named_call.to_owned(), false), + (thinking.to_owned(), false), + (format!("{answer}{unnamed_call}{answer}"), false), + ] { + let mut grammar = compiler + .compile_lark_in("start: /(?s:.+)/", Some(&envelope)) + .unwrap(); + let accepted = tokenizer + .encode(text.as_str(), false) + .unwrap() + .get_ids() + .iter() + .copied() + .chain([256]) + .all(|id| grammar.advance(id).is_ok()); + assert_eq!(accepted, valid, "{text}"); + } + } } #[cfg(all(test,feature="server"))] diff --git a/helios/src/grammar/strict.rs b/helios/src/grammar/strict.rs index d7435c46b..638b76460 100644 --- a/helios/src/grammar/strict.rs +++ b/helios/src/grammar/strict.rs @@ -1563,6 +1563,7 @@ impl GrammarCompiler { )); } let mut tool_rules = Vec::new(); + let mut payload_refs = Vec::new(); for (index, tool) in plan.tools.iter().enumerate() { let wrapper = match &tool.strict_schema { Some(schema) => embed_schema_in_tml_wrapper(&tool.name, schema), @@ -1582,6 +1583,7 @@ impl GrammarCompiler { .remove(0); payload.name = Some(format!("payload_{index}")); subgrammars.push(payload); + payload_refs.push(format!("@payload_{index}")); rules.push_str(&format!( "tool_{index}: {} {} @payload_{index} {end}\n", self.marker(&tool.name), @@ -1594,6 +1596,12 @@ impl GrammarCompiler { "strict tool grammar requires at least one active tool", )); } + rules.push_str(&format!( + "tool_unnamed: {} ({}) {end}\n", + self.marker("<|content_invoke_tool_json|>"), + payload_refs.join(" | "), + )); + tool_rules.push("tool_unnamed".into()); rules.push_str(&format!("tool: {}\n", tool_rules.join(" | "))); if plan.single_call { rules.push_str(&format!("tools: tool ({restart} thinking* answer)?\n")); @@ -1603,9 +1611,11 @@ impl GrammarCompiler { )); } let ending = if plan.require_call { - "tools" + "tools".to_owned() + } else if plan.single_call { + format!("(answer ({restart} thinking* tool)? | tools)") } else { - "(answer | tools)" + format!("(answer ({restart} thinking* tool)* | tools)") }; rules.push_str(&format!("tail: thinking* {ending}\n")); match recipient.start { @@ -4121,6 +4131,16 @@ mod tests { valid: "weather<|content_invoke_tool_json|>{\"name\":\"weather\",\"args\":{\"value\":2}}<|end_message|>", invalid: "weather<|content_invoke_tool_json|>{\"name\":\"weather\",\"args\":{\"value\":4}}<|end_message|>", }, + Case { + name: "TML_unnamed", + kind: ToolParserKind::TmlJson, + separator: "", + start: OutputStart::RecipientHeader, + controls: &CONTROL_MARKERS, + constraint: Constraint::NumericRange, + valid: "<|content_invoke_tool_json|>{\"name\":\"weather\",\"args\":{\"value\":2}}<|end_message|>", + invalid: "<|content_invoke_tool_json|>{\"name\":\"weather\",\"args\":{\"value\":4}}<|end_message|>", + }, ]; for case in cases { @@ -4501,4 +4521,116 @@ mod tests { false, ); } + + #[test] + fn strict_tml_grammar_allows_unnamed_headers_and_preamble_before_tools() { + use crate::model::contract::{ToolParser, ToolParserKind}; + use crate::output::{ + OutputConfig, OutputPipeline, + tagged::{OutputConfig as TaggedConfig, OutputStart}, + tml::CONTROL_MARKERS, + }; + + let weather_schema = json!({ + "type": "object", + "properties": {"value": {"type": "integer", "minimum": 1, "maximum": 3}}, + "required": ["value"], + "additionalProperties": false + }); + let lookup_schema = json!({ + "type": "object", + "properties": {"query": {"type": "string", "minLength": 2}}, + "required": ["query"], + "additionalProperties": false + }); + 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 mut syntax = crate::model::testing::metadata().frontend; + syntax.reasoning = None; + syntax.tools = Some(ToolParser { + kind: ToolParserKind::TmlJson, + wrapping_newlines: 0, + tag_separator: String::new(), + }); + let config = OutputConfig { + syntax, + control_tokens: controls.clone(), + content: TaggedConfig { + structured: false, + start: OutputStart::RecipientHeader, + tools: vec![ + json!({"type":"function","function":{"name":"weather","parameters":weather_schema}}), + json!({"type":"function","function":{"name":"lookup","parameters":lookup_schema}}), + ], + }, + }; + let envelope = OutputPipeline::grammar_envelope(&config).unwrap(); + let encode = |wire: &str| { + let mut tokens = Vec::new(); + let mut rest = wire; + while let Some((at, id, marker)) = controls + .iter() + .filter_map(|(id, marker)| { + rest.find(marker).map(|at| (at, *id, marker.as_str())) + }) + .min_by_key(|(at, _, _)| *at) + { + tokens.extend(rest[..at].bytes().map(u32::from)); + tokens.push(id); + rest = &rest[at + marker.len()..]; + } + tokens.extend(rest.bytes().map(u32::from)); + tokens + }; + let accepts = |single_call: bool, wire: &str| { + let plan = ToolGrammarPlan { + tools: vec![ + StrictToolSpec { + name: "weather".into(), + strict_schema: Some(&weather_schema), + }, + StrictToolSpec { + name: "lookup".into(), + strict_schema: Some(&lookup_schema), + }, + ], + syntax: Some((ToolParserKind::TmlJson, 0, String::new())), + dsml_token: None, + allow_undeclared: false, + require_call: false, + single_call, + }; + let mut g = compiler + .compile_with_strict_tools(None, Some(&envelope), &plan) + .unwrap(); + encode(wire) + .into_iter() + .chain([256]) + .all(|token| g.advance(token).is_ok()) + && g.is_stopped() + }; + + // Multi-tool unnamed strict headers accept valid arguments for either tool + assert!(accepts(false, r#"<|content_invoke_tool_json|>{"name":"weather","args":{"value":2}}<|end_message|>"#)); + assert!(accepts(false, r#"<|content_invoke_tool_json|>{"name":"lookup","args":{"query":"ok"}}<|end_message|>"#)); + // Unnamed strict headers reject schema violations and undeclared tools + assert!(!accepts(false, r#"<|content_invoke_tool_json|>{"name":"weather","args":{"value":9}}<|end_message|>"#)); + assert!(!accepts(false, r#"<|content_invoke_tool_json|>{"name":"lookup","args":{"query":"x"}}<|end_message|>"#)); + assert!(!accepts(false, r#"<|content_invoke_tool_json|>{"name":"other","args":{}}<|end_message|>"#)); + // Named strict headers reject header/body mismatch + assert!(!accepts(false, r#"weather<|content_invoke_tool_json|>{"name":"lookup","args":{"query":"ok"}}<|end_message|>"#)); + // Visible preamble before unnamed strict tool calls is accepted; single_call caps at one tool + let preamble_one = r#"<|content_text|>Checking now.<|end_message|><|message_model|><|content_invoke_tool_json|>{"name":"weather","args":{"value":2}}<|end_message|>"#; + let preamble_two = r#"<|content_text|>Checking both.<|end_message|><|message_model|><|content_invoke_tool_json|>{"name":"weather","args":{"value":2}}<|end_message|><|message_model|><|content_invoke_tool_json|>{"name":"lookup","args":{"query":"ok"}}<|end_message|>"#; + let preamble_bad = r#"<|content_text|>Checking now.<|end_message|><|message_model|><|content_invoke_tool_json|>{"name":"weather","args":{"value":9}}<|end_message|>"#; + assert!(accepts(false, preamble_one)); + assert!(accepts(false, preamble_two)); + assert!(!accepts(false, preamble_bad)); + assert!(accepts(true, preamble_one)); + assert!(!accepts(true, preamble_two)); + } } diff --git a/helios/src/output/tml.rs b/helios/src/output/tml.rs index 5bd5d7a28..2ff009277 100644 --- a/helios/src/output/tml.rs +++ b/helios/src/output/tml.rs @@ -75,6 +75,13 @@ enum State { Closed, } +#[derive(Clone, Copy, PartialEq)] +enum AnswerState { + Empty, + HeaderWithoutContent, + Emitted, +} + /// The parser start after a prompt, from the last framing control token in it. pub(crate) fn prompt_start(prompt: &[u32], control_tokens: &[(u32, String)]) -> OutputStart { let marker = prompt.iter().rev().find_map(|id| { @@ -94,6 +101,7 @@ pub(crate) fn prompt_start(prompt: &[u32], control_tokens: &[(u32, String)]) -> pub struct TmlOutput { state: State, + answer: AnswerState, /// Escaped generated text with framing markers inserted only for control tokens. buffer: String, name: Option, @@ -128,6 +136,7 @@ fn first(buffer: &str, markers: &[&'static str]) -> Option<(usize, &'static str) impl TmlOutput { pub fn new(config: OutputConfig, control_tokens: Vec<(u32, String)>) -> Self { Self { + answer: AnswerState::Empty, state: match config.start { OutputStart::RecipientHeader => State::Header { model: true }, OutputStart::RecipientFrame => State::Frame, @@ -207,6 +216,7 @@ impl TmlOutput { if kind == Body::Thinking { events.push(Event::Reasoning(text)); } else { + self.answer = AnswerState::Emitted; self.spans.push(Some(start..start + text.len())); events.push(Event::Content(text)); } @@ -269,6 +279,13 @@ impl TmlOutput { }; let name = unescape(&self.buffer[..at]); self.buffer.drain(..at + marker.len()); + if model + && at > 0 + && matches!(marker, END | TURN_END) + && self.answer == AnswerState::Empty + { + self.answer = AnswerState::HeaderWithoutContent; + } self.state = match marker { MODEL => State::Header { model: true }, USER | SYSTEM | TOOL => State::Header { model: false }, @@ -315,12 +332,13 @@ impl TmlOutput { /// A registered invocation, or its payload as visible text when TMLv0 rejects it. fn call_or_text(&mut self, body: &str, start: usize) -> Vec { - if let Some(events) = self.call(body) { - return events; - } if body.is_empty() { return vec![]; } + self.answer = AnswerState::Emitted; + if let Some(events) = self.call(body) { + return events; + } self.spans.push(Some(start..start + body.len())); vec![Event::Content(body.to_owned())] } @@ -378,6 +396,9 @@ impl TmlOutput { // An unterminated header carries no content. self.buffer.clear(); self.state = State::Closed; + if cause == Termination::Eos && self.answer == AnswerState::HeaderWithoutContent { + return Err("TML model header closed without a content kind and the turn produced no answer or tool call".into()); + } Ok(events) } } @@ -565,6 +586,73 @@ mod tests { assert_eq!(run(frame, &[MODEL, "lookup"], Termination::Eos), Parsed::default()); } + #[test] + fn nonempty_model_header_closed_without_a_content_kind_fails_at_eos() { + for fragmented in [false, true] { + for deliver_turn_end in [false, true] { + let mut p = parser(OutputStart::RecipientFrame); + let mut events = vec![]; + for piece in [MODEL, THINK, "Inspect the branch.", END, MODEL, + r#"bash"description":"Inspect branch"}}"#, END] { + if CONTROL_MARKERS.contains(&piece) { + events.extend(feed(&mut p, piece, fragmented).unwrap()); + } else { + events.extend(p.push(Input::Text(piece)).unwrap()); + } + } + if deliver_turn_end { + events.extend(feed(&mut p, TURN_END, fragmented).unwrap()); + } + assert_eq!(events, vec![Event::Reasoning("Inspect the branch.".into())]); + let error = p.finish(Termination::Eos).unwrap_err(); + assert!(error.to_string().contains("without a content kind"), "{error}"); + } + let mut p = parser(OutputStart::RecipientFrame); + let mut events = vec![]; + for piece in [MODEL, THINK, "Inspect the branch.", END, MODEL, + r#"bash"description":"Inspect branch"}}"#, TURN_END] { + if CONTROL_MARKERS.contains(&piece) { + events.extend(feed(&mut p, piece, fragmented).unwrap()); + } else { + events.extend(p.push(Input::Text(piece)).unwrap()); + } + } + assert_eq!(events, vec![Event::Reasoning("Inspect the branch.".into())]); + let error = p.finish(Termination::Eos).unwrap_err(); + assert!(error.to_string().contains("without a content kind"), "{error}"); + } + } + + #[test] + fn a_closed_untyped_header_allows_visible_content_and_completed_calls() { + let frame = OutputStart::RecipientFrame; + let header = [MODEL, "untyped", END]; + let answer = [MODEL, TEXT, "done", END]; + let call = [MODEL, "lookup", JSON_CALL, r#"{"name":"lookup","args":{}}"#, END]; + let invalid_call = [MODEL, JSON_CALL, "invalid JSON", END]; + for valid in [&answer[..], &call[..], &invalid_call[..]] { + let expected = run(frame, valid, Termination::Eos); + for order in [[&header[..], valid], [valid, &header[..]]] { + assert_eq!(run(frame, &order.concat(), Termination::Eos), expected); + } + } + } + + #[test] + fn empty_model_headers_other_roles_and_external_stops_keep_their_termination() { + let frame = OutputStart::RecipientFrame; + for pieces in [vec![MODEL, END], vec![USER, "name", END], vec![TOOL, "lookup", END], + vec![SYSTEM, "name", END]] { + assert_eq!(run(frame, &pieces, Termination::Eos), Parsed::default()); + } + for cause in [Termination::OutputLimit, Termination::UserStop, Termination::Cancelled, + Termination::ExecutionError] { + assert_eq!(run(frame, &[MODEL, "untyped", END], cause), Parsed::default()); + } + assert_eq!(run(frame, &[MODEL, THINK, "t", END, TURN_END], Termination::Eos), + ("t".into(), String::new(), vec![])); + } + #[test] fn prompt_tail_selects_the_parser_start() { let controls: Vec<_> = CONTROL_MARKERS diff --git a/helios/src/server/request/tml_tests.rs b/helios/src/server/request/tml_tests.rs index bfbfa18f5..07c5cab4a 100644 --- a/helios/src/server/request/tml_tests.rs +++ b/helios/src/server/request/tml_tests.rs @@ -243,6 +243,44 @@ fn parse(inkling: &Inkling, case: &Value) -> (String, String, Vec<(String, Value (reasoning, content, calls) } +#[test] +#[ignore = "requires FLARE_INKLING2_TEST_SNAPSHOT with the Inkling 2 tokenizer"] +fn a_model_frame_without_a_content_kind_reports_a_failed_response() { + use crate::server::output::Decoder; + use crate::server::protocol::{Encoder, PromptUsage}; + + let inkling = Inkling::load(&golden()); + let request = inkling.request(Protocol::Responses, json!({ + "input": "Inspect the branch.", + "tools": [{"type":"function","name":"bash","parameters":{"type":"object"}}] + })).unwrap(); + let prepared = prepare_inference(&inkling.frontend, None, &inkling.compiler, &inkling.config, + &request, 0, false).unwrap(); + let mut decoder = Decoder::::new( + &inkling.frontend, &inkling.config.eos_token_ids, prepared.output); + let mut encoder = Encoder::new(Protocol::Responses, "test".into(), inkling.config.model_id.clone(), + 0, 1, vec![PromptUsage { tokens: prepared.prompt.tokens.len(), image_tokens: 0 }], + request.tools, request.tool_choice, true, true, json!({})); + + let mut tokens = vec![200001, 200008]; // Model reasoning frame + tokens.extend(inkling.frontend.encode("Inspect the branch.", false).unwrap()); + tokens.extend([END_MESSAGE, 200001]); + // Captured ordinary IDs between the second model-frame opener and its end. + tokens.extend([33131, 1, 70469, 1, 25, 1, 3960, 150309, 12, 68206, 155417, 152664, 1, 92, 92]); + tokens.extend([END_MESSAGE, 200006]); + for id in tokens { + let events = decoder.push(id).unwrap(); + assert!(events.iter().all(|event| matches!(event, Event::Reasoning(_)))); + encoder.apply(0, events).unwrap(); + } + let error = decoder.finish(Termination::Eos).unwrap_err(); + let frame = encoder.failure(&error); + assert_eq!(frame.event.as_deref(), Some("response.failed")); + assert_eq!(frame.data["response"]["status"], "failed"); + assert_eq!(frame.data["response"]["error"]["code"], "server_error"); + assert!(error.to_string().contains("without a content kind"), "{error}"); +} + #[test] #[ignore = "requires FLARE_INKLING2_TEST_SNAPSHOT with the Inkling 2 tokenizer"] fn outputs_match_reference_parses() { @@ -351,3 +389,90 @@ fn structured_output_grammars_constrain_frames() { assert_eq!(accepted, valid, "{text}"); } } + +#[test] +#[ignore = "requires FLARE_INKLING2_TEST_SNAPSHOT with an Inkling 2 tokenizer"] +fn inkling_stress_untyped_closed_header_must_surface_failure() { + use crate::server::output::Decoder; + use crate::server::protocol::{Encoder, PromptUsage}; + + let inkling = Inkling::load(&golden()); + let request = inkling.request(Protocol::Responses, json!({ + "input":"Inspect the branch.", + "tools":[{"type":"function","name":"bash","parameters":{"type":"object"}}], + "tool_choice":"auto" + })).unwrap(); + let prepared = prepare_inference( + &inkling.frontend, None, &inkling.compiler, &inkling.config, &request, 0, false, + ).unwrap(); + let mut decoder = Decoder::::new( + &inkling.frontend, &inkling.config.eos_token_ids, prepared.output, + ); + let mut encoder = Encoder::new( + Protocol::Responses, "stress".into(), inkling.config.model_id.clone(), 0, 1, + vec![PromptUsage { tokens: prepared.prompt.tokens.len(), image_tokens: 0 }], + request.tools, request.tool_choice, true, true, json!({}), + ); + + // A short valid reasoning frame, then the exact captured 18-token suffix. + let mut ids = vec![200001, 200008]; + ids.extend(inkling.frontend.encode("Inspect the branch.", false).unwrap()); + ids.push(END_MESSAGE); + ids.extend([ + 200001, 33131, 1, 70469, 1, 25, 1, 3960, 150309, 12, 68206, 155417, + 152664, 1, 92, 92, END_MESSAGE, 200006, + ]); + let decoded: crate::Result<()> = (|| { + for id in ids { + let events = decoder.push(id)?; + assert!(events.iter().all(|e| matches!(e, Event::Reasoning(_)))); + encoder.apply(0, events)?; + } + let last = decoder.finish(Termination::Eos)?; + assert!(last.iter().all(|e| matches!(e, Event::Reasoning(_)))); + Ok(()) + })(); + let error = decoded.expect_err("malformed terminal header silently disposed of the action"); + let terminal = encoder.failure(&error); + assert_eq!(terminal.event.as_deref(), Some("response.failed")); + assert_eq!(terminal.data["response"]["status"], "failed"); +} + +#[test] +#[ignore = "requires FLARE_INKLING2_TEST_SNAPSHOT with an Inkling 2 tokenizer"] +fn inkling_stress_custom_grammar_preamble_then_tool() { + let inkling = Inkling::load(&golden()); + let preamble = "I'll start by exploring the workspace and the PR."; + let text = format!("<|message_model|><|content_text|>{preamble}<|end_message|>"); + let call = concat!( + "<|message_model|>bash<|content_invoke_tool_json|>", + r#"{"name":"bash","args":{"command":"git status","description":"Inspect branch"}}"#, + "<|end_message|>", + ); + let preamble_then_call = format!("{text}{call}"); + let mut ids = inkling.frontend.encode(&preamble_then_call, false).unwrap(); + ids.push(200006); + let fixture = json!({"output_ids":ids,"tools":["bash"],"finish":"eos"}); + let (_, parsed_text, calls) = parse(&inkling, &fixture); + assert_eq!(parsed_text, preamble); + assert_eq!(calls, vec![("bash".to_owned(), + json!({"command":"git status","description":"Inspect branch"}))]); + + let request = inkling.request(Protocol::Responses, json!({ + "input":"Inspect the branch.", + "tools":[{"type":"function","name":"bash","parameters":{"type":"object"}}], + "tool_choice":"auto","grammar":"start: /(?s:.+)/" + })).unwrap(); + let accepts = |frames: &str| { + let mut prepared = prepare_inference( + &inkling.frontend, None, &inkling.compiler, &inkling.config, &request, 0, false, + ).unwrap(); + let grammar = prepared.prompt.grammar.as_mut().unwrap(); + inkling.frontend.encode(frames, false).unwrap().into_iter().chain([200006]) + .all(|id| grammar.advance(id).is_ok()) + }; + assert!(accepts(&text)); + assert!(accepts(call)); + assert!(accepts(&format!("{call}{text}"))); + assert!(accepts(&preamble_then_call), "answer before a valid tool call rejected"); +}