deepseek_parser.rs 12.1 KB
Newer Older
1
2
3
4
use async_trait::async_trait;
use regex::Regex;
use serde_json::Value;

5
6
use crate::protocols::spec::Tool;

7
8
use crate::tool_parser::{
    errors::{ToolParserError, ToolParserResult},
9
    parsers::helpers,
10
    traits::ToolParser,
11
    types::{FunctionCall, StreamingParseResult, ToolCall, ToolCallItem},
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
};

/// DeepSeek V3 format parser for tool calls
///
/// Handles the DeepSeek V3 specific format that uses Unicode tokens:
/// `<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>{name}\n```json\n{args}\n```<|tool▁call▁end|><|tool▁calls▁end|>`
///
/// Features:
/// - Unicode token delimiters
/// - JSON arguments in code blocks
/// - Support for multiple sequential tool calls
pub struct DeepSeekParser {
    /// Regex for extracting complete tool calls
    tool_call_extractor: Regex,
    /// Regex for extracting function details
    func_detail_extractor: Regex,
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
    /// Regex for matching partial tool calls during streaming
    partial_tool_call_regex: Regex,
    /// Regex pattern for removing completed tool calls from buffer
    tool_call_end_pattern: Regex,

    /// Buffer for accumulating incomplete patterns across chunks
    buffer: String,

    /// Stores complete tool call info (name and arguments) for each tool being parsed
    prev_tool_call_arr: Vec<Value>,

    /// Index of currently streaming tool call (-1 means no active tool)
    current_tool_id: i32,

    /// Flag for whether current tool's name has been sent to client
    current_tool_name_sent: bool,

    /// Tracks raw JSON string content streamed to client for each tool's arguments
    streamed_args_for_tool: Vec<String>,
47
48
49
50
51
52
53
54
55
56
57
58
}

impl DeepSeekParser {
    /// Create a new DeepSeek parser
    pub fn new() -> Self {
        // Use (?s) flag for DOTALL mode to handle newlines
        let tool_call_pattern = r"(?s)<|tool▁call▁begin|>.*?<|tool▁call▁end|>";
        let tool_call_extractor = Regex::new(tool_call_pattern).expect("Valid regex pattern");

        let func_detail_pattern = r"(?s)<|tool▁call▁begin|>(.*?)<|tool▁sep|>(.*?)\n```json\n(.*?)\n```<|tool▁call▁end|>";
        let func_detail_extractor = Regex::new(func_detail_pattern).expect("Valid regex pattern");

59
60
61
62
63
64
65
66
        // Partial pattern for streaming - uses .* (greedy) not .*? to match all partial content
        let partial_pattern = r"(?s)<|tool▁call▁begin|>(.*)<|tool▁sep|>(.*)\n```json\n(.*)";
        let partial_tool_call_regex = Regex::new(partial_pattern).expect("Valid regex pattern");

        // Pattern for removing completed tool calls
        let end_pattern = r"(?s)<|tool▁call▁begin|>.*?<|tool▁call▁end|>";
        let tool_call_end_pattern = Regex::new(end_pattern).expect("Valid regex pattern");

67
68
69
        Self {
            tool_call_extractor,
            func_detail_extractor,
70
71
72
73
74
75
76
            partial_tool_call_regex,
            tool_call_end_pattern,
            buffer: String::new(),
            prev_tool_call_arr: Vec::new(),
            current_tool_id: -1,
            current_tool_name_sent: false,
            streamed_args_for_tool: Vec::new(),
77
78
79
80
81
82
83
84
        }
    }

    /// Check if text contains DeepSeek tool markers
    fn has_tool_markers(&self, text: &str) -> bool {
        text.contains("<|tool▁calls▁begin|>")
    }

85
86
87
88
89
90
91
92
93
94
95
96
97
98
    /// Parse a single tool call block - throws error if parsing fails
    fn parse_tool_call(&self, block: &str) -> ToolParserResult<ToolCall> {
        let captures = self.func_detail_extractor.captures(block).ok_or_else(|| {
            ToolParserError::ParsingFailed("Failed to match tool call pattern".to_string())
        })?;

        // Get function type (should be "function")
        let func_type = captures.get(1).map_or("", |m| m.as_str());
        if func_type != "function" {
            return Err(ToolParserError::ParsingFailed(format!(
                "Invalid function type: {}",
                func_type
            )));
        }
99

100
101
102
103
104
105
        // Get function name
        let func_name = captures.get(2).map_or("", |m| m.as_str()).trim();
        if func_name.is_empty() {
            return Err(ToolParserError::ParsingFailed(
                "Empty function name".to_string(),
            ));
106
        }
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131

        // Get JSON arguments
        let json_args = captures.get(3).map_or("{}", |m| m.as_str()).trim();

        // Parse JSON arguments
        let value = serde_json::from_str::<Value>(json_args)
            .map_err(|e| ToolParserError::ParsingFailed(format!("Invalid JSON: {}", e)))?;

        // Create arguments object
        let args = if value.is_object() {
            value
        } else {
            // If not an object, wrap it
            serde_json::json!({ "value": value })
        };

        let arguments = serde_json::to_string(&args)
            .map_err(|e| ToolParserError::ParsingFailed(e.to_string()))?;

        Ok(ToolCall {
            function: FunctionCall {
                name: func_name.to_string(),
                arguments,
            },
        })
132
133
134
135
136
137
138
139
140
141
142
    }
}

impl Default for DeepSeekParser {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl ToolParser for DeepSeekParser {
143
    async fn parse_complete(&self, text: &str) -> ToolParserResult<(String, Vec<ToolCall>)> {
144
        if !self.has_tool_markers(text) {
145
            return Ok((text.to_string(), vec![]));
146
147
        }

148
149
150
        // Find where tool calls begin
        let idx = text.find("<|tool▁calls▁begin|>").unwrap();
        let normal_text = text[..idx].to_string();
151

152
153
154
155
156
157
158
159
160
        // Try to extract tool calls, log warnings for failures
        let mut tools = Vec::new();
        for mat in self.tool_call_extractor.find_iter(text) {
            match self.parse_tool_call(mat.as_str()) {
                Ok(tool) => tools.push(tool),
                Err(e) => {
                    tracing::warn!("Failed to parse tool call: {}", e);
                    continue;
                }
161
162
163
            }
        }

164
165
166
167
        // If no tools were successfully parsed despite having markers, return entire text as fallback
        if tools.is_empty() {
            return Ok((text.to_string(), vec![]));
        }
168
169

        Ok((normal_text, tools))
170
171
172
    }

    async fn parse_incremental(
173
        &mut self,
174
        chunk: &str,
175
176
177
178
179
180
181
182
        tools: &[Tool],
    ) -> ToolParserResult<StreamingParseResult> {
        self.buffer.push_str(chunk);
        let current_text = &self.buffer.clone();

        // Check if we have a tool call (either the start token or individual tool call)
        let has_tool_call =
            self.has_tool_markers(current_text) || current_text.contains("<|tool▁call▁begin|>");
183

184
        if !has_tool_call {
185
            // No tool markers detected - return all buffered content as normal text
186
187
188
189
190
191
192
193
194
            // Strip out end tokens if present
            let mut normal_text = std::mem::take(&mut self.buffer);
            for e_token in ["<|tool▁calls▁end|>", "```", "<|tool▁call▁end|>"] {
                normal_text = normal_text.replace(e_token, "");
            }
            return Ok(StreamingParseResult {
                normal_text,
                calls: vec![],
            });
195
196
        }

197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
        // Build tool indices for validation
        let tool_indices = helpers::get_tool_indices(tools);

        let mut calls: Vec<ToolCallItem> = Vec::new();

        // Try to match the partial tool call pattern
        if let Some(captures) = self.partial_tool_call_regex.captures(current_text) {
            let func_name = captures.get(2).map_or("", |m| m.as_str()).trim();
            let func_args_raw = captures.get(3).map_or("", |m| m.as_str()).trim();

            // Validate tool name
            if !tool_indices.contains_key(func_name) {
                // Invalid tool name - skip this tool, preserve indexing for next tool
                tracing::warn!("Invalid tool name '{}' - skipping", func_name);
                helpers::reset_current_tool_state(
                    &mut self.buffer,
                    &mut self.current_tool_name_sent,
                    &mut self.streamed_args_for_tool,
                    &self.prev_tool_call_arr,
                );
                return Ok(StreamingParseResult::default());
218
            }
219

220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
            // Initialize state if this is the first tool call
            if self.current_tool_id == -1 {
                self.current_tool_id = 0;
                self.prev_tool_call_arr = Vec::new();
                self.streamed_args_for_tool = vec![String::new()];
            }

            // Ensure we have enough entries in our tracking arrays
            helpers::ensure_capacity(
                self.current_tool_id,
                &mut self.prev_tool_call_arr,
                &mut self.streamed_args_for_tool,
            );

            // Send tool name if not sent yet
            if !self.current_tool_name_sent {
                calls.push(ToolCallItem {
                    tool_index: self.current_tool_id as usize,
                    name: Some(func_name.to_string()),
                    parameters: String::new(),
                });
                self.current_tool_name_sent = true;

                // Store the tool call info for serving layer completions endpoint
                let tool_id = self.current_tool_id as usize;
                if self.prev_tool_call_arr.len() <= tool_id {
                    self.prev_tool_call_arr
                        .resize_with(tool_id + 1, || Value::Null);
                }
                self.prev_tool_call_arr[tool_id] = serde_json::json!({
                    "name": func_name,
                    "arguments": {},
                });
            } else {
                // Compute incremental diff
                let tool_id = self.current_tool_id as usize;
                let last_sent = self
                    .streamed_args_for_tool
                    .get(tool_id)
                    .map(|s| s.as_str())
                    .unwrap_or("");

                let argument_diff = func_args_raw
                    .strip_prefix(last_sent)
                    .unwrap_or(func_args_raw);

                if !argument_diff.is_empty() {
                    calls.push(ToolCallItem {
                        tool_index: tool_id,
                        name: None,
                        parameters: argument_diff.to_string(),
                    });
                    if tool_id < self.streamed_args_for_tool.len() {
                        self.streamed_args_for_tool[tool_id].push_str(argument_diff);
274
                    }
275
276
277
278
279
280
281
282
283
284
                }

                // Check if JSON is complete
                if helpers::is_complete_json(func_args_raw) {
                    // Update the stored arguments
                    if let Ok(parsed_args) = serde_json::from_str::<Value>(func_args_raw) {
                        let tool_id = self.current_tool_id as usize;
                        if tool_id < self.prev_tool_call_arr.len() {
                            if let Some(obj) = self.prev_tool_call_arr[tool_id].as_object_mut() {
                                obj.insert("arguments".to_string(), parsed_args);
285
286
287
                            }
                        }
                    }
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304

                    // Find the end of the current tool call and remove only that part from buffer
                    if let Some(mat) = self.tool_call_end_pattern.find(current_text) {
                        // Remove the completed tool call from buffer, keep any remaining content
                        self.buffer = current_text[mat.end()..].to_string();
                    } else {
                        self.buffer.clear();
                    }

                    let result = StreamingParseResult {
                        normal_text: String::new(),
                        calls,
                    };

                    self.current_tool_id += 1;
                    self.current_tool_name_sent = false;
                    return Ok(result);
305
306
307
308
                }
            }
        }

309
310
311
312
        Ok(StreamingParseResult {
            normal_text: String::new(),
            calls,
        })
313
314
315
316
317
    }

    fn detect_format(&self, text: &str) -> bool {
        self.has_tool_markers(text)
    }
318
319
320
321

    fn get_unstreamed_tool_args(&self) -> Option<Vec<ToolCallItem>> {
        helpers::get_unstreamed_args(&self.prev_tool_call_arr, &self.streamed_args_for_tool)
    }
322
}