deepseek.rs 12.3 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
};

/// 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
24
25
///
/// Reference: https://huggingface.co/deepseek-ai/DeepSeek-V3-0324?chat_template=default
26
27
28
29
30
pub struct DeepSeekParser {
    /// Regex for extracting complete tool calls
    tool_call_extractor: Regex,
    /// Regex for extracting function details
    func_detail_extractor: Regex,
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
    /// 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>,
50
51
52
53
54
55
56
57
58
59
60
61
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        Ok((normal_text, tools))
168
169
170
    }

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

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

195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
        // 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());
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
270
271
            // 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);
272
                    }
273
274
275
276
277
278
279
280
281
282
                }

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

                    // 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);
303
304
305
306
                }
            }
        }

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

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

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

    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();
    }
328
}