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
8 changes: 7 additions & 1 deletion crates/tool_parser/src/parsers/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -423,7 +423,13 @@ pub(crate) fn handle_json_tool_streaming(
// them either because only this branch populates `prev_tool_call_arr`.
// `current_tool_name_sent` implies `current_tool_id >= 0`.
if *current_tool_name_sent {
let Some(cur_arguments) = current_tool_call.get("arguments") else {
// A complete call without arguments takes `{}`, as in the
// non-streaming parse.
let empty_obj = Value::Object(serde_json::Map::new());
let Some(cur_arguments) = current_tool_call
.get("arguments")
.or_else(|| is_complete.then_some(&empty_obj))
else {
return Ok(result);
};
let tool_id = *current_tool_id as usize;
Expand Down
10 changes: 9 additions & 1 deletion crates/tool_parser/src/parsers/minimax_m2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,15 @@ impl ToolParser for MinimaxM2Parser {
let tool_id = self.current_tool_id as usize;
if tool_id < self.streamed_args_for_tool.len() {
let current_streamed = &self.streamed_args_for_tool[tool_id];
if !current_streamed.is_empty() && !current_streamed.ends_with('}') {
if current_streamed.is_empty() {
// No parameters: `{}`, as in the non-streaming parse.
calls.push(ToolCallItem {
tool_index: tool_id,
name: None,
parameters: "{}".to_string(),
});
self.streamed_args_for_tool[tool_id].push_str("{}");
} else if !current_streamed.ends_with('}') {
// Count opening and closing braces to check if JSON is complete
let open_braces = current_streamed.matches('{').count();
let close_braces = current_streamed.matches('}').count();
Expand Down
36 changes: 36 additions & 0 deletions crates/tool_parser/tests/tool_parser_cohere.rs
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,42 @@ async fn test_cohere_streaming_basic() {
assert_eq!(tool_names[0], "get_weather");
}

#[tokio::test]
async fn test_cohere_streaming_empty_parameters() {
// A streamed call without parameters ends with `{}`, as parse_complete returns.
let tools = common::create_test_tools();
for chunks in [
vec![
"<|START_ACTION|>",
r#"{"tool_name": "get_weather"}"#,
"<|END_ACTION|>",
],
vec![
"<|START_ACTION|>",
"{",
"\"tool_name\"",
": ",
"\"get_weather\"",
"}",
"<|END_ACTION|>",
],
] {
let mut parser = CohereParser::new();
let mut name = None;
let mut arguments = String::new();
for chunk in chunks {
let result = parser.parse_incremental(chunk, &tools).await.unwrap();
for call in result.calls {
assert_eq!(call.tool_index, 0);
name = call.name.or(name);
arguments.push_str(&call.parameters);
}
}
assert_eq!(name.as_deref(), Some("get_weather"));
assert_eq!(arguments, "{}");
}
}

#[tokio::test]
async fn test_cohere_reset() {
let mut parser = CohereParser::new();
Expand Down
29 changes: 29 additions & 0 deletions crates/tool_parser/tests/tool_parser_minimax_m2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -548,6 +548,35 @@ async fn test_minimax_empty_parameters() {
assert_eq!(args, serde_json::json!({}));
}

#[tokio::test]
async fn test_minimax_streaming_empty_parameters() {
// A streamed call without parameters ends with `{}`, as parse_complete returns.
let tools = create_test_tools();
for chunks in [
vec!["<minimax:tool_call>\n<invoke name=\"get_weather\">\n</invoke>\n</minimax:tool_call>"],
vec![
"<minimax:tool_call>",
"\n<invoke name=\"get_weather\">",
"\n</invoke>",
"\n</minimax:tool_call>",
],
] {
let mut parser = MinimaxM2Parser::new();
let mut name = None;
let mut arguments = String::new();
for chunk in chunks {
let result = parser.parse_incremental(chunk, &tools).await.unwrap();
for call in result.calls {
assert_eq!(call.tool_index, 0);
name = call.name.or(name);
arguments.push_str(&call.parameters);
}
}
assert_eq!(name.as_deref(), Some("get_weather"));
assert_eq!(arguments, "{}");
}
}

#[tokio::test]
async fn test_minimax_multiline_parameter_values() {
let parser = MinimaxM2Parser::new();
Expand Down
36 changes: 35 additions & 1 deletion crates/tool_parser/tests/tool_parser_streaming_flush.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
//! empty stream — no tool_call deltas AND no content deltas — while the
//! non-streaming path correctly fell back to returning the text as content.
//!
//! Four properties are covered here:
//! Five properties are covered here:
//! 1. Text that is definitively not a declared tool call (complete JSON with
//! a missing or undeclared name) is surfaced as normal text mid-stream
//! instead of being buffered forever or silently dropped, while legitimate
Expand All @@ -22,6 +22,8 @@
//! 4. A call whose name and arguments both land in one chunk streams *both*
//! in that chunk. There is no later parser call to fall back on, so a name
//! without arguments would reach the client as an unusable tool call.
//! 5. A complete call without arguments streams `{}`, as the non-streaming
//! parse returns, rather than a name alone.
mod common;

use common::{create_test_tools, streaming_helpers};
Expand Down Expand Up @@ -368,6 +370,38 @@ async fn streaming_never_swallows_content() {
}
}

#[tokio::test]
async fn a_call_without_arguments_streams_an_empty_object() {
let cases: [(&str, MakeParser, &[&str]); 4] = [
("json", json, &[r#"{"name": "get_weather"}"#]),
("llama", llama, &[r#"{"name": "get_weather"}"#]),
(
"mistral",
mistral,
&[r#"[TOOL_CALLS] [{"name": "get_weather"}]"#],
),
(
"qwen",
qwen,
&["<tool_call>\n{\"name\": \"get_weather\"}\n</tool_call>"],
),
];
for (label, make, whole) in cases {
for feed in [Feed::Chunks(whole), Feed::Realistic(whole[0])] {
let mut parser = make();
let (text, calls) = stream(parser.as_mut(), &feed).await;
assert_eq!(text, "", "[{label}] streamed content");
assert_eq!(
announced(&calls),
Some("get_weather"),
"[{label}] tool call"
);
assert_eq!(streamed_args(&calls), "{}", "[{label}] arguments");
assert_eq!(parser.take_unstreamed_normal_text(), "", "[{label}] flush");
}
}
}

#[tokio::test]
async fn partial_declared_name_keeps_buffering() {
let mut parser = LlamaParser::new();
Expand Down
7 changes: 4 additions & 3 deletions model_gateway/src/routers/grpc/regular/processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -755,12 +755,13 @@ impl ResponseProcessor {
.and_then(|v| v.as_str().map(String::from))
});

let stop_reason = if tool_calls.is_some() || finish_reason_str == "tool_calls" {
// Parsed calls do not override a truncation, as in Chat.
let stop_reason = if finish_reason_str == "length" {
Some(messages::StopReason::MaxTokens)
} else if tool_calls.is_some() || finish_reason_str == "tool_calls" {
Some(messages::StopReason::ToolUse)
} else if stop_sequence.is_some() {
Some(messages::StopReason::StopSequence)
} else if finish_reason_str == "length" {
Some(messages::StopReason::MaxTokens)
} else {
Some(messages::StopReason::EndTurn)
};
Expand Down
14 changes: 14 additions & 0 deletions model_gateway/src/routers/grpc/regular/responses/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,20 @@ pub(super) fn apply_mcp_tool_call_limit(
)
}

/// Whether a server call among `calls` has arguments that are not JSON. A
/// parser can report a call's name before its arguments, so a call whose
/// output was cut short or failed to parse arrives without them. Like the
/// calls of a truncated or failed generation, it must not be dispatched.
pub(super) fn has_unfinished_mcp_call(
calls: &[ExtractedToolCall],
session: &McpToolSession<'_>,
) -> bool {
calls.iter().any(|call| {
session.has_exposed_tool(&call.name)
&& serde_json::from_str::<serde_json::Value>(&call.arguments).is_err()
})
}

/// Extract all tool calls from chat response (for parallel tool call support)
pub(super) fn extract_all_tool_calls_from_chat(
response: &openai_protocol::chat::ChatCompletionResponse,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@ use tracing::{debug, error, trace};
use super::{
common::{
apply_mcp_tool_call_limit, build_next_request, convert_mcp_tools_to_chat_tools,
extract_all_tool_calls_from_chat, load_conversation_history, prepare_chat_tools_and_choice,
ExtractedToolCall, McpToolCallLimit, ResponsesCallContext, ToolLoopState,
extract_all_tool_calls_from_chat, has_unfinished_mcp_call, load_conversation_history,
prepare_chat_tools_and_choice, ExtractedToolCall, McpToolCallLimit, ResponsesCallContext,
ToolLoopState,
},
conversions,
};
Expand Down Expand Up @@ -216,12 +217,14 @@ pub(super) async fn execute_tool_loop(
.collect();

// A truncated or failed generation must never dispatch tools, even if a complete
// call was parsed before the engine stopped. Match the streaming loop.
// call was parsed before the engine stopped, and neither must a server call the
// generation did not finish. Match the streaming loop.
let generation_interrupted = chat_response
.choices
.first()
.and_then(|choice| choice.finish_reason.as_deref())
.is_some_and(|reason| matches!(reason, "length" | "failed" | "error"));
.is_some_and(|reason| matches!(reason, "length" | "failed" | "error"))
|| has_unfinished_mcp_call(&tool_calls, &session);
if tool_calls.is_empty() || generation_interrupted {
// No more tool calls, we're done
trace!(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ use uuid::Uuid;
use super::{
common::{
apply_mcp_tool_call_limit, build_next_request, convert_mcp_tools_to_chat_tools,
extract_all_tool_calls_from_chat, prepare_chat_tools_and_choice, ExtractedToolCall,
McpToolCallLimit, ResponsesCallContext, ToolLoopState,
extract_all_tool_calls_from_chat, has_unfinished_mcp_call, prepare_chat_tools_and_choice,
ExtractedToolCall, McpToolCallLimit, ResponsesCallContext, ToolLoopState,
},
conversions,
};
Expand Down Expand Up @@ -685,6 +685,10 @@ async fn execute_tool_loop_streaming_internal(

// Check for tool calls (extract all of them for parallel execution)
let tool_calls = extract_all_tool_calls_from_chat(&accumulated_response);
// Neither can a server call the generation did not finish.
if has_unfinished_mcp_call(&tool_calls, &session) {
break None;
}

if !tool_calls.is_empty() {
trace!(
Expand Down
10 changes: 6 additions & 4 deletions model_gateway/src/routers/grpc/regular/streaming.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2663,13 +2663,15 @@ impl StreamingProcessor {
.await?;
}

// Phase 4: Emit message_delta with stop_reason and usage
let stop_reason = if has_tool_calls || finish_reason_str == "tool_calls" {
// Phase 4: Emit message_delta with stop_reason and usage. A truncation
// stays max_tokens after a tool call started, as Chat keeps `length`:
// the call may be cut short.
let stop_reason = if finish_reason_str == "length" {
Some(messages::StopReason::MaxTokens)
} else if has_tool_calls || finish_reason_str == "tool_calls" {
Some(messages::StopReason::ToolUse)
} else if matched_stop.is_some() {
Some(messages::StopReason::StopSequence)
} else if finish_reason_str == "length" {
Some(messages::StopReason::MaxTokens)
} else {
Some(messages::StopReason::EndTurn)
};
Expand Down
107 changes: 106 additions & 1 deletion model_gateway/src/routers/grpc/regular/streaming/eof_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ use tokio::{net::TcpListener, task::JoinHandle};
use tonic::codec::Codec;

use super::*;
use crate::{routers::common::sse::SseReceiver, worker::WorkerRegistry};
use crate::{
routers::{common::sse::SseReceiver, grpc::regular::processor::ResponseProcessor},
worker::WorkerRegistry,
};

#[derive(Default)]
struct CharacterTokenizer {
Expand Down Expand Up @@ -464,6 +467,108 @@ async fn messages_eof_emits_thinking_tail_before_block_stop() {
}
}

/// A Messages response to `text` through the `qwen_xml` tool parser, which
/// reports a call's name before its arguments: the type of each content block
/// and the stop reason.
async fn qwen_xml_messages(text: &str, finish: &str, stream: bool) -> (Vec<String>, String) {
let resolver = || {
utils::ParserResolver::new(
Arc::new(WorkerRegistry::new()),
Some("qwen_xml".to_string()),
None,
)
};
let request = serde_json::from_value::<messages::CreateMessageRequest>(serde_json::json!({
"model": "eof-test", "max_tokens": 16,
"messages": [{"role": "user", "content": "weather?"}],
"tools": [{"name": "lookup", "input_schema": {"type": "object", "properties": {}}}]
}))
.expect("messages request");
let spec = MessagesResponseSpec::from(&request);
let mut last = complete(0, finish);
if let Some(GenerationEvent::Complete(complete)) = &mut last.response {
complete.output_ids = text.chars().map(u32::from).collect();
}
let (grpc_stream, server) = scripted_stream(vec![chunk(0, text), last], "0").await;
let tokenizer: Arc<dyn Tokenizer> = Arc::new(CharacterTokenizer::default());
let read = if stream {
let processor = StreamingProcessor::new(
ToolParserFactory::new(),
ReasoningParserFactory::new(),
resolver(),
"vllm",
);
let (tx, rx) = sse_channel();
let result = processor
.process_messages_streaming_chunks(
grpc_stream,
dispatch(),
tokenizer,
(None, None, false, false, false),
spec,
&tx,
None,
)
.await;
drop(tx);
assert!(result.is_ok(), "{result:?}");
let events = collect_events(rx).await;
let blocks = events
.iter()
.filter(|event| event["type"] == "content_block_start")
.map(|event| event["content_block"]["type"].as_str().unwrap().to_string())
.collect();
let delta = events.iter().find(|event| event["type"] == "message_delta");
let stop_reason = &delta.unwrap()["delta"]["stop_reason"];
(blocks, stop_reason.as_str().unwrap().to_string())
} else {
let processor = ResponseProcessor::new(
ToolParserFactory::new(),
ReasoningParserFactory::new(),
resolver(),
);
let mut decoder = utils::create_stop_decoder(&tokenizer, None, None, false, false, false);
let message = processor
.process_non_streaming_messages_response(
context::ExecutionResult::Single {
stream: grpc_stream,
},
spec,
dispatch(),
tokenizer,
&mut decoder,
)
.await
.unwrap_or_else(|response| panic!("{}", response.status()));
let message = serde_json::to_value(message).unwrap();
let blocks = message["content"].as_array().unwrap().iter();
let blocks = blocks
.map(|block| block["type"].as_str().unwrap().to_string())
.collect();
(blocks, message["stop_reason"].as_str().unwrap().to_string())
};
server.abort();
read
}

#[tokio::test]
async fn messages_truncated_after_a_tool_call_starts_stop_at_max_tokens() {
// The output ends inside a call the parser already named, or after a
// whole call. Only an output that finished calls a tool.
let cut = "<tool_call>\n<function=lookup>\n<parameter=city>\nPar";
let whole = "<tool_call>\n<function=lookup>\n</function>\n</tool_call>\nThen";
for (text, stream) in [(cut, true), (whole, true), (whole, false)] {
for (finish, stop_reason) in [("length", "max_tokens"), ("stop", "tool_use")] {
let (blocks, got) = qwen_xml_messages(text, finish, stream).await;
assert!(
blocks.iter().any(|block| block == "tool_use"),
"{text:?} {finish} stream={stream}: {blocks:?}"
);
assert_eq!(got, stop_reason, "{text:?} {finish} stream={stream}");
}
}
}

#[tokio::test]
async fn deepseek_usage_rides_on_the_last_finish_chunk() {
for options in [
Expand Down
Loading
Loading