tool_parser_json.rs 20.2 KB
Newer Older
1
2
3
4
5
//! JSON Parser Integration Tests
//!
//! Tests for the JSON parser which handles OpenAI, Claude, and generic JSON formats

use serde_json::json;
6
use sglang_router_rs::tool_parser::{JsonParser, ToolParser};
7

8
9
10
mod common;
use common::{create_test_tools, streaming_helpers::*};

11
12
13
14
15
#[tokio::test]
async fn test_simple_json_tool_call() {
    let parser = JsonParser::new();
    let input = r#"{"name": "get_weather", "arguments": {"location": "San Francisco"}}"#;

16
    let (normal_text, tools) = parser.parse_complete(input).await.unwrap();
17
    assert_eq!(tools.len(), 1);
18
    assert_eq!(normal_text, "");
19
    assert_eq!(tools[0].function.name, "get_weather");
20

21
    let args: serde_json::Value = serde_json::from_str(&tools[0].function.arguments).unwrap();
22
23
24
25
26
27
    assert_eq!(args["location"], "San Francisco");
}

#[tokio::test]
async fn test_json_array_of_tools() {
    let parser = JsonParser::new();
28
    let input = r#"Hello, here are the results: [
29
30
31
32
        {"name": "get_weather", "arguments": {"location": "SF"}},
        {"name": "search", "arguments": {"query": "news"}}
    ]"#;

33
    let (normal_text, tools) = parser.parse_complete(input).await.unwrap();
34
    assert_eq!(tools.len(), 2);
35
    assert_eq!(normal_text, "Hello, here are the results: ");
36
37
    assert_eq!(tools[0].function.name, "get_weather");
    assert_eq!(tools[1].function.name, "search");
38
39
40
41
42
43
44
}

#[tokio::test]
async fn test_json_with_parameters_key() {
    let parser = JsonParser::new();
    let input = r#"{"name": "calculate", "parameters": {"x": 10, "y": 20}}"#;

45
    let (normal_text, tools) = parser.parse_complete(input).await.unwrap();
46
    assert_eq!(tools.len(), 1);
47
    assert_eq!(normal_text, "");
48
    assert_eq!(tools[0].function.name, "calculate");
49

50
    let args: serde_json::Value = serde_json::from_str(&tools[0].function.arguments).unwrap();
51
52
53
54
55
56
57
58
59
    assert_eq!(args["x"], 10);
    assert_eq!(args["y"], 20);
}

#[tokio::test]
async fn test_json_extraction_from_text() {
    let parser = JsonParser::new();
    let input = r#"I'll help you with that. {"name": "search", "arguments": {"query": "rust"}} Let me search for that."#;

60
    let (normal_text, tools) = parser.parse_complete(input).await.unwrap();
61
    assert_eq!(tools.len(), 1);
62
63
64
65
    assert_eq!(
        normal_text,
        "I'll help you with that.  Let me search for that."
    );
66
    assert_eq!(tools[0].function.name, "search");
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
}

#[tokio::test]
async fn test_json_with_nested_objects() {
    let parser = JsonParser::new();
    let input = r#"{
        "name": "update_config",
        "arguments": {
            "settings": {
                "theme": "dark",
                "language": "en",
                "notifications": {
                    "email": true,
                    "push": false
                }
            }
        }
    }"#;

86
    let (normal_text, tools) = parser.parse_complete(input).await.unwrap();
87
    assert_eq!(tools.len(), 1);
88
    assert_eq!(normal_text, "");
89
    assert_eq!(tools[0].function.name, "update_config");
90

91
    let args: serde_json::Value = serde_json::from_str(&tools[0].function.arguments).unwrap();
92
93
94
95
96
97
98
99
100
    assert_eq!(args["settings"]["theme"], "dark");
    assert_eq!(args["settings"]["notifications"]["email"], true);
}

#[tokio::test]
async fn test_json_with_special_characters() {
    let parser = JsonParser::new();
    let input = r#"{"name": "echo", "arguments": {"text": "Line 1\nLine 2\tTabbed", "path": "C:\\Users\\test"}}"#;

101
    let (normal_text, tools) = parser.parse_complete(input).await.unwrap();
102
    assert_eq!(tools.len(), 1);
103
    assert_eq!(normal_text, "");
104

105
    let args: serde_json::Value = serde_json::from_str(&tools[0].function.arguments).unwrap();
106
107
108
109
110
111
112
113
114
    assert_eq!(args["text"], "Line 1\nLine 2\tTabbed");
    assert_eq!(args["path"], "C:\\Users\\test");
}

#[tokio::test]
async fn test_json_with_unicode() {
    let parser = JsonParser::new();
    let input = r#"{"name": "translate", "arguments": {"text": "Hello 世界 🌍", "emoji": "😊"}}"#;

115
    let (normal_text, tools) = parser.parse_complete(input).await.unwrap();
116
    assert_eq!(tools.len(), 1);
117
    assert_eq!(normal_text, "");
118

119
    let args: serde_json::Value = serde_json::from_str(&tools[0].function.arguments).unwrap();
120
121
122
123
124
125
126
127
128
    assert_eq!(args["text"], "Hello 世界 🌍");
    assert_eq!(args["emoji"], "😊");
}

#[tokio::test]
async fn test_json_empty_arguments() {
    let parser = JsonParser::new();
    let input = r#"{"name": "ping", "arguments": {}}"#;

129
    let (normal_text, tools) = parser.parse_complete(input).await.unwrap();
130
    assert_eq!(tools.len(), 1);
131
    assert_eq!(normal_text, "");
132
    assert_eq!(tools[0].function.name, "ping");
133

134
    let args: serde_json::Value = serde_json::from_str(&tools[0].function.arguments).unwrap();
135
136
137
138
139
140
141
142
143
    assert_eq!(args, json!({}));
}

#[tokio::test]
async fn test_json_invalid_format() {
    let parser = JsonParser::new();

    // Missing closing brace
    let input = r#"{"name": "test", "arguments": {"key": "value""#;
144
    let (normal_text, tools) = parser.parse_complete(input).await.unwrap();
145
    assert_eq!(tools.len(), 0);
146
147
148
149
    assert_eq!(
        normal_text,
        "{\"name\": \"test\", \"arguments\": {\"key\": \"value\""
    );
150
151
152

    // Not JSON at all
    let input = "This is just plain text";
153
154
    let (_normal_text, tools) = parser.parse_complete(input).await.unwrap();
    assert_eq!(tools.len(), 0);
155
156
157
158
159
160
}

#[tokio::test]
async fn test_json_format_detection() {
    let parser = JsonParser::new();

161
162
163
    assert!(parser.has_tool_markers(r#"{"name": "test", "arguments": {}}"#));
    assert!(parser.has_tool_markers(r#"[{"name": "test"}]"#));
    assert!(!parser.has_tool_markers("plain text"));
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
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
491
492
493
494
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717

// Streaming tests for JSON array format
#[tokio::test]
async fn test_json_array_streaming_required_mode() {
    use sglang_router_rs::protocols::common::Tool;

    // Test that simulates the exact streaming pattern from required mode
    let mut parser = JsonParser::new();

    // Define test tools
    let tools = vec![Tool {
        tool_type: "function".to_string(),
        function: sglang_router_rs::protocols::common::Function {
            name: "get_weather".to_string(),
            description: Some("Get weather".to_string()),
            parameters: serde_json::json!({}),
            strict: None,
        },
    }];

    // Simulate the EXACT chunks from the debug log
    let chunks = vec![
        "[{",
        " \"",
        "name",
        "\":",
        " \"",
        "get",
        "_weather",
        "\",",
        " \"",
        "parameters",
        "\":",
        " {",
        " \"",
        "city",
        "\":",
        " \"",
        "Paris",
        "\"",
        " }",
        " }]",
    ];

    let mut all_results = Vec::new();
    let mut all_normal_text = String::new();

    for chunk in chunks {
        let result = parser.parse_incremental(chunk, &tools).await.unwrap();
        all_results.extend(result.calls);
        all_normal_text.push_str(&result.normal_text);
    }

    // We should have gotten tool call chunks
    assert!(
        !all_results.is_empty(),
        "Should have emitted tool call chunks"
    );

    // Should not have emitted any normal text (including the closing ])
    assert_eq!(
        all_normal_text, "",
        "Should not emit normal text for JSON array format"
    );

    // Check that we got the function name
    let has_name = all_results
        .iter()
        .any(|item| item.name.as_ref().is_some_and(|n| n == "get_weather"));
    assert!(has_name, "Should have emitted function name");

    // Check that we got the parameters
    let has_params = all_results.iter().any(|item| !item.parameters.is_empty());
    assert!(has_params, "Should have emitted parameters");
}

#[tokio::test]
async fn test_json_array_multiple_tools_streaming() {
    use sglang_router_rs::protocols::common::Tool;

    // Test with multiple tools in array
    let mut parser = JsonParser::new();

    let tools = vec![
        Tool {
            tool_type: "function".to_string(),
            function: sglang_router_rs::protocols::common::Function {
                name: "get_weather".to_string(),
                description: Some("Get weather".to_string()),
                parameters: serde_json::json!({}),
                strict: None,
            },
        },
        Tool {
            tool_type: "function".to_string(),
            function: sglang_router_rs::protocols::common::Function {
                name: "get_news".to_string(),
                description: Some("Get news".to_string()),
                parameters: serde_json::json!({}),
                strict: None,
            },
        },
    ];

    // Split into smaller, more realistic chunks
    let chunks = vec![
        "[{",
        "\"name\":",
        "\"get_weather\"",
        ",\"parameters\":",
        "{\"city\":",
        "\"SF\"}",
        "}",
        ",",
        "{\"name\":",
        "\"get_news\"",
        ",\"parameters\":",
        "{\"topic\":",
        "\"tech\"}",
        "}]",
    ];

    let mut all_results = Vec::new();

    for chunk in chunks {
        let result = parser.parse_incremental(chunk, &tools).await.unwrap();
        all_results.extend(result.calls);
    }

    // Should have gotten tool calls for both functions
    let has_weather = all_results
        .iter()
        .any(|item| item.name.as_ref().is_some_and(|n| n == "get_weather"));
    let has_news = all_results
        .iter()
        .any(|item| item.name.as_ref().is_some_and(|n| n == "get_news"));

    assert!(has_weather, "Should have get_weather tool call");
    assert!(has_news, "Should have get_news tool call");
}

#[tokio::test]
async fn test_json_array_closing_bracket_separate_chunk() {
    use sglang_router_rs::protocols::common::Tool;

    // Test case where the closing ] comes as a separate chunk
    let mut parser = JsonParser::new();

    let tools = vec![Tool {
        tool_type: "function".to_string(),
        function: sglang_router_rs::protocols::common::Function {
            name: "get_weather".to_string(),
            description: Some("Get weather".to_string()),
            parameters: json!({}),
            strict: None,
        },
    }];

    // Closing ] as separate chunk, followed by normal text
    let chunks = vec![
        "[{",
        "\"",
        "name",
        "\":",
        "\"",
        "get",
        "_weather",
        "\",",
        "\"",
        "parameters",
        "\":",
        "{",
        "\"",
        "city",
        "\":",
        "\"",
        "Paris",
        "\"",
        "}",
        "}",
        "]",
        " Here's",
        " the",
        " weather",
        " info",
    ];

    let mut all_normal_text = String::new();

    for chunk in chunks {
        let result = parser.parse_incremental(chunk, &tools).await.unwrap();
        all_normal_text.push_str(&result.normal_text);
    }

    // Should emit only the third chunk as normal text, NOT the ]
    assert_eq!(
        all_normal_text, " Here's the weather info",
        "Should emit only normal text without ], got: '{}'",
        all_normal_text
    );
}

#[tokio::test]
async fn test_json_single_object_with_trailing_text() {
    use sglang_router_rs::protocols::common::Tool;

    // Test single object format (no array) with trailing text
    let mut parser = JsonParser::new();

    let tools = vec![Tool {
        tool_type: "function".to_string(),
        function: sglang_router_rs::protocols::common::Function {
            name: "get_weather".to_string(),
            description: Some("Get weather".to_string()),
            parameters: serde_json::json!({}),
            strict: None,
        },
    }];

    let chunks = vec![
        "{",
        "\"",
        "name",
        "\":",
        "\"",
        "get_weather",
        "\",",
        "\"",
        "parameters",
        "\":",
        "{",
        "\"city",
        "\":",
        "\"Paris",
        "\"}",
        "}",
        " Here's",
        " the",
        " weather",
    ];

    let mut all_normal_text = String::new();

    for chunk in chunks {
        let result = parser.parse_incremental(chunk, &tools).await.unwrap();
        all_normal_text.push_str(&result.normal_text);
    }

    // Should emit the trailing text as normal_text (no ] to strip for single object)
    assert_eq!(
        all_normal_text, " Here's the weather",
        "Should emit normal text for single object format, got: '{}'",
        all_normal_text
    );
}

#[tokio::test]
async fn test_json_single_object_with_bracket_in_text() {
    use sglang_router_rs::protocols::common::Tool;

    // Test that ] in normal text is NOT stripped for single object format
    let mut parser = JsonParser::new();

    let tools = vec![Tool {
        tool_type: "function".to_string(),
        function: sglang_router_rs::protocols::common::Function {
            name: "get_weather".to_string(),
            description: Some("Get weather".to_string()),
            parameters: serde_json::json!({}),
            strict: None,
        },
    }];

    let chunks = vec![
        "{",
        "\"name",
        "\":",
        "\"get_weather",
        "\",",
        "\"parameters",
        "\":",
        "{",
        "\"city",
        "\":",
        "\"Paris",
        "\"}",
        "}",
        "]",
        " Here's",
        " the",
        " weather",
    ];

    let mut all_normal_text = String::new();

    for chunk in chunks {
        let result = parser.parse_incremental(chunk, &tools).await.unwrap();
        all_normal_text.push_str(&result.normal_text);
    }

    // For single object format, ] should NOT be stripped (it's part of normal text)
    assert_eq!(
        all_normal_text, "] Here's the weather",
        "Should preserve ] in normal text for single object format, got: '{}'",
        all_normal_text
    );
}

#[tokio::test]
async fn test_json_array_bracket_in_text_after_tools() {
    use sglang_router_rs::protocols::common::Tool;

    // Test that ] in normal text AFTER array tools is preserved
    let mut parser = JsonParser::new();

    let tools = vec![Tool {
        tool_type: "function".to_string(),
        function: sglang_router_rs::protocols::common::Function {
            name: "get_weather".to_string(),
            description: Some("Get weather".to_string()),
            parameters: serde_json::json!({}),
            strict: None,
        },
    }];

    let chunks = vec![
        "[",
        "{",
        "\"name",
        "\":",
        "\"get_weather",
        "\",",
        "\"parameters",
        "\":",
        "{",
        "\"city",
        "\":",
        "\"Paris",
        "\"}",
        "}",
        "]",
        " Array",
        " notation:",
        " arr",
        "[",
        "0",
        "]",
    ];

    let mut all_normal_text = String::new();

    for chunk in chunks {
        let result = parser.parse_incremental(chunk, &tools).await.unwrap();
        all_normal_text.push_str(&result.normal_text);
    }

    // Should preserve ] in normal text after array tools complete
    assert_eq!(
        all_normal_text, " Array notation: arr[0]",
        "Should preserve ] in normal text after array tools, got: '{}'",
        all_normal_text
    );
}
// =============================================================================
// REALISTIC STREAMING TESTS
// =============================================================================

#[tokio::test]
async fn test_json_bug_incomplete_tool_name_string() {
    let tools = create_test_tools();
    let mut parser = JsonParser::new();

    // This exact sequence triggered the bug:
    // Parser receives {"name": " and must NOT parse it as empty name
    let chunks = vec![
        r#"{"#,
        r#"""#,
        r#"name"#,
        r#"""#,
        r#":"#,
        r#" "#,
        r#"""#, // ← Critical moment: parser has {"name": "
        // At this point, partial_json should NOT allow incomplete strings
        // when current_tool_name_sent=false
        r#"search"#, // Use valid tool name from create_test_tools()
        r#"""#,
        r#", "#,
        r#"""#,
        r#"arguments"#,
        r#"""#,
        r#": {"#,
        r#"""#,
        r#"query"#,
        r#"""#,
        r#": "#,
        r#"""#,
        r#"rust programming"#,
        r#"""#,
        r#"}}"#,
    ];

    let mut got_tool_name = false;
    let mut saw_empty_name = false;

    for chunk in chunks.iter() {
        let result = parser.parse_incremental(chunk, &tools).await.unwrap();

        for call in result.calls {
            if let Some(name) = &call.name {
                if name.is_empty() {
                    saw_empty_name = true;
                }
                if name == "search" {
                    got_tool_name = true;
                }
            }
        }
    }

    assert!(
        !saw_empty_name,
        "Parser should NEVER return empty tool name"
    );
    assert!(got_tool_name, "Should have parsed tool name correctly");
}

#[tokio::test]
async fn test_json_realistic_chunks_simple_tool() {
    let tools = create_test_tools();
    let mut parser = JsonParser::new();

    let input = r#"{"name": "get_weather", "arguments": {"city": "Paris"}}"#;
    let chunks = create_realistic_chunks(input);

    assert!(chunks.len() > 10, "Should have many small chunks");

    let mut got_tool_name = false;

    for chunk in chunks {
        let result = parser.parse_incremental(&chunk, &tools).await.unwrap();
        for call in result.calls {
            if let Some(name) = call.name {
                assert_eq!(name, "get_weather");
                got_tool_name = true;
            }
        }
    }

    assert!(got_tool_name, "Should have parsed tool name");
}

#[tokio::test]
async fn test_json_strategic_chunks_with_quotes() {
    let tools = create_test_tools();
    let mut parser = JsonParser::new();

    let input = r#"{"name": "search", "arguments": {"query": "rust programming"}}"#;
    let chunks = create_strategic_chunks(input);

    // Strategic chunks break after quotes and colons
    assert!(chunks.iter().any(|c| c.ends_with('"')));

    let mut got_tool_name = false;

    for chunk in chunks {
        let result = parser.parse_incremental(&chunk, &tools).await.unwrap();
        for call in result.calls {
            if call.name.is_some() {
                got_tool_name = true;
            }
        }
    }

    assert!(got_tool_name, "Should have parsed tool name");
}

#[tokio::test]
async fn test_json_incremental_arguments_streaming() {
    let tools = create_test_tools();
    let mut parser = JsonParser::new();

    let input = r#"{"name": "search", "arguments": {"query": "test", "limit": 10}}"#;
    let chunks = create_realistic_chunks(input);

    let mut tool_name_sent = false;
    let mut got_arguments = false;

    for chunk in chunks {
        let result = parser.parse_incremental(&chunk, &tools).await.unwrap();
        for call in result.calls {
            if call.name.is_some() {
                tool_name_sent = true;
            }
            if tool_name_sent && !call.parameters.is_empty() {
                got_arguments = true;
            }
        }
    }

    assert!(tool_name_sent, "Should have sent tool name");
    assert!(got_arguments, "Should have sent arguments");
}

#[tokio::test]
async fn test_json_very_long_url_in_arguments() {
    let tools = create_test_tools();
    let mut parser = JsonParser::new();

    // Simulate long URL arriving in many chunks
    let long_url = "https://example.com/very/long/path/".to_string() + &"segment/".repeat(50);
    let input = format!(
        r#"{{"name": "search", "arguments": {{"query": "{}"}}}}"#,
        long_url
    );
    let chunks = create_realistic_chunks(&input);

    assert!(chunks.len() > 100, "Long URL should create many chunks");

    let mut got_tool_name = false;

    for chunk in chunks {
        let result = parser.parse_incremental(&chunk, &tools).await.unwrap();
        for call in result.calls {
            if call.name.is_some() {
                got_tool_name = true;
            }
        }
    }

    assert!(got_tool_name, "Should have parsed tool name");
}

#[tokio::test]
async fn test_json_unicode() {
    let tools = create_test_tools();
    let mut parser = JsonParser::new();

    let input = r#"{"name": "search", "arguments": {"query": "Hello 世界 🌍"}}"#;
    let chunks = create_realistic_chunks(input);

    let mut got_tool_name = false;

    for chunk in chunks {
        let result = parser.parse_incremental(&chunk, &tools).await.unwrap();
        for call in result.calls {
            if call.name.is_some() {
                got_tool_name = true;
            }
        }
    }

    assert!(got_tool_name, "Should have parsed with unicode");
}