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

5
6
7
8
9
10
11
12
use crate::{
    protocols::common::Tool,
    tool_parser::{
        errors::{ParserError, ParserResult},
        parsers::helpers,
        traits::ToolParser,
        types::{FunctionCall, StreamingParseResult, ToolCall, ToolCallItem},
    },
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
};

/// 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,
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
    /// 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>,
48
49
50
51
52
53
54
55
56
57
58
59
}

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");

60
61
62
63
64
65
66
67
        // 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");

68
69
70
        Self {
            tool_call_extractor,
            func_detail_extractor,
71
72
73
74
75
76
77
            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(),
78
79
80
        }
    }

81
    /// Parse a single tool call block - throws error if parsing fails
82
    fn parse_tool_call(&self, block: &str) -> ParserResult<ToolCall> {
83
        let captures = self.func_detail_extractor.captures(block).ok_or_else(|| {
84
            ParserError::ParsingFailed("Failed to match tool call pattern".to_string())
85
86
87
88
89
        })?;

        // Get function type (should be "function")
        let func_type = captures.get(1).map_or("", |m| m.as_str());
        if func_type != "function" {
90
            return Err(ParserError::ParsingFailed(format!(
91
92
93
94
                "Invalid function type: {}",
                func_type
            )));
        }
95

96
97
98
        // Get function name
        let func_name = captures.get(2).map_or("", |m| m.as_str()).trim();
        if func_name.is_empty() {
99
            return Err(ParserError::ParsingFailed(
100
101
                "Empty function name".to_string(),
            ));
102
        }
103
104
105
106
107
108

        // 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)
109
            .map_err(|e| ParserError::ParsingFailed(format!("Invalid JSON: {}", e)))?;
110
111
112
113
114
115
116
117
118

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

119
120
        let arguments =
            serde_json::to_string(&args).map_err(|e| ParserError::ParsingFailed(e.to_string()))?;
121
122
123
124
125
126
127

        Ok(ToolCall {
            function: FunctionCall {
                name: func_name.to_string(),
                arguments,
            },
        })
128
129
130
131
132
133
134
135
136
137
138
    }
}

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

#[async_trait]
impl ToolParser for DeepSeekParser {
139
    async fn parse_complete(&self, text: &str) -> ParserResult<(String, Vec<ToolCall>)> {
140
        if !self.has_tool_markers(text) {
141
            return Ok((text.to_string(), vec![]));
142
143
        }

144
145
146
        // Find where tool calls begin
        let idx = text.find("<|tool▁calls▁begin|>").unwrap();
        let normal_text = text[..idx].to_string();
147

148
149
150
151
152
153
154
155
156
        // 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;
                }
157
158
159
            }
        }

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

        Ok((normal_text, tools))
166
167
168
    }

    async fn parse_incremental(
169
        &mut self,
170
        chunk: &str,
171
        tools: &[Tool],
172
    ) -> ParserResult<StreamingParseResult> {
173
174
175
176
177
178
        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|>");
179

180
        if !has_tool_call {
181
            // No tool markers detected - return all buffered content as normal text
182
183
184
185
186
187
188
189
190
            // 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![],
            });
191
192
        }

193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
        // 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());
214
            }
215

216
217
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
            // 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);
270
                    }
271
272
273
274
275
276
277
278
279
280
                }

                // 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);
281
282
283
                            }
                        }
                    }
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300

                    // 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);
301
302
303
304
                }
            }
        }

305
306
307
308
        Ok(StreamingParseResult {
            normal_text: String::new(),
            calls,
        })
309
310
    }

311
312
    fn has_tool_markers(&self, text: &str) -> bool {
        text.contains("<|tool▁calls▁begin|>")
313
    }
314
315
316
317

    fn get_unstreamed_tool_args(&self) -> Option<Vec<ToolCallItem>> {
        helpers::get_unstreamed_args(&self.prev_tool_call_arr, &self.streamed_args_for_tool)
    }
318
319
320
321
322
323
324
325

    fn reset(&mut self) {
        self.buffer.clear();
        self.prev_tool_call_arr.clear();
        self.current_tool_id = -1;
        self.current_tool_name_sent = false;
        self.streamed_args_for_tool.clear();
    }
326
}