[router][grpc] Support streaming parsing with Tool Choice in chat completions API (#12677)

This commit is contained in:
Chang Su
2025-11-05 12:12:21 -08:00
committed by GitHub
parent fb2e816e83
commit 4fe53e5888
17 changed files with 1035 additions and 378 deletions
@@ -21,6 +21,8 @@ use crate::{
/// - Unicode token delimiters
/// - JSON arguments in code blocks
/// - Support for multiple sequential tool calls
///
/// Reference: https://huggingface.co/deepseek-ai/DeepSeek-V3-0324?chat_template=default
pub struct DeepSeekParser {
/// Regex for extracting complete tool calls
tool_call_extractor: Regex,
+12 -2
View File
@@ -217,8 +217,18 @@ pub fn handle_json_tool_streaming(
}
};
// Check if JSON is complete
let is_complete = end_idx == json_str.len() && serde_json::from_str::<Value>(json_str).is_ok();
// Check if JSON is complete - validate only the parsed portion
// Ensure end_idx is on a valid UTF-8 character boundary
let safe_end_idx = if json_str.is_char_boundary(end_idx) {
end_idx
} else {
// Find the nearest valid character boundary before end_idx
(0..end_idx)
.rev()
.find(|&i| json_str.is_char_boundary(i))
.unwrap_or(0)
};
let is_complete = serde_json::from_str::<Value>(&json_str[..safe_end_idx]).is_ok();
// Validate tool name if present
if let Some(name) = obj.get("name").and_then(|v| v.as_str()) {
+32 -5
View File
@@ -39,6 +39,12 @@ pub struct JsonParser {
/// Separator between multiple tool calls
tool_call_separator: &'static str,
/// Track whether we're parsing array format `[...]` vs single object `{...}`
is_array_format: bool,
/// Track whether we've already stripped the closing ] bracket (for array format)
array_closed: bool,
}
impl JsonParser {
@@ -52,6 +58,8 @@ impl JsonParser {
current_tool_name_sent: false,
streamed_args_for_tool: Vec::new(),
tool_call_separator: ",",
is_array_format: false,
array_closed: false,
}
}
@@ -211,14 +219,31 @@ impl ToolParser for JsonParser {
self.buffer.push_str(chunk);
let current_text = &self.buffer.clone();
// Determine format on first parse (array vs single object)
if self.current_tool_id == -1 && self.has_tool_markers(current_text) {
self.is_array_format = current_text.trim().starts_with('[');
}
// Check if current_text has tool_call
let has_tool_start = self.has_tool_markers(current_text)
|| (self.current_tool_id >= 0 && current_text.starts_with(self.tool_call_separator));
// Once array is closed, don't treat [ or { as tool markers
let has_tool_start = (!self.array_closed && self.has_tool_markers(current_text))
|| (self.current_tool_id > 0 && current_text.starts_with(self.tool_call_separator));
if !has_tool_start {
let normal_text = self.buffer.clone();
let mut normal_text = self.buffer.clone();
self.buffer.clear();
// Strip ] only once (the closing bracket of JSON array format)
// Only for array format and only if we haven't already closed it
if self.is_array_format
&& !self.array_closed
&& self.current_tool_id > 0
&& normal_text.starts_with("]")
{
normal_text = normal_text.strip_prefix("]").unwrap().to_string();
self.array_closed = true;
}
return Ok(StreamingParseResult {
normal_text,
calls: vec![],
@@ -233,12 +258,12 @@ impl ToolParser for JsonParser {
let start_idx = if let Some(bracket_pos) = current_text.find('[') {
let brace_pos = current_text.find('{');
match brace_pos {
Some(bp) if bp < bracket_pos => bp,
Some(bp) => bp,
_ => bracket_pos,
}
} else if let Some(brace_pos) = current_text.find('{') {
brace_pos
} else if self.current_tool_id >= 0 && current_text.starts_with(self.tool_call_separator) {
} else if self.current_tool_id > 0 && current_text.starts_with(self.tool_call_separator) {
self.tool_call_separator.len()
} else {
0
@@ -274,5 +299,7 @@ impl ToolParser for JsonParser {
&mut self.current_tool_name_sent,
&mut self.streamed_args_for_tool,
);
self.is_array_format = false;
self.array_closed = false;
}
}
@@ -21,6 +21,8 @@ use crate::{
/// - Token-based delimiters
/// - Function calls with explicit indexing
/// - JSON arguments
///
/// Reference: https://huggingface.co/moonshotai/Kimi-K2-Instruct/blob/main/docs/tool_call_guidance.md
pub struct KimiK2Parser {
/// Regex for extracting complete tool calls
tool_call_extractor: Regex,
+2 -2
View File
@@ -181,7 +181,7 @@ impl ToolParser for LlamaParser {
// Check if current_text has tool_call
let has_tool_start = self.has_tool_markers(current_text)
|| (self.current_tool_id >= 0 && current_text.starts_with(self.tool_call_separator));
|| (self.current_tool_id > 0 && current_text.starts_with(self.tool_call_separator));
if !has_tool_start {
// Only clear buffer if we're sure no tool call is starting
@@ -205,7 +205,7 @@ impl ToolParser for LlamaParser {
// Determine start index for JSON parsing
let start_idx = if let Some(pos) = current_text.find(self.bot_token) {
pos + self.bot_token.len()
} else if self.current_tool_id >= 0 && current_text.starts_with(self.tool_call_separator) {
} else if self.current_tool_id > 0 && current_text.starts_with(self.tool_call_separator) {
self.tool_call_separator.len()
} else {
0
+24 -7
View File
@@ -17,10 +17,7 @@ use crate::{
/// Handles the Mistral-specific format:
/// `[TOOL_CALLS] [{"name": "func", "arguments": {...}}, ...]`
///
/// Features:
/// - Bracket counting for proper JSON array extraction
/// - Support for multiple tool calls in a single array
/// - String-aware parsing to handle nested brackets in JSON
/// Reference: https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.3?chat_template=default
pub struct MistralParser {
/// Parser for handling incomplete JSON during streaming
partial_json: PartialJson,
@@ -42,7 +39,11 @@ pub struct MistralParser {
/// Token configuration
bot_token: &'static str,
eot_token: &'static str,
tool_call_separator: &'static str,
/// Track whether we've already stripped the closing ] bracket
array_closed: bool,
}
impl MistralParser {
@@ -56,7 +57,9 @@ impl MistralParser {
current_tool_name_sent: false,
streamed_args_for_tool: Vec::new(),
bot_token: "[TOOL_CALLS] [",
eot_token: "]",
tool_call_separator: ", ",
array_closed: false,
}
}
@@ -207,14 +210,27 @@ impl ToolParser for MistralParser {
// Check if current_text has tool_call
let has_tool_start = self.has_tool_markers(current_text)
|| (self.current_tool_id >= 0 && current_text.starts_with(self.tool_call_separator));
|| (self.current_tool_id > 0 && current_text.starts_with(self.tool_call_separator));
if !has_tool_start {
// Only clear buffer if we're sure no tool call is starting
if helpers::ends_with_partial_token(&self.buffer, self.bot_token).is_none() {
let normal_text = self.buffer.clone();
let mut normal_text = self.buffer.clone();
self.buffer.clear();
// Strip ] only once (the closing bracket of [TOOL_CALLS] array)
// current_tool_id > 0 means we've parsed at least one tool
if !self.array_closed
&& self.current_tool_id > 0
&& normal_text.starts_with(self.eot_token)
{
normal_text = normal_text
.strip_prefix(self.eot_token)
.unwrap()
.to_string();
self.array_closed = true;
}
return Ok(StreamingParseResult {
normal_text,
calls: vec![],
@@ -231,7 +247,7 @@ impl ToolParser for MistralParser {
// Determine start index for JSON parsing
let start_idx = if let Some(pos) = current_text.find(self.bot_token) {
pos + self.bot_token.len()
} else if self.current_tool_id >= 0 && current_text.starts_with(self.tool_call_separator) {
} else if self.current_tool_id > 0 && current_text.starts_with(self.tool_call_separator) {
self.tool_call_separator.len()
} else {
0
@@ -266,5 +282,6 @@ impl ToolParser for MistralParser {
&mut self.current_tool_name_sent,
&mut self.streamed_args_for_tool,
);
self.array_closed = false;
}
}
@@ -9,6 +9,7 @@ use std::sync::OnceLock;
///
/// This format is used by Llama models and uses Python literals
/// rather than JSON for arguments.
/// Reference: https://huggingface.co/meta-llama/Llama-4-Scout-17B-16E-Instruct?chat_template=default
use async_trait::async_trait;
use num_traits::ToPrimitive;
use regex::Regex;
+19 -15
View File
@@ -19,10 +19,11 @@ use crate::{
/// `<tool_call>\n{"name": "func", "arguments": {...}}\n</tool_call>`
///
/// Features:
/// - XML-style tags with JSON content
/// - Support for multiple sequential tool calls
/// - Newline-aware parsing
/// - Buffering for partial end tokens
/// - Tool Call Tags: `<tool_call>` and `</tool_call>` wrap each individual call
/// - Each individual call is separated by `\n`
/// - Function Call Object: JSON object with "name" and "arguments" fields
///
/// Reference: https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct?chat_template=default
pub struct QwenParser {
/// Parser for handling incomplete JSON during streaming
partial_json: PartialJson,
@@ -49,8 +50,9 @@ pub struct QwenParser {
normal_text_buffer: String,
/// Token configuration
bot_token: &'static str,
eot_token: &'static str,
/// Start/end tokens for each individual tool call (not the entire sequence)
individual_tool_start_token: &'static str,
individual_tool_end_token: &'static str,
tool_call_separator: &'static str,
}
@@ -70,8 +72,8 @@ impl QwenParser {
current_tool_name_sent: false,
streamed_args_for_tool: Vec::new(),
normal_text_buffer: String::new(),
bot_token: "<tool_call>\n",
eot_token: "\n</tool_call>",
individual_tool_start_token: "<tool_call>\n",
individual_tool_end_token: "\n</tool_call>",
tool_call_separator: "\n",
}
}
@@ -157,11 +159,13 @@ impl ToolParser for QwenParser {
// Check if current_text has tool_call
let has_tool_start = self.has_tool_markers(current_text)
|| (self.current_tool_id >= 0 && current_text.starts_with(self.tool_call_separator));
|| (self.current_tool_id > 0 && current_text.starts_with(self.tool_call_separator));
if !has_tool_start {
// Only clear buffer if we're sure no tool call is starting
if helpers::ends_with_partial_token(&self.buffer, self.bot_token).is_none() {
if helpers::ends_with_partial_token(&self.buffer, self.individual_tool_start_token)
.is_none()
{
let normal_text = self.buffer.clone();
self.buffer.clear();
@@ -170,7 +174,7 @@ impl ToolParser for QwenParser {
calls: vec![],
});
} else {
// Might be partial bot_token, keep buffering
// Might be partial individual_tool_start_token, keep buffering
return Ok(StreamingParseResult::default());
}
}
@@ -179,9 +183,9 @@ impl ToolParser for QwenParser {
let tool_indices = helpers::get_tool_indices(tools);
// Determine start index for JSON parsing
let start_idx = if let Some(pos) = current_text.find(self.bot_token) {
pos + self.bot_token.len()
} else if self.current_tool_id >= 0 && current_text.starts_with(self.tool_call_separator) {
let start_idx = if let Some(pos) = current_text.find(self.individual_tool_start_token) {
pos + self.individual_tool_start_token.len()
} else if self.current_tool_id > 0 && current_text.starts_with(self.tool_call_separator) {
self.tool_call_separator.len()
} else {
0
@@ -205,7 +209,7 @@ impl ToolParser for QwenParser {
self.normal_text_buffer.push_str(&result.normal_text);
// Check if buffer contains complete end token (without leading newline)
let end_token_without_newline = &self.eot_token[1..]; // "</tool_call>"
let end_token_without_newline = &self.individual_tool_end_token[1..]; // "</tool_call>"
if self.normal_text_buffer.contains(end_token_without_newline) {
// Complete end token found - clean it and return
let cleaned_text = self