deepseek_parser.rs 18.9 KB
Newer Older
1
2
3
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

4
use regex::RegexBuilder;
5
use serde_json::Value;
6
use uuid::Uuid;
7
8
9
10

use super::config::JsonParserConfig;
use super::response::{CalledFunction, ToolCallResponse, ToolCallType};

11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/// Extract individual tool call blocks from the input string.
/// Returns a list of strings, each representing one tool call block.
///
/// DeepSeek format: <|tool▁call▁begin|>{name}<|tool▁sep|>{args}<|tool▁call▁end|>
///
/// DeepSeek uses nested tokens:
/// - Wrapper tokens: <|tool▁calls▁begin|> ... <|tool▁calls▁end|> (wraps all tool calls)
/// - Individual tokens: <|tool▁call▁begin|> ... <|tool▁call▁end|> (individual call)
fn extract_tool_call_blocks(
    input: &str,
    start_tokens: &[String],
    end_tokens: &[String],
) -> Vec<String> {
    let mut blocks = Vec::new();

    // Filter tokens to find individual call markers (not the wrapper "calls" versions)
    let individual_start_tokens: Vec<&String> = start_tokens
        .iter()
        .filter(|t| t.contains("tool_call_begin") || t.contains("tool▁call▁begin"))
        .collect();
31

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
    let individual_end_tokens: Vec<&String> = end_tokens
        .iter()
        .filter(|t| t.contains("tool_call_end") || t.contains("tool▁call▁end"))
        .collect();

    // Try all combinations of individual start and end tokens
    for start_token in individual_start_tokens.iter() {
        for end_token in individual_end_tokens.iter() {
            if start_token.is_empty() || end_token.is_empty() {
                continue;
            }

            // Build regex pattern with escaped tokens
            let escaped_start = regex::escape(start_token);
            let escaped_end = regex::escape(end_token);
            let pattern = format!(r"{}(.*?){}", escaped_start, escaped_end);

            if let Ok(regex) = RegexBuilder::new(&pattern)
                .dot_matches_new_line(true)
                .build()
            {
                for capture in regex.captures_iter(input) {
                    if let Some(matched) = capture.get(1) {
                        // Don't trim the content - preserve whitespace for multiline JSON
                        let content = matched.as_str();
                        if !content.trim().is_empty() {
                            blocks.push(content.to_string());
                        }
                    }
                }

                // If we found matches with this token pair, don't try other combinations
                if !blocks.is_empty() {
                    return blocks;
                }
            }
        }
    }

    blocks
72
73
}

74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/// Parse a single tool call block that contains function name and arguments separated by a separator token.
///
/// Format: {function_name}<|tool▁sep|>{json_arguments}
fn parse_single_tool_call(block: &str, separator_tokens: &[String]) -> Option<(String, Value)> {
    // Try each separator token
    for sep_token in separator_tokens.iter() {
        if sep_token.is_empty() {
            continue;
        }

        if let Some((name_part, args_part)) = block.split_once(sep_token) {
            let function_name = name_part.trim();
            let args_str = args_part.trim();

            // Validate function name (should not be empty and should not contain JSON-like chars)
            if function_name.is_empty() || function_name.contains(['{', '}', '[', ']']) {
                continue;
            }

            // Try to parse arguments as JSON
            // First try parsing as-is
            if let Ok(arguments) = serde_json::from_str::<Value>(args_str) {
                return Some((function_name.to_string(), arguments));
            }

            // If that fails, try normalizing the JSON (handle multiline strings with unescaped newlines)
            // This is a lenient approach for malformed JSON that may come from LLMs
            let normalized = args_str
                .lines()
                .map(|line| line.trim_start())
                .collect::<Vec<_>>()
                .join(" ");

            if let Ok(arguments) = serde_json::from_str::<Value>(&normalized) {
                return Some((function_name.to_string(), arguments));
            }
        }
    }

    None
114
115
116
117
118
119
120
}

pub fn parse_tool_calls_deepseek_v3_1(
    message: &str,
    config: &JsonParserConfig,
) -> anyhow::Result<(Vec<ToolCallResponse>, Option<String>)> {
    // Format Structure:
121
    // <|tool▁calls▁begin|><|tool▁call▁begin|>{function_name}<|tool▁sep|>{json_arguments}<|tool▁call▁end|><|tool▁calls▁end|>
122
123
    let trimmed = message.trim();

124
125
126
127
128
    // Early exit if no content
    if trimmed.is_empty() {
        return Ok((vec![], Some(String::new())));
    }

129
    let tool_call_start_tokens = &config.tool_call_start_tokens;
130
131
    let tool_call_end_tokens = &config.tool_call_end_tokens;
    let separator_tokens = &config.tool_call_separator_tokens;
132

133
134
    // Early exit if no tokens configured
    if tool_call_start_tokens.is_empty() || separator_tokens.is_empty() {
135
136
137
        return Ok((vec![], Some(trimmed.to_string())));
    }

138
    // Check if tool call start token is present
139
    if !detect_tool_call_start_deepseek_v3_1(trimmed, config) {
140
141
142
        return Ok((vec![], Some(trimmed.to_string())));
    }

143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
    // Extract normal text (content before the first wrapper start token)
    // Look for wrapper tokens like <|tool▁calls▁begin|> (note: "calls" not "call")
    let wrapper_tokens: Vec<&String> = tool_call_start_tokens
        .iter()
        .filter(|t| t.contains("tool_calls_begin") || t.contains("tool▁calls▁begin"))
        .collect();

    let normal_text = if !wrapper_tokens.is_empty() {
        wrapper_tokens
            .iter()
            .find_map(|token| {
                trimmed
                    .find(token.as_str())
                    .map(|idx| trimmed[..idx].to_string())
            })
            .unwrap_or_else(String::new)
    } else {
        // Fallback to first individual call token if no wrapper found
        tool_call_start_tokens
            .iter()
            .filter(|token| !token.is_empty())
            .find_map(|token| trimmed.find(token).map(|idx| trimmed[..idx].to_string()))
            .unwrap_or_else(String::new)
    };

    // Extract individual tool call blocks
    let blocks = extract_tool_call_blocks(trimmed, tool_call_start_tokens, tool_call_end_tokens);

    if blocks.is_empty() {
        // Found start token but no valid blocks
        return Ok((vec![], Some(trimmed.to_string())));
    }
175

176
    // Parse each block to extract function name and arguments
177
    let mut tool_calls: Vec<ToolCallResponse> = Vec::new();
178
179
    for block in blocks {
        if let Some((function_name, arguments)) = parse_single_tool_call(&block, separator_tokens) {
180
            tool_calls.push(ToolCallResponse {
181
                id: format!("call-{}", Uuid::new_v4()),
182
183
                tp: ToolCallType::Function,
                function: CalledFunction {
184
                    name: function_name,
185
186
187
188
189
190
                    arguments: serde_json::to_string(&arguments)?,
                },
            });
        }
    }

191
    // If no valid tool calls were parsed, return everything as normal text
192
193
194
195
196
197
198
    if tool_calls.is_empty() {
        return Ok((vec![], Some(trimmed.to_string())));
    }

    Ok((tool_calls, Some(normal_text)))
}

199
200
pub fn detect_tool_call_start_deepseek_v3_1(chunk: &str, config: &JsonParserConfig) -> bool {
    let trimmed = chunk.trim();
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
    if trimmed.is_empty() {
        return false;
    }

    // Check for complete start tokens first
    let has_complete_token = config
        .tool_call_start_tokens
        .iter()
        .any(|token| !token.is_empty() && trimmed.contains(token));

    if has_complete_token {
        return true;
    }

    // Check for partial start tokens (streaming scenario)
    // This handles cases where start tokens are split across multiple chunks
    config.tool_call_start_tokens.iter().any(|token| {
        if token.is_empty() {
            return false;
        }
        // Check if the chunk could be a prefix of this start token
        // Handle Unicode character boundaries properly
        for i in 1..=token.chars().count() {
            if let Some(prefix) = token.chars().take(i).collect::<String>().get(..) {
                let prefix_str = &prefix[..prefix.len()];
                if trimmed == prefix_str || trimmed.ends_with(prefix_str) {
                    return true;
                }
            }
        }
        false
    })
233
234
}

235
236
#[cfg(test)]
mod tests {
237
    use super::super::config::ToolCallConfig;
238
239
240
241
242
243
244
245
246
247
    use super::*;

    fn extract_name_and_args(call: ToolCallResponse) -> (String, serde_json::Value) {
        let args: serde_json::Value = serde_json::from_str(&call.function.arguments).unwrap();
        (call.function.name, args)
    }

    #[test]
    fn test_parse_tool_calls_deepseek_v3_1_basic() {
        let text = r#"<|tool▁calls▁begin|><|tool▁call▁begin|>get_current_weather<|tool▁sep|>{"location": "Tokyo"}<|tool▁call▁end|><|tool▁call▁begin|>get_current_weather<|tool▁sep|>{"location": "Paris"}<|tool▁call▁end|><|tool▁calls▁end|><|end▁of▁sentence|>"#;
248
        let config = ToolCallConfig::deepseek_v3_1().json;
249
250
251
252
253
254
255
256
257
258
259
260
261
262
        let (result, content) = parse_tool_calls_deepseek_v3_1(text, &config).unwrap();
        assert_eq!(content, Some("".to_string()));
        assert_eq!(result.len(), 2);
        let (name, args) = extract_name_and_args(result[0].clone());
        assert_eq!(name, "get_current_weather");
        assert_eq!(args["location"], "Tokyo");
        let (name, args) = extract_name_and_args(result[1].clone());
        assert_eq!(name, "get_current_weather");
        assert_eq!(args["location"], "Paris");
    }

    #[test]
    fn test_parse_tool_calls_deepseek_v3_1_with_normal_text() {
        let text = r#"The following tool call retrieves weather information: <|tool▁calls▁begin|><|tool▁call▁begin|>get_current_weather<|tool▁sep|>{"location": "New York"}<|tool▁call▁end|><|tool▁calls▁end|><|end▁of▁sentence|>"#;
263
        let config = ToolCallConfig::deepseek_v3_1().json;
264
265
266
267
268
269
270
271
272
273
274
275
276
277
        let (result, content) = parse_tool_calls_deepseek_v3_1(text, &config).unwrap();
        assert_eq!(
            content,
            Some("The following tool call retrieves weather information: ".to_string())
        );
        assert_eq!(result.len(), 1);
        let (name, args) = extract_name_and_args(result[0].clone());
        assert_eq!(name, "get_current_weather");
        assert_eq!(args["location"], "New York");
    }

    #[test]
    fn test_parse_tool_calls_deepseek_v3_1_without_tool_call_start_token() {
        let text = r#"<|tool▁call▁begin|>get_current_weather宽带}{location": "Tokyo"}<|tool▁call▁end|><|tool▁calls▁end|>"#;
278
        let config = ToolCallConfig::deepseek_v3_1().json;
279
280
281
282
283
284
285
286
        let (result, content) = parse_tool_calls_deepseek_v3_1(text, &config).unwrap();
        assert_eq!(content, Some(text.to_string()));
        assert_eq!(result.len(), 0);
    }

    #[test]
    fn test_parse_tool_calls_deepseek_v3_1_with_multi_tool_calls_with_multiple_args() {
        let text = r#"<|tool▁calls▁begin|><|tool▁call▁begin|>get_current_weather<|tool▁sep|>{"location": "Berlin", "units": "metric"}<|tool▁call▁end|><|tool▁call▁begin|>get_weather_forecast<|tool▁sep|>{"location": "Berlin", "days": 7, "units": "imperial"}<|tool▁call▁end|><|tool▁call▁begin|>get_air_quality<|tool▁sep|>{"location": "Berlin", "radius": 50}<|tool▁call▁end|><|tool▁calls▁end|><|end▁of▁sentence|>"#;
287
        let config = ToolCallConfig::deepseek_v3_1().json;
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
        let (result, content) = parse_tool_calls_deepseek_v3_1(text, &config).unwrap();
        assert_eq!(content, Some("".to_string()));
        assert_eq!(result.len(), 3);
        let (name, args) = extract_name_and_args(result[0].clone());
        assert_eq!(name, "get_current_weather");
        assert_eq!(args["location"], "Berlin");
        assert_eq!(args["units"], "metric");
        let (name, args) = extract_name_and_args(result[1].clone());
        assert_eq!(name, "get_weather_forecast");
        assert_eq!(args["location"], "Berlin");
        assert_eq!(args["days"], 7);
        assert_eq!(args["units"], "imperial");
        let (name, args) = extract_name_and_args(result[2].clone());
        assert_eq!(name, "get_air_quality");
        assert_eq!(args["location"], "Berlin");
        assert_eq!(args["radius"], 50);
    }

    #[test]
    fn test_parse_tool_calls_deepseek_v3_1_with_invalid_json() {
        // Everything is normal text in case of invalid json
        let text = r#"<|tool▁calls▁begin|><|tool▁call▁begin|>get_current_weather}{location": "Tokyo"}<|tool▁call▁end|><|tool▁calls▁end|>"#;
310
        let config = ToolCallConfig::deepseek_v3_1().json;
311
312
313
314
315
316
317
318
319
        let (result, content) = parse_tool_calls_deepseek_v3_1(text, &config).unwrap();
        assert_eq!(content, Some(text.trim().to_string()));
        assert_eq!(result.len(), 0);
    }

    #[test]
    fn test_parse_tool_calls_deepseek_v3_1_with_multi_tool_calls_with_normal_text() {
        // Everything is normal text in case of invalid json
        let text = r#"The following tool calls retrieve weather information: <|tool▁calls▁begin|><|tool▁call▁begin|>get_current_weather宽带}{location": "Tokyo"}<|tool▁call▁end|><|tool▁call▁begin|>get_weather_forecast宽带}{location": "Berlin", "days": 7, "units": "imperial"}<|tool▁call▁end|><|tool▁call▁begin|>get_air_quality宽带}{location": "Berlin", "radius": 50}<|tool▁call▁end|><|tool▁calls▁end|>"#;
320
        let config = ToolCallConfig::deepseek_v3_1().json;
321
322
323
324
        let (result, content) = parse_tool_calls_deepseek_v3_1(text, &config).unwrap();
        assert_eq!(content, Some(text.trim().to_string()));
        assert_eq!(result.len(), 0);
    }
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381

    #[test]
    fn test_parse_tool_calls_deepseek_v3_1_with_multiline_json() {
        let text = r#"I'll help you understand this codebase. Let me start by exploring the structure and key
  files to provide you with a comprehensive
  explanation.<|tool▁calls▁begin|><|tool▁call▁begin|>TodoWrite<|tool▁sep|>{"todos":
  [{"content": "Explore the root directory structure", "status": "in_progress", "activeForm":
   "Exploring the root directory structure"}, {"content": "Examine package.json and
  configuration files", "status": "pending", "activeForm": "Examining package.json and
  configuration files"}, {"content": "Analyze source code structure and key modules",
  "status": "pending", "activeForm": "Analyzing source code structure and key modules"},
  {"content": "Identify main entry points and architectural patterns", "status": "pending",
  "activeForm": "Identifying main entry points and architectural patterns"}, {"content":
  "Summarize the codebase purpose and functionality", "status": "pending", "activeForm":
  "Summarizing the codebase purpose and
  functionality"}]}<|tool▁call▁end|><|tool▁calls▁end|>"#;
        let config = ToolCallConfig::deepseek_v3_1().json;

        let (tool_call_results, normal_content) =
            parse_tool_calls_deepseek_v3_1(text, &config).unwrap();

        assert_eq!(tool_call_results.len(), 1);

        let (name, args) = extract_name_and_args(tool_call_results[0].clone());
        assert_eq!(name, "TodoWrite");
        assert_eq!(tool_call_results[0].tp, ToolCallType::Function);

        let todos_array = args["todos"].as_array().unwrap();
        assert_eq!(todos_array.len(), 5);

        assert_eq!(
            todos_array[0]["content"],
            "Explore the root directory structure"
        );
        assert_eq!(todos_array[0]["status"], "in_progress");
        assert_eq!(
            todos_array[0]["activeForm"],
            "Exploring the root directory structure"
        );

        assert_eq!(
            todos_array[1]["content"],
            "Examine package.json and configuration files"
        );
        assert_eq!(todos_array[1]["status"], "pending");

        assert_eq!(
            todos_array[4]["content"],
            "Summarize the codebase purpose and functionality"
        );
        assert_eq!(todos_array[4]["status"], "pending");

        assert_eq!(
            normal_content,
            Some("I'll help you understand this codebase. Let me start by exploring the structure and key\n  files to provide you with a comprehensive\n  explanation.".to_string())
        );
    }
382
}
383
384
385

#[cfg(test)]
mod detect_parser_tests {
386
    use super::super::config::ToolCallConfig;
387
388
389
390
    use super::*;
    #[test]
    fn test_detect_tool_call_start_deepseek_v3_1_chunk_with_tool_call_start_token() {
        let text = r#"<|tool▁calls▁begin|><|tool▁call▁begin|>get_current_weather宽带}"#;
391
        let config = ToolCallConfig::deepseek_v3_1().json;
392
393
394
395
396
397
398
        let result = detect_tool_call_start_deepseek_v3_1(text, &config);
        assert!(result);
    }

    #[test]
    fn test_detect_tool_call_start_deepseek_v3_1_chunk_without_tool_call_start_token() {
        let text = r#"<|tool▁call▁begin|>get_current_weather宽带}"#;
399
        let config = ToolCallConfig::deepseek_v3_1().json;
400
        let result = detect_tool_call_start_deepseek_v3_1(text, &config);
401
        assert!(result);
402
403
404
405
406
    }

    #[test]
    fn test_detect_tool_call_start_deepseek_v3_1_chunk_with_tool_call_start_token_in_middle() {
        let text = r#"The following tool calls retrieve weather information: <|tool▁calls▁begin|><|tool▁call▁begin|>get_current_weather宽带}"#;
407
        let config = ToolCallConfig::deepseek_v3_1().json;
408
409
410
        let result = detect_tool_call_start_deepseek_v3_1(text, &config);
        assert!(result);
    }
411
412
413
414

    #[test]
    fn test_detect_tool_call_start_deepseek_v3_1_partial_tokens() {
        // Test partial token detection for streaming scenarios with unicode characters
415
        let config = ToolCallConfig::deepseek_v3_1().json;
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444

        // Test various partial prefixes
        assert!(
            detect_tool_call_start_deepseek_v3_1("<", &config),
            "'<' should be detected as potential start"
        );
        assert!(
            detect_tool_call_start_deepseek_v3_1("<|", &config),
            "'<|' should be detected as potential start"
        );
        assert!(
            detect_tool_call_start_deepseek_v3_1("<|tool", &config),
            "'<|tool' should be detected as potential start"
        );
        assert!(
            detect_tool_call_start_deepseek_v3_1("<|tool▁calls", &config),
            "'<|tool▁calls' should be detected as potential start"
        );

        // Test that unrelated text is not detected
        assert!(
            !detect_tool_call_start_deepseek_v3_1("hello world", &config),
            "'hello world' should not be detected"
        );
        assert!(
            !detect_tool_call_start_deepseek_v3_1("xyz", &config),
            "'xyz' should not be detected"
        );
    }
445
}