parser.rs 15.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
// SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

// Reference implementation:
// https://github.com/sgl-project/sglang/blob/44da737770e4bcd9bfa27751f0a0751c9b5c06e1/python/sglang/srt/function_call/qwen3_coder_detector.py

use std::collections::HashMap;

use regex::Regex;
use uuid::Uuid;

12
use super::super::config::XmlParserConfig;
13
14
15
16
use super::response::{CalledFunction, ToolCallResponse, ToolCallType};

/// Check if a chunk contains the start of a xml-style tool call.
/// Format: <tool_call><function=name><parameter=foo>...</parameter></function></tool_call>
17
pub fn detect_tool_call_start_xml(chunk: &str, config: &XmlParserConfig) -> bool {
18
    // Check for complete or partial start token.
19
    let start_token = &config.tool_call_start_token;
20
21

    // Check if we have the complete start token.
22
    if chunk.contains(start_token.as_str()) {
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
        return true;
    }

    // Check for partial match at the end of the chunk (for streaming).
    for i in 1..start_token.len() {
        if chunk.ends_with(&start_token[..i]) {
            return true;
        }
    }

    false
}

/// Find the end position of a Qwen3Coder tool call.
/// Returns the position after </tool_call> or the length of the chunk if not found.
38
39
pub fn find_tool_call_end_position_xml(chunk: &str, config: &XmlParserConfig) -> usize {
    let end_token = &config.tool_call_end_token;
40

41
    if let Some(pos) = chunk.find(end_token.as_str()) {
42
43
44
45
46
47
48
49
50
51
52
        pos + end_token.len()
    } else {
        chunk.len()
    }
}

/// Try to parse Qwen3Coder formatted tool calls from a message.
/// Format: <tool_call><function=name><parameter=key>value</parameter></function></tool_call>
/// Returns (parsed_tool_calls, normal_text_content)
pub fn try_tool_call_parse_xml(
    message: &str,
53
    config: &XmlParserConfig,
54
) -> anyhow::Result<(Vec<ToolCallResponse>, Option<String>)> {
55
    let (normal_text, tool_calls) = extract_tool_calls(message, config)?;
56
57
58
59
60
61
62
63
64
65
66

    let normal_content = if normal_text.is_empty() {
        Some("".to_string())
    } else {
        Some(normal_text)
    };

    Ok((tool_calls, normal_content))
}

/// Extract tool calls and normal text from message.
67
68
69
70
fn extract_tool_calls(
    text: &str,
    config: &XmlParserConfig,
) -> anyhow::Result<(String, Vec<ToolCallResponse>)> {
71
72
73
74
    let mut normal_parts = Vec::new();
    let mut calls = Vec::new();
    let mut cursor = 0;

75
76
    let start_token = &config.tool_call_start_token;
    let end_token = &config.tool_call_end_token;
77
78
79

    while cursor < text.len() {
        // Find next tool call start.
80
        if let Some(start_pos) = text[cursor..].find(start_token.as_str()) {
81
82
83
84
85
86
            let abs_start = cursor + start_pos;

            // Add text before tool call to normal parts.
            normal_parts.push(&text[cursor..abs_start]);

            // Find the corresponding end token.
87
            if let Some(end_pos) = text[abs_start..].find(end_token.as_str()) {
88
89
90
91
                let abs_end = abs_start + end_pos + end_token.len();
                let block = &text[abs_start..abs_end];

                // Parse this tool call block.
92
                if let Ok(mut parsed_calls) = parse_tool_call_block(block, config) {
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
                    calls.append(&mut parsed_calls);
                }

                cursor = abs_end;
            } else {
                // No end token found -> treat the rest as normal text.
                normal_parts.push(&text[abs_start..]);
                break;
            }
        } else {
            // No more tool calls.
            normal_parts.push(&text[cursor..]);
            break;
        }
    }

    let normal_text = normal_parts.join("").trim().to_string();
    Ok((normal_text, calls))
}

/// Parse a single tool call block
/// Format: <tool_call><function=name><parameter=key>value</parameter>...</function></tool_call>
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
fn parse_tool_call_block(
    block: &str,
    config: &XmlParserConfig,
) -> anyhow::Result<Vec<ToolCallResponse>> {
    // Build regex patterns based on config
    let function_start = regex::escape(&config.function_start_token);
    let function_end = regex::escape(&config.function_end_token);
    let parameter_start = regex::escape(&config.parameter_start_token);
    let parameter_end = regex::escape(&config.parameter_end_token);

    let function_pattern = format!(r"(?s){}([^>]+)>(.*?)(?:{}|$)", function_start, function_end);
    let parameter_pattern = format!(
        r"(?s){}([^>]+)>(.*?)(?:{}|$)",
        parameter_start, parameter_end
    );

    let function_regex = Regex::new(&function_pattern)?;
    let parameter_regex = Regex::new(&parameter_pattern)?;
133
134
135
136
137
138
139
140
141
142
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223

    let mut results = Vec::new();

    // Find all function blocks.
    for func_cap in function_regex.captures_iter(block) {
        let function_name = func_cap.get(1).map(|m| m.as_str().trim()).unwrap_or("");
        let function_body = func_cap.get(2).map(|m| m.as_str()).unwrap_or("");

        if function_name.is_empty() {
            continue;
        }

        // Parse parameters from the function body.
        let mut parameters: HashMap<String, serde_json::Value> = HashMap::new();

        for param_cap in parameter_regex.captures_iter(function_body) {
            let param_name = param_cap.get(1).map(|m| m.as_str().trim()).unwrap_or("");
            let param_value = param_cap.get(2).map(|m| m.as_str()).unwrap_or("");

            if !param_name.is_empty() {
                let parsed_value = safe_parse_value(param_value);
                parameters.insert(param_name.to_string(), parsed_value);
            }
        }

        // Create tool call response.
        let arguments_json = serde_json::to_string(&parameters)?;

        let tool_call = ToolCallResponse {
            id: format!("call-{}", Uuid::new_v4()),
            tp: ToolCallType::Function,
            function: CalledFunction {
                name: function_name.to_string(),
                arguments: arguments_json,
            },
        };

        results.push(tool_call);
    }

    Ok(results)
}

/// Safely parse a value - tries JSON, then falls back to string.
/// Mimics SGLang's `_safe_val` function in spirit.
fn safe_parse_value(raw: &str) -> serde_json::Value {
    // HTML unescape
    let unescaped = html_unescape(raw.trim());

    if let Ok(value) = serde_json::from_str::<serde_json::Value>(&unescaped) {
        return value;
    }

    if let Ok(num) = unescaped.parse::<i64>() {
        return serde_json::Value::Number(num.into());
    }

    if let Ok(num) = unescaped.parse::<f64>()
        && let Some(num_val) = serde_json::Number::from_f64(num)
    {
        return serde_json::Value::Number(num_val);
    }

    match unescaped.to_lowercase().as_str() {
        "true" => return serde_json::Value::Bool(true),
        "false" => return serde_json::Value::Bool(false),
        "null" | "none" => return serde_json::Value::Null,
        _ => {}
    }

    // Default to string, stripping newlines from start and end.
    serde_json::Value::String(unescaped.trim_matches('\n').to_string())
}

/// Simple HTML unescape for common entities.
fn html_unescape(s: &str) -> String {
    s.replace("&lt;", "<")
        .replace("&gt;", ">")
        .replace("&amp;", "&")
        .replace("&quot;", "\"")
        .replace("&#x27;", "'")
        .replace("&#39;", "'")
}

#[cfg(test)]
mod tests {
    use super::*;
    use rstest::rstest;

    #[test]
    fn test_detect_tool_call_start() {
224
225
226
227
228
229
230
        let config = XmlParserConfig::default();
        assert!(detect_tool_call_start_xml("<tool_call>", &config));
        assert!(detect_tool_call_start_xml("text <tool_call>", &config));
        assert!(detect_tool_call_start_xml("<tool_c", &config)); // Partial match
        assert!(detect_tool_call_start_xml("<", &config)); // Partial match
        assert!(!detect_tool_call_start_xml("no tool call here", &config));
        assert!(!detect_tool_call_start_xml("toolcall", &config));
231
232
233
234
    }

    #[test]
    fn test_find_tool_call_end_position() {
235
        let config = XmlParserConfig::default();
236
        let text = "<tool_call><function=test></function></tool_call>more text";
237
        let pos = find_tool_call_end_position_xml(text, &config);
238
239
240
241
        assert_eq!(pos, 49); // Position after </tool_call>
        assert_eq!(&text[pos..], "more text");

        let text_no_end = "<tool_call><function=test>";
242
        let pos = find_tool_call_end_position_xml(text_no_end, &config);
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
274
275
276
277
278
279
280
281
        assert_eq!(pos, text_no_end.len());
    }

    #[rstest]
    #[case(r#"{"key": "value"}"#, serde_json::json!({"key": "value"}), "JSON object")]
    #[case(r#"[1, 2, 3]"#, serde_json::json!([1, 2, 3]), "JSON array")]
    #[case("42", serde_json::json!(42), "integer")]
    #[case("3.15", serde_json::json!(3.15), "float")]
    #[case("true", serde_json::json!(true), "boolean true")]
    #[case("false", serde_json::json!(false), "boolean false")]
    #[case("null", serde_json::json!(null), "null")]
    #[case("hello", serde_json::json!("hello"), "unquoted string")]
    #[case("  text  ", serde_json::json!("text"), "trimmed string")]
    fn test_safe_parse_value(
        #[case] input: &str,
        #[case] expected: serde_json::Value,
        #[case] _description: &str,
    ) {
        assert_eq!(safe_parse_value(input), expected);
    }

    #[rstest]
    #[case("&lt;div&gt;", "<div>", "HTML tags")]
    #[case("a &amp; b", "a & b", "ampersand")]
    #[case("&quot;quoted&quot;", "\"quoted\"", "quotes")]
    fn test_html_unescape(#[case] input: &str, #[case] expected: &str, #[case] _description: &str) {
        assert_eq!(html_unescape(input), expected);
    }

    #[test]
    fn test_parse_simple_tool_call() {
        let input = r#"<tool_call>
<function=execute_bash>
<parameter=command>
pwd && ls
</parameter>
</function>
</tool_call>"#;

282
        let (calls, normal) = try_tool_call_parse_xml(input, &XmlParserConfig::default()).unwrap();
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].function.name, "execute_bash");
        assert_eq!(normal, Some("".to_string()));

        let args: serde_json::Value = serde_json::from_str(&calls[0].function.arguments).unwrap();
        assert_eq!(args["command"], "pwd && ls");
    }

    #[test]
    fn test_parse_multiple_parameters() {
        let input = r#"<tool_call>
<function=get_weather>
<parameter=city>
San Francisco
</parameter>
<parameter=state>
CA
</parameter>
<parameter=unit>
fahrenheit
</parameter>
</function>
</tool_call>"#;

307
        let (calls, _) = try_tool_call_parse_xml(input, &XmlParserConfig::default()).unwrap();
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].function.name, "get_weather");

        let args: serde_json::Value = serde_json::from_str(&calls[0].function.arguments).unwrap();
        assert_eq!(args["city"], "San Francisco");
        assert_eq!(args["state"], "CA");
        assert_eq!(args["unit"], "fahrenheit");
    }

    #[test]
    fn test_parse_with_normal_text() {
        let input = r#"I'll help you with that. <tool_call>
<function=get_weather>
<parameter=city>
Dallas
</parameter>
</function>
</tool_call> Let me check that for you."#;

327
        let (calls, normal) = try_tool_call_parse_xml(input, &XmlParserConfig::default()).unwrap();
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
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].function.name, "get_weather");
        assert_eq!(
            normal,
            Some("I'll help you with that.  Let me check that for you.".to_string())
        );
    }

    #[test]
    fn test_parse_multiple_tool_calls() {
        let input = r#"<tool_call>
<function=get_weather>
<parameter=city>
Dallas
</parameter>
</function>
</tool_call>
<tool_call>
<function=get_weather>
<parameter=city>
Orlando
</parameter>
</function>
</tool_call>"#;

353
        let (calls, _) = try_tool_call_parse_xml(input, &XmlParserConfig::default()).unwrap();
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
        assert_eq!(calls.len(), 2);
        assert_eq!(calls[0].function.name, "get_weather");
        assert_eq!(calls[1].function.name, "get_weather");

        let args0: serde_json::Value = serde_json::from_str(&calls[0].function.arguments).unwrap();
        let args1: serde_json::Value = serde_json::from_str(&calls[1].function.arguments).unwrap();
        assert_eq!(args0["city"], "Dallas");
        assert_eq!(args1["city"], "Orlando");
    }

    #[test]
    fn test_parse_json_parameter_value() {
        let input = r#"<tool_call>
<function=process_data>
<parameter=config>
{"setting": "value", "count": 42}
</parameter>
</function>
</tool_call>"#;

374
        let (calls, _) = try_tool_call_parse_xml(input, &XmlParserConfig::default()).unwrap();
375
376
377
378
379
380
381
382
383
384
385
        assert_eq!(calls.len(), 1);

        let args: serde_json::Value = serde_json::from_str(&calls[0].function.arguments).unwrap();
        assert!(args["config"].is_object());
        assert_eq!(args["config"]["setting"], "value");
        assert_eq!(args["config"]["count"], 42);
    }

    #[test]
    fn test_parse_no_tool_calls() {
        let input = "This is just normal text without any tool calls.";
386
        let (calls, normal) = try_tool_call_parse_xml(input, &XmlParserConfig::default()).unwrap();
387
388
389
390
391
392
393
394
395
396
397
398
399
        assert_eq!(calls.len(), 0);
        assert_eq!(normal, Some(input.to_string()));
    }

    #[test]
    fn test_parse_malformed_tool_call() {
        let input = r#"<tool_call>
<function=incomplete>
<parameter=test>
value
</tool_call>"#;

        // Should handle gracefully - might parse or return empty
400
        let result = try_tool_call_parse_xml(input, &XmlParserConfig::default());
401
402
403
404
405
406
407
408
409
410
411
412
        assert!(result.is_ok());
    }

    #[test]
    fn test_parse_missing_parameter_closing_tag() {
        let input = r#"<tool_call>
<function=execute_bash>
<parameter=command>
ls -la
</function>
</tool_call>"#;

413
        let (calls, _) = try_tool_call_parse_xml(input, &XmlParserConfig::default()).unwrap();
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].function.name, "execute_bash");

        let args: serde_json::Value = serde_json::from_str(&calls[0].function.arguments).unwrap();
        assert_eq!(args["command"], "ls -la");
    }

    #[test]
    fn test_parse_missing_function_closing_tag() {
        let input = r#"<tool_call>
<function=get_weather>
<parameter=city>
Boston
</parameter>
</tool_call>"#;

430
        let (calls, _) = try_tool_call_parse_xml(input, &XmlParserConfig::default()).unwrap();
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].function.name, "get_weather");

        let args: serde_json::Value = serde_json::from_str(&calls[0].function.arguments).unwrap();
        assert_eq!(args["city"], "Boston");
    }

    #[test]
    fn test_parse_missing_both_closing_tags() {
        let input = r#"<tool_call>
<function=run_query>
<parameter=sql>
SELECT * FROM users
</tool_call>"#;

446
        let (calls, _) = try_tool_call_parse_xml(input, &XmlParserConfig::default()).unwrap();
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].function.name, "run_query");

        let args: serde_json::Value = serde_json::from_str(&calls[0].function.arguments).unwrap();
        // This matches the original SGLang python implementation.
        assert_eq!(args["sql"], "SELECT * FROM users\n</tool_call>");
    }

    #[test]
    fn test_parse_multiple_parameters_missing_closing_tags() {
        let input = r#"<tool_call>
<function=search>
<parameter=query>
rust programming
<parameter=limit>
10
</function>
</tool_call>"#;

466
        let (calls, _) = try_tool_call_parse_xml(input, &XmlParserConfig::default()).unwrap();
467
468
469
470
471
472
473
474
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].function.name, "search");

        let args: serde_json::Value = serde_json::from_str(&calls[0].function.arguments).unwrap();
        // This matches the original SGLang python implementation.
        assert_eq!(args["query"], "rust programming\n<parameter=limit>\n10");
    }
}