parser.rs 32.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
// 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;
10
use serde_json::Value;
11
12
use uuid::Uuid;

13
use super::super::ToolDefinition;
14
use super::super::config::XmlParserConfig;
15
16
17
18
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>
19
pub fn detect_tool_call_start_xml(chunk: &str, config: &XmlParserConfig) -> bool {
20
    // Check for complete or partial start token.
21
    let start_token = &config.tool_call_start_token;
22
23

    // Check if we have the complete start token.
24
    if chunk.contains(start_token.as_str()) {
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
        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.
40
41
pub fn find_tool_call_end_position_xml(chunk: &str, config: &XmlParserConfig) -> usize {
    let end_token = &config.tool_call_end_token;
42

43
    if let Some(pos) = chunk.find(end_token.as_str()) {
44
45
46
47
48
49
50
51
52
53
54
        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,
55
    config: &XmlParserConfig,
56
    tools: Option<&[ToolDefinition]>,
57
) -> anyhow::Result<(Vec<ToolCallResponse>, Option<String>)> {
58
    let (normal_text, tool_calls) = extract_tool_calls(message, config, tools)?;
59
60
61
62
63
64
65
66
67
68
69

    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.
70
71
72
fn extract_tool_calls(
    text: &str,
    config: &XmlParserConfig,
73
    tools: Option<&[ToolDefinition]>,
74
) -> anyhow::Result<(String, Vec<ToolCallResponse>)> {
75
76
77
78
    let mut normal_parts = Vec::new();
    let mut calls = Vec::new();
    let mut cursor = 0;

79
80
    let start_token = &config.tool_call_start_token;
    let end_token = &config.tool_call_end_token;
81
82
83

    while cursor < text.len() {
        // Find next tool call start.
84
        if let Some(start_pos) = text[cursor..].find(start_token.as_str()) {
85
86
87
88
89
90
            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.
91
            if let Some(end_pos) = text[abs_start..].find(end_token.as_str()) {
92
93
94
95
                let abs_end = abs_start + end_pos + end_token.len();
                let block = &text[abs_start..abs_end];

                // Parse this tool call block.
96
                if let Ok(mut parsed_calls) = parse_tool_call_block(block, config, tools) {
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
                    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>
119
120
121
fn parse_tool_call_block(
    block: &str,
    config: &XmlParserConfig,
122
    tools: Option<&[ToolDefinition]>,
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
) -> 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)?;
138
139
140
141
142
143
144
145
146
147
148
149

    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;
        }

150
151
152
        // Get parameter config for this function
        let param_config = get_arguments_config(function_name, tools);

153
154
155
156
157
158
159
160
        // 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() {
161
162
                let parsed_value =
                    convert_param_value(param_value, param_name, &param_config, function_name);
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
                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)
}

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
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
/// Extract argument configuration for a function from the tool definitions.
/// Returns a HashMap of parameter names to their schema definitions.
fn get_arguments_config(
    func_name: &str,
    tools: Option<&[ToolDefinition]>,
) -> HashMap<String, Value> {
    let Some(tools) = tools else {
        return HashMap::new();
    };

    for tool in tools {
        if tool.name == func_name {
            if let Some(params) = &tool.parameters {
                // Try to extract "properties" from the parameters schema
                if let Some(properties) = params.get("properties") {
                    if let Some(props_obj) = properties.as_object() {
                        return props_obj
                            .iter()
                            .map(|(k, v)| (k.clone(), v.clone()))
                            .collect();
                    }
                } else if let Some(params_obj) = params.as_object() {
                    // If no "properties" field, treat the whole thing as the config
                    return params_obj
                        .iter()
                        .map(|(k, v)| (k.clone(), v.clone()))
                        .collect();
                }
            }
            return HashMap::new();
        }
    }

    tracing::warn!("Tool '{}' is not defined in the tools list.", func_name);
    HashMap::new()
}

/// Convert parameter value based on its type in the schema.
/// This matches the behavior of the Python implementation.
/// Converts a string parameter value from XML into a typed JSON Value.
///
/// # Examples
///
/// **String types:**
/// ```text
/// Input:  param_value="hello world", param_type="string"
/// Output: Value::String("hello world")
/// ```
///
/// ```text
/// Input:  param_value="42", param_type="string"
/// Output: Value::String("42")
/// ```
///
/// **Integer types:**
/// ```text
/// Input:  param_value="42", param_type="integer"
/// Output: Value::Number(42)
///
/// Input:  param_value="not_a_number", param_type="int"
/// Output: Value::String("not_a_number")  // Falls back to string with warning
/// ```
///
/// **Float/Number types:**
/// ```text
/// Input:  param_value="3.14", param_type="number"
/// Output: Value::Number(3.14)
///
/// Input:  param_value="42.0", param_type="float"
/// Output: Value::Number(42)  // Whole numbers stored as integers
/// ```
///
/// **Boolean types:**
/// ```text
/// Input:  param_value="true", param_type="boolean"
/// Output: Value::Bool(true)
///
/// Input:  param_value="yes", param_type="bool"
/// Output: Value::Bool(false)  // Falls back to false with warning
/// ```
///
/// **Complex types (objects/arrays):**
/// ```text
/// Input:  param_value='{"key": "value"}', param_type="object"
/// Output: Value::Object({"key": "value"})
///
/// Input:  param_value="[1, 2, 3]", param_type="array"
/// Output: Value::Array([1, 2, 3])
///
/// Input:  param_value="{'key': 'value'}", param_type="dict"
/// Output: Value::Object({"key": "value"})  // Uses ast.literal_eval-style parsing
/// ```
///
/// **Special cases:**
/// ```text
/// Input:  param_value="null", param_type=<any>
/// Output: Value::Null  // Handled before type checking
///
/// Input:  param_value="&lt;tag&gt;", param_type="string"
/// Output: Value::String("<tag>")  // HTML entities are unescaped
///
/// Input:  param_value="123", param_type=<undefined/not in schema>
/// Output: Value::String("123")  // Unknown params returned as strings
/// ```
///
/// # Arguments
///
/// * `param_value` - The raw string value from XML parameter
/// * `param_name` - The parameter name (used for schema lookup and error messages)
/// * `param_config` - Schema defining expected types for each parameter
/// * `func_name` - The function/tool name (used for error messages)
///
/// # Type Aliases
///
/// The function recognizes various type name aliases:
/// - Strings: "string", "str", "text", "varchar", "char", "enum"
/// - Integers: "int", "integer", "int32", "int64", "uint", "long", "short", "unsigned"
/// - Numbers: "number", "num", "float", "float32", "float64", "double"
/// - Booleans: "boolean", "bool", "binary"
/// - Objects: "object", "dict", "dictionary"
/// - Arrays: "array", "arr", "list"
fn convert_param_value(
    param_value: &str,
    param_name: &str,
    param_config: &HashMap<String, Value>,
    func_name: &str,
) -> Value {
    // HTML unescape and trim
    let param_value = html_unescape(param_value.trim());

    // Handle null
    if param_value.to_lowercase() == "null" {
        return Value::Null;
    }

    // Check if parameter is in config
    if !param_config.contains_key(param_name) {
        tracing::debug!(
            "Parsed parameter '{}' is not defined in the tool parameters for tool '{}', directly returning the string value.",
            param_name,
            func_name
        );
        return Value::String(param_value);
    }

    // Get the type from schema
    let param_type = param_config
        .get(param_name)
        .and_then(|v| v.get("type"))
        .and_then(|t| t.as_str())
        .unwrap_or("string")
        .to_lowercase();

    // The follow `match` block follows this rough pattern for each block:
    // 1. Match `param_type` against predefined string representations of each type,
    // 2. Parse the string value and convert it to the appropriate Rust JSON Value type.
    // Each branch handles a category of type aliases (e.g., "int"/"integer"/"int32" all map to i64).
    // If parsing fails, we log a warning and fall back to returning the value as a string.
    match param_type.as_str() {
        // String types: Return value as-is (already HTML-unescaped above)
        "string" | "str" | "text" | "varchar" | "char" | "enum" => Value::String(param_value),

        // Integer types: Parse as i64, fall back to string on error.
        // Matches: "int", "integer", "int32", "uint", "unsigned", "long", "short", etc.
        t if t.starts_with("int")
            || t.starts_with("uint")
            || t.starts_with("long")
            || t.starts_with("short")
            || t.starts_with("unsigned") =>
        {
            match param_value.parse::<i64>() {
                Ok(int_val) => Value::Number(int_val.into()),
                Err(_) => {
                    tracing::warn!(
                        "Parsed value '{}' of parameter '{}' is not an integer in tool '{}', degenerating to string.",
                        param_value,
                        param_name,
                        func_name
                    );
                    Value::String(param_value)
                }
            }
        }

        // Float/Number types: Parse as f64.
        // Matches: "number", "num", "float", "float32", "float64", "double", etc.
        // Note: Whole numbers (e.g., 42.0) are stored as integers for better JSON compatibility.
        t if t.starts_with("num") || t.starts_with("float") => {
            match param_value.parse::<f64>() {
                Ok(float_val) => {
                    // Return int if it's a whole number, otherwise float.
                    if float_val.fract() == 0.0 && float_val.is_finite() {
                        Value::Number((float_val as i64).into())
                    } else if let Some(num) = serde_json::Number::from_f64(float_val) {
                        Value::Number(num)
                    } else {
                        tracing::warn!(
                            "Parsed value '{}' of parameter '{}' is not a valid float in tool '{}', degenerating to string.",
                            param_value,
                            param_name,
                            func_name
                        );
                        Value::String(param_value)
                    }
                }
                Err(_) => {
                    tracing::warn!(
                        "Parsed value '{}' of parameter '{}' is not a float in tool '{}', degenerating to string.",
                        param_value,
                        param_name,
                        func_name
                    );
                    Value::String(param_value)
                }
            }
        }

        // Boolean types: Only "true" or "false" (case-insensitive) are valid.
        // Any other value defaults to false with a warning.
        "boolean" | "bool" | "binary" => {
            let lower_val = param_value.to_lowercase();
            if lower_val != "true" && lower_val != "false" {
                tracing::warn!(
                    "Parsed value '{}' of parameter '{}' is not a boolean (`true` or `false`) in tool '{}', degenerating to false.",
                    param_value,
                    param_name,
                    func_name
                );
            }
            Value::Bool(lower_val == "true")
        }

        // Complex types (objects/arrays): Try JSON parsing, then fall back to Python-style
        // `ast.literal_eval` (or our own barebones version of it for the purposes of this
        // parser).
        // Matches: "object", "array", "arr", "dict", "dictionary", "list", etc.
        // This handles both JSON syntax ({"a": 1}) and Python syntax ({'a': 1}).
        t if t == "object"
            || t == "array"
            || t == "arr"
            || t.starts_with("dict")
            || t.starts_with("list") =>
        {
            // Try JSON parsing first (standard JSON with double quotes).
            if let Ok(json_val) = serde_json::from_str::<Value>(&param_value) {
                return json_val;
            }

            tracing::warn!(
                "Parsed value '{}' of parameter '{}' cannot be parsed with json.loads in tool '{}', will try other methods to parse it.",
                param_value,
                param_name,
                func_name
            );

            // Try `ast.literal_eval` equivalent (handles Python-style single quotes, etc.).
            if let Ok(json_val) = try_literal_eval(&param_value) {
                return json_val;
            }

            tracing::warn!(
                "Parsed value '{}' of parameter '{}' cannot be converted via Python `ast.literal_eval()` in tool '{}', degenerating to string.",
                param_value,
                param_name,
                func_name
            );
            Value::String(param_value)
        }

        // Unknown/custom types: Attempt best-effort parsing via `literal_eval`.
        // This allows for flexible type names while still trying to parse structured data
        _ => {
            // Unknown type, try `literal_eval`.
            if let Ok(json_val) = try_literal_eval(&param_value) {
                return json_val;
            }

            tracing::warn!(
                "Parsed value '{}' of parameter '{}' cannot be converted via Python `ast.literal_eval()` in tool '{}', degenerating to string.",
                param_value,
                param_name,
                func_name
            );
            Value::String(param_value)
        }
    }
}

/// Try to parse a value similar to Python's ast.literal_eval.
/// This is a simplified version that handles common cases.
fn try_literal_eval(s: &str) -> Result<Value, ()> {
    // First try standard JSON
    if let Ok(val) = serde_json::from_str::<Value>(s) {
        return Ok(val);
    }

    // Try to handle Python-style literals (single quotes, True/False/None)
    let normalized = s
        .replace('\'', "\"") // Replace single quotes with double quotes
        .replace("True", "true")
        .replace("False", "false")
        .replace("None", "null");

    serde_json::from_str::<Value>(&normalized).map_err(|_| ())
}

491
492
/// Safely parse a value - tries JSON, then falls back to string.
/// Mimics SGLang's `_safe_val` function in spirit.
493
494
/// NOTE: This function is deprecated and kept for reference. Use convert_param_value instead.
#[allow(dead_code)]
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
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() {
541
542
543
544
545
546
547
        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));
548
549
550
551
    }

    #[test]
    fn test_find_tool_call_end_position() {
552
        let config = XmlParserConfig::default();
553
        let text = "<tool_call><function=test></function></tool_call>more text";
554
        let pos = find_tool_call_end_position_xml(text, &config);
555
556
557
558
        assert_eq!(pos, 49); // Position after </tool_call>
        assert_eq!(&text[pos..], "more text");

        let text_no_end = "<tool_call><function=test>";
559
        let pos = find_tool_call_end_position_xml(text_no_end, &config);
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
        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>"#;

599
600
        let (calls, normal) =
            try_tool_call_parse_xml(input, &XmlParserConfig::default(), None).unwrap();
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
        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>"#;

625
        let (calls, _) = try_tool_call_parse_xml(input, &XmlParserConfig::default(), None).unwrap();
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
        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."#;

645
646
        let (calls, normal) =
            try_tool_call_parse_xml(input, &XmlParserConfig::default(), None).unwrap();
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
        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>"#;

672
        let (calls, _) = try_tool_call_parse_xml(input, &XmlParserConfig::default(), None).unwrap();
673
674
675
676
677
678
679
680
681
682
683
684
        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() {
685
686
687
688
689
690
691
692
693
694
695
        // With schema-aware parsing, we need to provide a schema to parse JSON objects
        let tools = vec![ToolDefinition {
            name: "process_data".to_string(),
            parameters: Some(serde_json::json!({
                "type": "object",
                "properties": {
                    "config": {"type": "object"}
                }
            })),
        }];

696
697
698
699
700
701
702
703
        let input = r#"<tool_call>
<function=process_data>
<parameter=config>
{"setting": "value", "count": 42}
</parameter>
</function>
</tool_call>"#;

704
705
        let (calls, _) =
            try_tool_call_parse_xml(input, &XmlParserConfig::default(), Some(&tools)).unwrap();
706
707
708
709
710
711
712
713
714
715
716
        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.";
717
718
        let (calls, normal) =
            try_tool_call_parse_xml(input, &XmlParserConfig::default(), None).unwrap();
719
720
721
722
723
724
725
726
727
728
729
730
731
        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
732
        let result = try_tool_call_parse_xml(input, &XmlParserConfig::default(), None);
733
734
735
736
737
738
739
740
741
742
743
744
        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>"#;

745
        let (calls, _) = try_tool_call_parse_xml(input, &XmlParserConfig::default(), None).unwrap();
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
        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>"#;

762
        let (calls, _) = try_tool_call_parse_xml(input, &XmlParserConfig::default(), None).unwrap();
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
        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>"#;

778
        let (calls, _) = try_tool_call_parse_xml(input, &XmlParserConfig::default(), None).unwrap();
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
        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>"#;

798
        let (calls, _) = try_tool_call_parse_xml(input, &XmlParserConfig::default(), None).unwrap();
799
800
801
802
803
804
805
        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");
    }
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933

    #[test]
    fn test_schema_aware_type_conversion() {
        // This test matches the Python test_parse_streaming_increment_multiple_parameters
        // from the diff, showing schema-aware type conversion
        let tools = vec![ToolDefinition {
            name: "multi_param_func".to_string(),
            parameters: Some(serde_json::json!({
                "type": "object",
                "properties": {
                    "param1": {"type": "string"},
                    "param2": {"type": "float"},
                    "param3": {"type": "integer"},
                    "param4": {"type": "boolean"},
                    "param5": {"type": "object"},
                    "param6": {"type": "array"},
                    "param7": {"type": "null"},
                    "param8": {"type": "other_type"}
                },
                "required": ["param1", "param2", "param3", "param4", "param5", "param6", "param7", "param8"]
            })),
        }];

        let input = r#"<tool_call>
<function=multi_param_func>
<parameter=param1>42</parameter>
<parameter=param2>41.9</parameter>
<parameter=param3>42</parameter>
<parameter=param4>true</parameter>
<parameter=param5>{"key": "value"}</parameter>
<parameter=param6>[1, 2, 3]</parameter>
<parameter=param7>null</parameter>
<parameter=param8>{'arg1': 3, 'arg2': [1, 2]}</parameter>
</function>
</tool_call>"#;

        let (calls, _) =
            try_tool_call_parse_xml(input, &XmlParserConfig::default(), Some(&tools)).unwrap();
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].function.name, "multi_param_func");

        let args: serde_json::Value = serde_json::from_str(&calls[0].function.arguments).unwrap();

        // param1 is type "string" so "42" stays as string
        assert_eq!(args["param1"], "42");

        // param2 is type "float" so 41.9 is parsed as float
        assert_eq!(args["param2"], 41.9);

        // param3 is type "integer" so 42 is parsed as integer
        assert_eq!(args["param3"], 42);

        // param4 is type "boolean" so "true" is parsed as bool
        assert_eq!(args["param4"], true);

        // param5 is type "object" so JSON is parsed
        assert_eq!(args["param5"], serde_json::json!({"key": "value"}));

        // param6 is type "array" so JSON array is parsed
        assert_eq!(args["param6"], serde_json::json!([1, 2, 3]));

        // param7 is type "null" so "null" is parsed as null
        assert_eq!(args["param7"], serde_json::Value::Null);

        // param8 is other_type, uses literal_eval which converts Python-style dict
        assert_eq!(
            args["param8"],
            serde_json::json!({"arg1": 3, "arg2": [1, 2]})
        );
    }

    #[test]
    fn test_schema_aware_type_conversion_fallback() {
        // Test that invalid values fall back to strings with warnings
        let tools = vec![ToolDefinition {
            name: "test_func".to_string(),
            parameters: Some(serde_json::json!({
                "type": "object",
                "properties": {
                    "int_param": {"type": "integer"},
                    "float_param": {"type": "float"},
                    "bool_param": {"type": "boolean"}
                }
            })),
        }];

        let input = r#"<tool_call>
<function=test_func>
<parameter=int_param>not_an_int</parameter>
<parameter=float_param>not_a_float</parameter>
<parameter=bool_param>not_a_bool</parameter>
</function>
</tool_call>"#;

        let (calls, _) =
            try_tool_call_parse_xml(input, &XmlParserConfig::default(), Some(&tools)).unwrap();
        assert_eq!(calls.len(), 1);

        let args: serde_json::Value = serde_json::from_str(&calls[0].function.arguments).unwrap();

        // All should fall back to strings
        assert_eq!(args["int_param"], "not_an_int");
        assert_eq!(args["float_param"], "not_a_float");
        // bool_param with invalid value defaults to false
        assert_eq!(args["bool_param"], false);
    }

    #[test]
    fn test_no_schema_fallback_behavior() {
        // Without schema, behavior should match old safe_parse_value logic
        let input = r#"<tool_call>
<function=unknown_func>
<parameter=param1>42</parameter>
<parameter=param2>true</parameter>
<parameter=param3>hello</parameter>
</function>
</tool_call>"#;

        let (calls, _) = try_tool_call_parse_xml(input, &XmlParserConfig::default(), None).unwrap();
        assert_eq!(calls.len(), 1);

        let args: serde_json::Value = serde_json::from_str(&calls[0].function.arguments).unwrap();

        // Without schema, all values are returned as strings (no type inference)
        assert_eq!(args["param1"], "42");
        assert_eq!(args["param2"], "true");
        assert_eq!(args["param3"], "hello");
    }
934
}