diff --git a/docs/api.md b/docs/api.md index ab3176c96..8920e09d5 100644 --- a/docs/api.md +++ b/docs/api.md @@ -537,19 +537,34 @@ and the call index). This format stays within the 40-character OpenAI Chat Completions maximum and the `[a-zA-Z0-9_-]+` character set accepted across Chat Completions, Responses, and Messages, keeping synthesized identifiers distinct across calls, choices, requests, server restarts, and hosts. Tool arguments are -JSON objects, bounded to 8 MiB. The model parsers buffer tool envelopes until -they are complete, so argument events do not imply incremental generation of an -unfinished call. Truncated tool envelopes are omitted and the response reports -its output limit. At natural completion, tagged tool parsers accept a non-strict -call whose inner arguments are structurally complete and self-delimited when -only its closing wrapper tag is omitted; undecided openers, bare headers -without a closing argument delimiter, unclosed arguments, trailing text, and -unclosed strict calls remain errors. +JSON objects, bounded to 8 MiB. A DeepSeek DSML call is announced once its name +is complete, and a function call's argument text is published while the model +writes it, so concatenating the argument fragments of a function call +reproduces its stored arguments byte for byte. A custom tool call publishes its +input once its arguments are accepted, because the client's text is the input +inside the argument object rather than the object itself. The tagged tool +parsers publish a call only when its envelope is complete. An announced call cut +off before completion is omitted from a buffered response for every termination +other than natural end-of-sequence, and a response that completes reports the +termination's finish reason; only an output-limit termination reports the +output limit. On the Responses wire the closing frame of such an item reports +status `incomplete`, and a truncated custom call's item carries an empty input +because its arguments never formed. When the omitted call leaves no completed +call, a `required` or named `tool_choice` fails the response instead, producing +HTTP 500 for buffered requests or a terminal error event for streams. A client +that received fragments of such a call has already seen a call that cannot +complete. At natural completion, tagged tool parsers accept a +non-strict call whose inner arguments are structurally complete and +self-delimited when only its closing wrapper tag is omitted; undecided openers, +bare headers without a closing argument delimiter, unclosed arguments, trailing +text, and unclosed strict calls remain errors. DeepSeek reasoning and both DSML tool syntaxes use the pinned official `deepseek-recipe` state machine. Helios adapts its actions into the same neutral -events, validates nonempty tool names and JSON objects with nonempty, unique -argument names, and publishes each call when its arguments complete. A parameter +events and validates nonempty tool names and JSON objects with nonempty, unique +argument names. A call ends after its argument object validates. A +`string="false"` value stays private until the parser decides whether to retain +it as text, so published fragments never change. A parameter tag that closes before its string attribute is discarded, so the following well-formed parameter is parsed normally. A parameter marked `string="false"` keeps its JSON type if its text decodes as one value @@ -557,8 +572,11 @@ inside the argument object. If decoding fails, Helios retains the original text as a JSON string. This includes valid JSON exceeding 126 levels of array or object nesting within the parameter. The combined size of the UTF-8 tool name and complete JSON argument object is limited to 1 MiB, including escapes -and delimiters. Helios rejects a larger call before publishing it. Closing the -outer calls block ends parsed output and discards subsequent generated text. +and delimiters. The bound is enforced on the append that crosses it, after the +call name and earlier argument fragments were published and are not retracted, +so an oversized call never completes and cannot appear in a buffered body. +Closing the outer calls block ends parsed output and discards subsequent +generated text. The official parser owns markup recognition, including its tolerance of omitted or partial tags. Structured answers become verbatim when ordinary answer content begins, preserving scalar JSON, Lark output, and markup inside string values. diff --git a/helios/src/output/dsml.rs b/helios/src/output/dsml.rs index 5393a6258..c926c4d86 100644 --- a/helios/src/output/dsml.rs +++ b/helios/src/output/dsml.rs @@ -35,6 +35,7 @@ struct Call { literal: Option, literal_quoted: bool, literal_escaped: bool, + published_argument_bytes: usize, } impl Call { @@ -45,6 +46,23 @@ impl Call { Ok(()) } + /// Publishes argument bytes appended since the previous call. + /// + /// A value whose `string="false"` text may still be rewritten stays private + /// until `close_literal` decides, so published text never changes afterwards. + fn publish(&mut self, index: usize, events: &mut Vec) -> Result<()> { + self.check_size()?; + if self.literal.is_some() || self.published_argument_bytes == self.arguments.len() { + return Ok(()); + } + events.push(Event::ToolArguments { + index, + text: self.arguments[self.published_argument_bytes..].to_owned(), + }); + self.published_argument_bytes = self.arguments.len(); + Ok(()) + } + /// Retain the model's text when it cannot be decoded as a value in the argument object. fn close_literal(&mut self) { let Some(start) = self.literal.take() else { @@ -132,6 +150,11 @@ impl DsmlOutput { if call.name.is_empty() { return Err("tool function name is empty".into()); } + events.push(Event::ToolBegin { + index: self.calls, + name: call.name.clone(), + id: None, + }); } OutputAction::LabelToolCallArguments(label) if !repeated => { let call = self @@ -167,6 +190,7 @@ impl DsmlOutput { } call.arguments.push_str(source); } + call.publish(self.calls, events)?; } OutputAction::ToolCallArgumentsEnd { closing_text } if !repeated => { let mut call = self @@ -175,21 +199,9 @@ impl DsmlOutput { .ok_or("DeepSeek tool arguments have no call")?; call.close_literal(); call.arguments.push_str(closing_text); - call.check_size()?; validate_arguments(&call.arguments)?; - let index = self.calls; - events.extend([ - Event::ToolBegin { - index, - name: call.name, - id: None, - }, - Event::ToolArguments { - index, - text: call.arguments, - }, - Event::ToolEnd { index }, - ]); + call.publish(self.calls, events)?; + events.push(Event::ToolEnd { index: self.calls }); self.calls += 1; } OutputAction::Label(label) if !repeated => { @@ -733,3 +745,281 @@ mod retained_literal_tests { check::(); } } + +#[cfg(test)] +mod streaming_tests { + use super::*; + use crate::output::tagged::{OutputConfig, OutputStart}; + use crate::output::{Input, ModelOutput, Termination}; + use crate::server::output::Accumulator; + use serde_json::json; + + fn config() -> OutputConfig { + OutputConfig { + structured: false, + start: OutputStart::Reasoning, + tools: vec![json!({"type":"function", "function":{"name":"write"}})], + } + } + + fn envelope(parameters: &str) -> String { + format!("thought<|DSML|tool_calls>\n<|DSML|invoke name=\"write\">\n{parameters}\n") + } + + fn string_parameter(name: &str, value: &str) -> String { + format!( + "<|DSML|parameter name=\"{name}\" string=\"true\">{value}\n" + ) + } + + fn arguments(events: &[Event]) -> String { + events + .iter() + .filter_map(|event| match event { + Event::ToolArguments { text, .. } => Some(text.as_str()), + _ => None, + }) + .collect() + } + + fn finish_arguments(parser: &mut DsmlOutput, output: &mut Accumulator) { + output + .apply(parser.finish(Termination::Eos).unwrap()) + .unwrap(); + output.finish().unwrap(); + } + + #[test] + fn a_call_opens_and_publishes_arguments_before_its_envelope_closes() { + let content = "x".repeat(64); + let text = envelope(&format!( + "{}{}", + string_parameter("path", "a.txt"), + string_parameter("content", &content) + )); + let expected = format!("{{\"path\": \"a.txt\", \"content\": \"{content}\"}}"); + let envelope_close = text.find("").unwrap(); + let mut parser = DsmlOutput::::new(config()); + let mut output = Accumulator::new("stream".into()); + let mut published = String::new(); + let mut began = false; + let mut ended = false; + for (at, character) in text.char_indices() { + let before_close = at < envelope_close; + for event in parser.push(Input::Text(&character.to_string())).unwrap() { + if before_close { + assert!( + !matches!(event, Event::ToolEnd { .. }), + "the call ended before its envelope closed" + ); + match &event { + Event::ToolBegin { index, name, .. } => { + assert_eq!((*index, name.as_str()), (0, "write")); + assert!(published.is_empty(), "arguments preceded the call header"); + began = true; + } + Event::ToolArguments { text, .. } => published.push_str(text), + _ => {} + } + } else if matches!(event, Event::ToolEnd { .. }) { + ended = true; + } + output.apply(vec![event]).unwrap(); + } + } + assert!(began, "the call was announced only when its envelope closed"); + assert!( + expected.starts_with(&published), + "published fragments are not a prefix of the arguments: {published}" + ); + assert!(ended, "the completed call never ended"); + finish_arguments(&mut parser, &mut output); + let stored = output.message()["tool_calls"][0]["function"]["arguments"] + .as_str() + .unwrap() + .to_owned(); + assert_eq!(stored, expected); + } + + #[test] + fn published_fragments_reconstruct_the_stored_arguments_at_every_split() { + let content = "é".repeat(24); + let text = envelope(&format!( + "{}{}{}", + string_parameter("path", "a.txt"), + string_parameter("content", &content), + "<|DSML|parameter name=\"count\" string=\"false\">42\n" + )); + let expected = format!("{{\"path\": \"a.txt\", \"content\": \"{content}\", \"count\": 42}}"); + let invoke_close = text.find("").unwrap(); + for split in text + .char_indices() + .map(|(at, _)| at) + .chain([text.len(), invoke_close]) + { + let mut parser = DsmlOutput::::new(config()); + let mut output = Accumulator::new("split".into()); + let mut events = parser.push(Input::Text(&text[..split])).unwrap(); + events.extend(parser.push(Input::Text(&text[split..])).unwrap()); + let fragments = arguments(&events); + let begins = events + .iter() + .filter(|event| matches!(event, Event::ToolBegin { .. })) + .count(); + let ends = events + .iter() + .filter(|event| matches!(event, Event::ToolEnd { .. })) + .count(); + output.apply(events).unwrap(); + finish_arguments(&mut parser, &mut output); + let stored = output.message()["tool_calls"][0]["function"]["arguments"] + .as_str() + .unwrap() + .to_owned(); + assert_eq!((begins, ends), (1, 1), "split {split}"); + assert_eq!(fragments, expected, "split {split}"); + assert_eq!(stored, expected, "split {split}"); + } + // A push that stops before the invoke close already published a prefix. + let mut parser = DsmlOutput::::new(config()); + let published = arguments(&parser.push(Input::Text(&text[..invoke_close])).unwrap()); + assert!(!published.is_empty(), "nothing was published before the envelope closed"); + assert!(expected.starts_with(&published), "{published}"); + } + + #[test] + fn a_rewritten_literal_value_publishes_only_its_final_text() { + let text = envelope(&format!( + "{}{}{}", + string_parameter("label", "a \"b\""), + "<|DSML|parameter name=\"v\" string=\"false\">3 apples\n", + string_parameter("tail", "x") + )); + let tail = text.find("<|DSML|parameter name=\"tail\"").unwrap(); + let cut = tail + text[tail..].find('>').unwrap() + 1; + let mut parser = DsmlOutput::::new(config()); + let mut events = parser.push(Input::Text(&text[..cut])).unwrap(); + let published = arguments(&events); + assert!( + published.contains("\"v\": \"3 apples\""), + "the retained value was not published when the next parameter opened: {published}" + ); + assert!(!published.contains("\"v\": 3 apples"), "{published}"); + assert!(!events.iter().any(|event| matches!(event, Event::ToolEnd { .. }))); + events.extend(parser.push(Input::Text(&text[cut..])).unwrap()); + assert_eq!( + serde_json::from_str::(&arguments(&events)).unwrap(), + json!({"label": "a \"b\"", "v": "3 apples", "tail": "x"}) + ); + } + + #[test] + fn a_truncated_announced_call_is_omitted_from_the_stored_message() { + for (parameters, cut_at, publishes) in [ + ( + string_parameter("content", &"x".repeat(32)), + "", + true, + ), + (String::new(), ">\n", false), + ] { + let text = envelope(¶meters); + let cut = text.find(cut_at).unwrap(); + for cause in [ + Termination::OutputLimit, + Termination::UserStop, + Termination::ExecutionError, + ] { + let mut parser = DsmlOutput::::new(config()); + let mut output = Accumulator::new("truncated".into()); + let events = parser.push(Input::Text(&text[..cut])).unwrap(); + assert!( + events.iter().any(|event| matches!(event, Event::ToolBegin { index: 0, name, .. } if name == "write")), + "the call name was never announced" + ); + assert_eq!(!arguments(&events).is_empty(), publishes, "{cut_at}"); + assert!( + !events + .iter() + .any(|event| matches!(event, Event::ToolEnd { .. })) + ); + output.apply(events).unwrap(); + output.apply(parser.finish(cause).unwrap()).unwrap(); + output.discard_unfinished_call(); + output.finish().unwrap(); + assert!(output.message().get("tool_calls").is_none(), "{cause:?}"); + } + } + } + + #[test] + fn dsml_truncated_second_call_keeps_the_completed_first_call() { + let text = "thought<|DSML|tool_calls>\n<|DSML|invoke name=\"write\"><|DSML|parameter name=\"path\" string=\"true\">a.txt\n<|DSML|invoke name=\"write\"><|DSML|parameter name=\"path\" string=\"true\">b"; + for cause in [ + Termination::OutputLimit, + Termination::UserStop, + Termination::ExecutionError, + ] { + let mut parser = DsmlOutput::::new(config()); + let mut output = Accumulator::new("two_calls".into()); + output.apply(parser.push(Input::Text(text)).unwrap()).unwrap(); + output + .apply(parser.finish(cause).unwrap()) + .unwrap(); + output.discard_unfinished_call(); + output.finish().unwrap(); + let message = output.message(); + assert_eq!(message["reasoning_content"], "thought", "{cause:?}"); + let calls = message["tool_calls"].as_array().unwrap(); + assert_eq!(calls.len(), 1, "{cause:?}"); + assert_eq!(calls[0]["function"]["arguments"], "{\"path\": \"a.txt\"}"); + } + } +} + +#[cfg(test)] +mod rejection_tests { + use super::*; + use crate::output::tagged::{OutputConfig, OutputStart}; + use crate::output::{Input, ModelOutput, Termination}; + use serde_json::json; + + fn parser() -> DsmlOutput { + DsmlOutput::new(OutputConfig { + structured: false, + start: OutputStart::Content, + tools: vec![json!({"type":"function", "function":{"name":"write"}})], + }) + } + + #[test] + fn end_of_sequence_inside_an_announced_call_is_an_error() { + let mut parser = parser(); + let events = parser.push(Input::Text( + "<|DSML|tool_calls><|DSML|invoke name=\"write\"><|DSML|parameter name=\"q\" string=\"true\">par", + )).unwrap(); + assert!(events.iter().any(|event| matches!(event, Event::ToolBegin { .. }))); + assert!(events.iter().any(|event| matches!(event, Event::ToolArguments { .. }))); + assert!(parser.finish(Termination::Eos).is_err()); + } + + #[test] + fn a_rejected_argument_object_fails_after_its_fragments_are_published() { + let text = "<|DSML|tool_calls><|DSML|invoke name=\"write\"><|DSML|parameter name=\"q\" string=\"true\">a<|DSML|parameter name=\"q\" string=\"true\">b"; + let first_value = text.find("").unwrap() + "".len(); + let mut parser = parser(); + let events = parser.push(Input::Text(&text[..first_value])).unwrap(); + assert!( + events + .iter() + .any(|event| matches!(event, Event::ToolBegin { index: 0, name, .. } if name == "write")), + "the call name was never announced" + ); + assert!( + events.iter().any(|event| matches!(event, Event::ToolArguments { text, .. } if !text.is_empty())), + "no argument fragment was published before the rejection" + ); + let err = parser.push(Input::Text(&text[first_value..])).unwrap_err(); + assert!(err.to_string().contains("unique"), "{err}"); + } +} diff --git a/helios/src/server/output.rs b/helios/src/server/output.rs index 62a83c7ab..301c58ec1 100644 --- a/helios/src/server/output.rs +++ b/helios/src/server/output.rs @@ -166,6 +166,12 @@ impl Accumulator { } Ok(()) } + /// Forget the last call when it was announced but never completed. + pub(crate) fn discard_unfinished_call(&mut self) { + if self.calls.last().is_some_and(|call| !call.ended) { + self.calls.pop(); + } + } pub(crate) fn message(&self) -> Value { let mut message = json!({"role":"assistant","content":if self.content.is_empty(){Value::Null}else{Value::String(self.content.clone())}}); if !self.reasoning.is_empty() { @@ -468,6 +474,12 @@ impl Drop for Decoder<'_, P> { } } +/// Whether a termination cause drops a tool call that was announced but never +/// completed, instead of reporting it as an incomplete call. +pub(crate) fn drops_unfinished_call(cause: Termination) -> bool { + cause != Termination::Eos +} + #[cfg(test)] struct Presentation<'a, P: ModelOutput> { decoder: Decoder<'a, P>, @@ -489,6 +501,9 @@ impl<'a, P: ModelOutput> Presentation<'a, P> { } fn finish(&mut self, cause: Termination) -> Result> { let deltas = self.output.apply(self.decoder.finish(cause)?)?; + if drops_unfinished_call(cause) { + self.output.discard_unfinished_call(); + } self.output.finish()?; Ok(deltas) } @@ -1251,20 +1266,15 @@ pub(crate) mod tests { ); } #[test] - fn user_stop_cannot_retract_an_already_emitted_partial_tool_call() { + fn user_stop_omits_an_already_emitted_partial_tool_call() { let frontend = frontend(&["x"]); let observed = Arc::new(Mutex::new(Vec::new())); let mut presentation = Presentation::::new(&frontend, &[98], observed, "partial".into()); let deltas = presentation.push(98).unwrap(); assert_eq!(deltas[0]["tool_calls"][0]["function"]["name"], "partial"); - assert_eq!( - presentation - .finish(Termination::UserStop) - .unwrap_err() - .to_string(), - "incomplete emitted tool call" - ); + presentation.finish(Termination::UserStop).unwrap(); + assert!(presentation.message().get("tool_calls").is_none()); } #[test] fn decoding_sources_cannot_be_mixed_in_either_order() { @@ -1370,7 +1380,7 @@ pub(crate) mod tests { .unwrap(); out.apply(Event::ToolEnd { index: 0 }, &resp_req_id) .unwrap(); - out.finish().unwrap(); + out.finish(Termination::Eos).unwrap(); let Block::Tool { id, .. } = &out.blocks[0] else { panic!("expected tool block"); }; @@ -1423,7 +1433,7 @@ pub(crate) mod tests { out.apply(Event::ToolEnd { index }, &scope).unwrap(); } acc.finish().unwrap(); - out.finish().unwrap(); + out.finish(Termination::Eos).unwrap(); let acc_calls = acc.message()["tool_calls"].as_array().unwrap().clone(); assert_eq!(acc_calls.len(), 128); assert_eq!(out.blocks.len(), 128); @@ -1639,7 +1649,7 @@ pub(crate) mod tests { let blocks_before = unclosed.blocks.clone(); let calls_before = unclosed.calls.clone(); - let err = unclosed.finish().unwrap_err(); + let err = unclosed.finish(Termination::Eos).unwrap_err(); assert_eq!(err.to_string(), "incomplete emitted tool call"); assert_eq!(unclosed.open, Some(0)); assert_eq!(unclosed.blocks, blocks_before); @@ -1667,7 +1677,7 @@ pub(crate) mod tests { .apply(Event::ToolEnd { index: 0 }, req_id) .unwrap(); assert_eq!(unclosed.open, None); - assert!(unclosed.finish().unwrap().is_empty()); + assert!(unclosed.finish(Termination::Eos).unwrap().is_empty()); } } @@ -1694,6 +1704,7 @@ pub(super) struct ResponseOutput { pub blocks: Vec, open: Option, calls: Vec, + abandoned: Option, } impl ResponseOutput { pub fn has_tools(&self) -> bool { @@ -1721,11 +1732,33 @@ impl ResponseOutput { } Ok(()) } - pub fn finish(&mut self) -> Result> { + pub fn finish(&mut self, cause: Termination) -> Result> { let mut changes = vec![]; + if drops_unfinished_call(cause) + && let Some(index) = self.open + && matches!(self.blocks[index], Block::Tool { ended: false, .. }) + { + changes.push(Change::End(index)); + self.abandoned = Some(index); + self.open = None; + } self.close(&mut changes)?; Ok(changes) } + /// Whether `finish` closed the tool block at `index` to send its closing + /// frame for a call that never completed. The block stays present until + /// `discard_abandoned`. + pub fn is_abandoned(&self, index: usize) -> bool { + self.abandoned == Some(index) + } + /// Remove the block `finish` closed for a truncated call, once its + /// closing frame has been rendered. + pub fn discard_abandoned(&mut self) { + if self.abandoned.take().is_some() { + self.blocks.pop(); + self.calls.pop(); + } + } pub fn apply(&mut self, event: Event, request_id: &str) -> Result> { let mut changes = vec![]; match event { diff --git a/helios/src/server/protocol/encode.rs b/helios/src/server/protocol/encode.rs index 848f9c920..126b44e67 100644 --- a/helios/src/server/protocol/encode.rs +++ b/helios/src/server/protocol/encode.rs @@ -10,7 +10,7 @@ use crate::{ output::{Event, Termination}, server::{ inference::{Tool, ToolChoice}, - output::{Accumulator, Block, Change, ResponseOutput}, + output::{Accumulator, Block, Change, ResponseOutput, drops_unfinished_call}, }, }; use serde_json::{Value, json}; @@ -468,11 +468,13 @@ impl Encoder { frames.push(self.named(name, data)); } (Protocol::Responses, Change::End(i)) => { - if let Block::Tool { - name, arguments, .. - } = &self.outputs[0].blocks[i] + let abandoned = self.outputs[0].is_abandoned(i); + let mut custom = false; + if let Block::Tool { name, arguments, .. } = &self.outputs[0].blocks[i] + && self.tool(name).is_some_and(|tool| tool.custom) { - if self.tool(name).is_some_and(|tool| tool.custom) { + custom = true; + if !abandoned { let value: Value = serde_json::from_str(arguments) .map_err(|e| format!("invalid custom tool arguments: {e}"))?; if !value.get("input").is_some_and(Value::is_string) { @@ -483,7 +485,10 @@ impl Encoder { } } } - let item = self.item(i, true); + // A truncated custom call has no complete input, so its item + // reports an empty string instead of the partial arguments. + let complete = !(abandoned && custom); + let item = self.item(i, complete); match &self.outputs[0].blocks[i] { Block::Text(text) | Block::Reasoning(text) => { let name = if matches!(&self.outputs[0].blocks[i], Block::Text(_)) { @@ -503,8 +508,10 @@ impl Encoder { if !item["input"].is_string() { return Err("custom tool input must be text".into()); } - frames.push(self.named("response.custom_tool_call_input.delta",json!({"item_id":self.item_id(i),"output_index":i,"delta":item["input"]}))); - frames.push(self.named("response.custom_tool_call_input.done",json!({"item_id":self.item_id(i),"output_index":i,"input":item["input"]}))); + if !abandoned { + frames.push(self.named("response.custom_tool_call_input.delta",json!({"item_id":self.item_id(i),"output_index":i,"delta":item["input"]}))); + frames.push(self.named("response.custom_tool_call_input.done",json!({"item_id":self.item_id(i),"output_index":i,"input":item["input"]}))); + } } else { frames.push(self.named("response.function_call_arguments.done",json!({"item_id":self.item_id(i),"output_index":i,"arguments":item["arguments"]}))); } @@ -672,16 +679,32 @@ impl Encoder { let stop = if self.tool_limit_reached { None } else { stop }; let mut frames = vec![]; if self.protocol == Protocol::Chat { + if drops_unfinished_call(cause) { + self.chats[index].discard_unfinished_call(); + } self.chats[index].finish()?; } - for change in self.outputs[index].finish()? { - if self.protocol == Protocol::Responses && cause == Termination::OutputLimit { - if let Change::End(i) = change { - self.incomplete_item = Some(i); + let mut abandoned = false; + for change in self.outputs[index].finish(cause)? { + if self.protocol == Protocol::Responses + && let Change::End(i) = &change + { + // An abandoned block is incomplete whatever ended it. Any other + // block is incomplete only when the output limit cut it short. + let truncated = self.outputs[index].is_abandoned(*i); + if truncated || cause == Termination::OutputLimit { + self.incomplete_item = Some(*i); } + abandoned |= truncated; } frames.extend(self.change(change)?); } + self.outputs[index].discard_abandoned(); + // The buffered response is rendered after this returns, so the marking + // outlives the change that set it unless the item is gone. + if abandoned { + self.incomplete_item = None; + } if matches!(self.tool_choice, ToolChoice::Required | ToolChoice::Named(_)) && !self.outputs[index].has_tools() { diff --git a/helios/src/server/protocol/tests.rs b/helios/src/server/protocol/tests.rs index e8159a1d8..d734c5ad8 100644 --- a/helios/src/server/protocol/tests.rs +++ b/helios/src/server/protocol/tests.rs @@ -51,6 +51,40 @@ fn encoder_with_parallel(protocol: Protocol, tool_choice: ToolChoice, parallel: json!({}), ) } +/// A Responses encoder whose only tool takes free-form text and validates it +/// against a grammar. +fn custom_tool_encoder(tool_choice: ToolChoice) -> Encoder { + let mut tools = tools(); + tools[0].custom = true; + let mut encoder = Encoder::new( + Protocol::Responses, + "test".into(), + "model".into(), + 1, + 1, + vec![PromptUsage { + tokens: 17, + image_tokens: 0, + }], + tools, + tool_choice, + true, + true, + json!({}), + ); + let compiler = crate::grammar::GrammarCompiler::new( + &crate::grammar::tests::byte_tokenizer(), + 320, + &[256, 257], + &[], + ) + .unwrap(); + encoder.set_tool_grammars(std::collections::HashMap::from([( + "lookup".to_owned(), + compiler.compile_text("regex", "SELECT [a-z]+").unwrap(), + )])); + encoder +} fn events() -> Vec { vec![ Event::Reasoning("考え".into()), @@ -3805,3 +3839,397 @@ fn responses_tool_outputs_decode_is_error_and_match_chat_and_messages() { } } } + +#[test] +fn an_announced_call_is_omitted_when_the_response_truncates() { + for protocol in [Protocol::Chat, Protocol::Messages, Protocol::Responses] { + for cause in [ + Termination::OutputLimit, + Termination::UserStop, + Termination::Cancelled, + Termination::ExecutionError, + ] { + for fragment in [Some(r#"{"query":"par"#), None] { + let mut encoder = encoder(protocol); + let _ = encoder.start(); + let opening = encoder + .apply( + 0, + vec![Event::ToolBegin { + index: 0, + name: "lookup".into(), + id: Some("call_1".into()), + }], + ) + .unwrap(); + assert_eq!(opening.len(), 1, "{protocol:?} opens a call with one frame"); + match protocol { + Protocol::Chat => assert_eq!( + opening[0].data["choices"][0]["delta"]["tool_calls"][0]["function"]["name"], + "lookup" + ), + Protocol::Messages => { + assert_eq!(opening[0].event.as_deref(), Some("content_block_start")); + assert_eq!(opening[0].data["content_block"]["input"], json!({})); + } + Protocol::Responses => { + assert_eq!( + opening[0].event.as_deref(), + Some("response.output_item.added") + ); + assert_eq!(opening[0].data["item"]["arguments"], ""); + } + _ => unreachable!(), + } + if let Some(text) = fragment { + let fragments = encoder + .apply( + 0, + vec![Event::ToolArguments { + index: 0, + text: text.into(), + }], + ) + .unwrap(); + assert_eq!( + fragments.len(), + 1, + "{protocol:?} publishes one fragment frame" + ); + } + let finished = encoder.finish(0, cause, 4, 0, None).unwrap(); + assert!(!finished.is_empty(), "{protocol:?} reports its finish"); + match protocol { + Protocol::Chat => {} + Protocol::Messages => assert!( + finished + .iter() + .any(|frame| frame.event.as_deref() == Some("content_block_stop")), + "{cause:?} left the announced block open" + ), + Protocol::Responses => assert!( + finished.iter().any( + |frame| frame.event.as_deref() == Some("response.output_item.done") + ), + "{cause:?} left the announced item open" + ), + _ => unreachable!(), + } + let response = encoder.response(); + match protocol { + Protocol::Chat => { + assert!( + response["choices"][0]["message"] + .get("tool_calls") + .is_none(), + "{cause:?}" + ); + let reason = if cause == Termination::OutputLimit { + "length" + } else { + "stop" + }; + assert_eq!(response["choices"][0]["finish_reason"], reason, "{cause:?}"); + } + Protocol::Messages => { + assert!( + response["content"].as_array().unwrap().is_empty(), + "{cause:?}" + ); + if cause == Termination::OutputLimit { + assert_eq!(response["stop_reason"], "max_tokens"); + } + } + Protocol::Responses => { + assert!( + response["output"].as_array().unwrap().is_empty(), + "{cause:?}" + ); + if cause == Termination::OutputLimit { + assert_eq!(response["status"], "incomplete"); + } + } + _ => unreachable!(), + } + } + } + } +} + +#[test] +fn a_truncated_second_call_keeps_the_completed_first_call() { + for protocol in [Protocol::Chat, Protocol::Messages, Protocol::Responses] { + for cause in [ + Termination::OutputLimit, + Termination::UserStop, + Termination::Cancelled, + ] { + let mut encoder = encoder(protocol); + let _ = encoder.start(); + encoder + .apply( + 0, + vec![ + Event::ToolBegin { + index: 0, + name: "lookup".into(), + id: Some("call_1".into()), + }, + Event::ToolArguments { + index: 0, + text: r#"{"query":"one"}"#.into(), + }, + Event::ToolEnd { index: 0 }, + Event::ToolBegin { + index: 1, + name: "lookup".into(), + id: Some("call_2".into()), + }, + Event::ToolArguments { + index: 1, + text: r#"{"query":"tw"#.into(), + }, + ], + ) + .unwrap(); + encoder.finish(0, cause, 4, 0, None).unwrap(); + let response = encoder.response(); + match protocol { + Protocol::Chat => { + let calls = response["choices"][0]["message"]["tool_calls"] + .as_array() + .unwrap(); + assert_eq!(calls.len(), 1, "{cause:?}"); + assert_eq!(calls[0]["function"]["arguments"], r#"{"query":"one"}"#); + let reason = match cause { + Termination::OutputLimit => "length", + Termination::UserStop => "stop", + _ => "tool_calls", + }; + assert_eq!(response["choices"][0]["finish_reason"], reason, "{cause:?}"); + } + Protocol::Messages => { + let content = response["content"].as_array().unwrap(); + assert_eq!(content.len(), 1, "{cause:?}"); + assert_eq!(content[0]["type"], "tool_use"); + assert_eq!(content[0]["input"], json!({"query": "one"})); + } + Protocol::Responses => { + let output = response["output"].as_array().unwrap(); + assert_eq!(output.len(), 1, "{cause:?}"); + assert_eq!(output[0]["type"], "function_call"); + assert_eq!(output[0]["arguments"], r#"{"query":"one"}"#); + } + _ => unreachable!(), + } + } + } +} + +#[test] +fn dsml_arguments_reach_the_chat_wire_while_the_call_is_open() { + use crate::{ + model::contract::{ToolParser, ToolParserKind}, + output::{ + Input as OutputInput, OutputConfig, OutputPipeline, + tagged::{self, OutputStart}, + }, + }; + let mut syntax = crate::model::testing::metadata().frontend; + syntax.reasoning = None; + syntax.tools = Some(ToolParser { + kind: ToolParserKind::Dsml, + wrapping_newlines: 0, + tag_separator: String::new(), + }); + let mut parser = OutputPipeline::new(OutputConfig { + syntax, + control_tokens: vec![], + content: tagged::OutputConfig { + structured: false, + start: OutputStart::Content, + tools: vec![json!({"type":"function","function":{"name":"lookup"}})], + }, + }); + let mut encoder = encoder(Protocol::Chat); + let _ = encoder.start(); + let wire = "<|DSML|tool_calls><|DSML|invoke name=\"lookup\"><|DSML|parameter name=\"q\" string=\"true\">ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + let envelope_close = wire.find("").unwrap(); + let mut fragments = String::new(); + let mut arguments_before_close = 0; + let mut named = false; + for (at, character) in wire.char_indices() { + let piece = &wire[at..at + character.len_utf8()]; + for frame in encoder.apply(0, parser.push(OutputInput::Text(piece)).unwrap()).unwrap() { + for call in frame.data["choices"][0]["delta"]["tool_calls"] + .as_array() + .into_iter() + .flatten() + { + if call["function"]["name"].as_str() == Some("lookup") { + named = true; + } + if let Some(arguments) = call["function"]["arguments"].as_str() + && !arguments.is_empty() + { + fragments.push_str(arguments); + if at < envelope_close { + arguments_before_close += 1; + } + } + } + } + } + let tail = parser.finish(Termination::Eos).unwrap(); + encoder.apply(0, tail).unwrap(); + encoder.finish(0, Termination::Eos, 8, 0, None).unwrap(); + assert!(named, "the call name never reached the wire"); + assert!( + arguments_before_close > 2, + "only {arguments_before_close} argument frames arrived before the envelope closed" + ); + let expected = r#"{"q": "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"}"#; + assert_eq!(fragments, expected); + let stored = encoder.response()["choices"][0]["message"]["tool_calls"][0]["function"] + ["arguments"] + .as_str() + .unwrap() + .to_owned(); + assert_eq!(stored, expected); +} + +#[test] +fn a_truncated_custom_call_closes_incomplete_without_failing_the_request() { + for cause in [ + Termination::OutputLimit, + Termination::UserStop, + Termination::Cancelled, + Termination::ExecutionError, + ] { + // The first partial parses but fails the grammar; the second does not + // parse at all. + for partial in [r#"{"input":"nope"}"#, r#"{"input":"#] { + let mut encoder = custom_tool_encoder(ToolChoice::Auto); + let _ = encoder.start(); + let opening = encoder + .apply( + 0, + vec![ + Event::ToolBegin { + index: 0, + name: "lookup".into(), + id: Some("call_1".into()), + }, + Event::ToolArguments { + index: 0, + text: partial.into(), + }, + ], + ) + .unwrap(); + assert_eq!(opening.len(), 1, "{cause:?} {partial:?}"); + let frames = encoder.finish(0, cause, 3, 0, None).unwrap(); + let done: Vec<_> = frames + .iter() + .filter(|frame| frame.event.as_deref() == Some("response.output_item.done")) + .collect(); + assert_eq!(done.len(), 1, "{cause:?} {partial:?}"); + assert_eq!(done[0].data["item"]["type"], "custom_tool_call"); + assert_eq!(done[0].data["item"]["status"], "incomplete"); + assert_eq!(done[0].data["item"]["input"], ""); + assert!( + !frames.iter().any(|frame| frame + .event + .as_deref() + .is_some_and(|name| name.starts_with("response.custom_tool_call_input"))), + "{cause:?} {partial:?}" + ); + assert_eq!(encoder.response()["output"], json!([]), "{cause:?} {partial:?}"); + } + } +} + +#[test] +fn an_abandoned_function_call_reports_incomplete() { + for cause in [Termination::UserStop, Termination::Cancelled] { + let mut encoder = encoder(Protocol::Responses); + let _ = encoder.start(); + let streamed = encoder + .apply( + 0, + vec![ + Event::ToolBegin { + index: 0, + name: "lookup".into(), + id: Some("call_1".into()), + }, + Event::ToolArguments { + index: 0, + text: r#"{"query":"par"#.into(), + }, + ], + ) + .unwrap(); + assert!( + streamed + .iter() + .any(|frame| frame.event.as_deref() + == Some("response.function_call_arguments.delta")), + "{cause:?}" + ); + let frames = encoder.finish(0, cause, 2, 0, None).unwrap(); + let done: Vec<_> = frames + .iter() + .filter(|frame| frame.event.as_deref() == Some("response.output_item.done")) + .collect(); + assert_eq!(done.len(), 1, "{cause:?}"); + assert_eq!(done[0].data["item"]["type"], "function_call"); + assert_eq!(done[0].data["item"]["status"], "incomplete"); + assert_eq!(done[0].data["item"]["arguments"], r#"{"query":"par"#); + assert!( + frames + .iter() + .any(|frame| frame.event.as_deref() + == Some("response.function_call_arguments.done")), + "{cause:?}" + ); + assert_eq!(encoder.response()["output"], json!([]), "{cause:?}"); + } +} + +#[test] +fn a_truncated_call_does_not_satisfy_a_required_tool_choice() { + for choice in [ToolChoice::Required, ToolChoice::Named("lookup".into())] { + for mut encoder in [ + custom_tool_encoder(choice.clone()), + encoder_with_choice(Protocol::Responses, choice.clone()), + ] { + let _ = encoder.start(); + encoder + .apply( + 0, + vec![ + Event::ToolBegin { + index: 0, + name: "lookup".into(), + id: Some("call_1".into()), + }, + Event::ToolArguments { + index: 0, + text: r#"{"query":"par"#.into(), + }, + ], + ) + .unwrap(); + let error = encoder + .finish(0, Termination::UserStop, 2, 0, None) + .unwrap_err(); + assert!( + error + .to_string() + .contains("did not produce a completed tool call"), + "{choice:?}: {error}" + ); + } + } +} diff --git a/helios/tests/deepseek_output.rs b/helios/tests/deepseek_output.rs index a34cf8713..2099457ca 100644 --- a/helios/tests/deepseek_output.rs +++ b/helios/tests/deepseek_output.rs @@ -496,11 +496,15 @@ fn empty_and_duplicate_top_level_parameter_names_are_rejected() { .collect(), ] { let mut output = pipeline(spaced, OutputStart::Content, false); - let mut published = vec![]; + let mut parsed = Parsed::default(); let mut error = None; for chunk in chunks { match output.push(Input::Text(chunk)) { - Ok(events) => published.extend(events), + Ok(events) => { + for event in events { + parsed.event(event); + } + } Err(failure) => { error = Some(failure); break; @@ -508,7 +512,7 @@ fn empty_and_duplicate_top_level_parameter_names_are_rejected() { } } assert!(error.unwrap().to_string().contains("nonempty and unique")); - assert!(published.is_empty()); + assert_eq!(parsed.ended, 0, "a rejected call reported an end"); } } let nested = parameter("object", "{\"x\":1,\"x\":2}"); @@ -572,16 +576,20 @@ fn parse_literal_parameters( let (open, _, close) = block(spaced); let s = if spaced { " " } else { "" }; let mut output = pipeline(spaced, OutputStart::Content, false); + let mut parsed = Parsed::default(); let header = format!("{open}<|DSML|{s}invoke name=\"lookup\">"); - assert!(output.push(Input::Text(&header))?.is_empty()); + for event in output.push(Input::Text(&header))? { + parsed.event(event); + } for (name, value) in parameters { let parameter = format!( "<|DSML|{s}parameter name=\"{name}\" string=\"false\">{value}" ); - assert!(output.push(Input::Text(¶meter))?.is_empty()); + for event in output.push(Input::Text(¶meter))? { + parsed.event(event); + } } let end = format!("{close}"); - let mut parsed = Parsed::default(); for event in output.push(Input::Text(&end))? { parsed.event(event); } diff --git a/helios/tests/deepseek_requests.rs b/helios/tests/deepseek_requests.rs index ddcec058c..0963c3d74 100644 --- a/helios/tests/deepseek_requests.rs +++ b/helios/tests/deepseek_requests.rs @@ -680,8 +680,17 @@ fn added_non_special_dsml_token_produces_tool_calls() { events.extend(output.finish(flare_helios::output::Termination::Eos).unwrap()); assert!(events.iter().any(|event| matches!(event, flare_helios::output::Event::ToolBegin { name, .. } if name == "get_weather"))); - assert!(events.iter().any(|event| matches!(event, - flare_helios::output::Event::ToolArguments { text, .. } if serde_json::from_str::(text).unwrap() == json!({"location":"Berlin"})))); + let arguments: String = events + .iter() + .filter_map(|event| match event { + flare_helios::output::Event::ToolArguments { text, .. } => Some(text.as_str()), + _ => None, + }) + .collect(); + assert_eq!( + serde_json::from_str::(&arguments).unwrap(), + json!({"location": "Berlin"}) + ); assert!(events.iter().any(|event| matches!(event, flare_helios::output::Event::ToolEnd { .. }))); } }