-
-
Notifications
You must be signed in to change notification settings - Fork 4.1k
Expand file tree
/
Copy pathparse_test.go
More file actions
2648 lines (2390 loc) · 93.8 KB
/
parse_test.go
File metadata and controls
2648 lines (2390 loc) · 93.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
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
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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
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
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package functions_test
import (
"encoding/json"
"regexp"
"strings"
. "github.com/mudler/LocalAI/pkg/functions"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("LocalAI function parse tests", func() {
var functionConfig FunctionsConfig
BeforeEach(func() {
// Default configuration setup
functionConfig = FunctionsConfig{}
})
Context("when using grammars and single result expected", func() {
It("should parse the function name and arguments correctly", func() {
input := `{"name": "add", "arguments": {"x": 5, "y": 3}}`
results := ParseFunctionCall(input, functionConfig)
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("add"))
Expect(results[0].Arguments).To(Equal(`{"x":5,"y":3}`))
})
})
Context("when not using grammars and regex is needed", func() {
It("should extract function name and arguments from the regex", func() {
input := `add({"x":5,"y":3})`
functionConfig.ResponseRegex = []string{`(?P<name>\w+)\s*\((?P<arguments>.*)\)`}
results := ParseFunctionCall(input, functionConfig)
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("add"))
Expect(results[0].Arguments).To(Equal(`{"x":5,"y":3}`))
})
It("should extract function name and arguments from the regex", func() {
input := `add({"x":5,"y":3})`
functionConfig.ResponseRegex = []string{`(?P<function>\w+)\s*\((?P<arguments>.*)\)`}
functionConfig.FunctionNameKey = "function"
results := ParseFunctionCall(input, functionConfig)
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("add"))
Expect(results[0].Arguments).To(Equal(`{"x":5,"y":3}`))
})
})
Context("when having invalid input", func() {
It("returns no results when there is no input", func() {
input := ""
results := ParseFunctionCall(input, functionConfig)
Expect(results).To(HaveLen(0))
})
It("returns no results when is invalid", func() {
input := "invalid input"
results := ParseFunctionCall(input, functionConfig)
Expect(results).To(HaveLen(0))
})
})
Context("when parallel calls are enabled", func() {
It("should handle multiple function calls", func() {
input := `[{"name": "add", "arguments": {"x": 5, "y": 3}}, {"name": "subtract", "arguments": {"x": 10, "y": 7}}]`
results := ParseFunctionCall(input, functionConfig)
Expect(results).To(HaveLen(2))
Expect(results[0].Name).To(Equal("add"))
Expect(results[0].Arguments).To(Equal(`{"x":5,"y":3}`))
Expect(results[1].Name).To(Equal("subtract"))
Expect(results[1].Arguments).To(Equal(`{"x":10,"y":7}`))
})
})
Context("without grammars and without regex", func() {
It("should parse the function name and arguments correctly with the name key", func() {
input := `{"function": "add", "arguments": {"x": 5, "y": 3}}`
functionConfig.FunctionNameKey = "function"
results := ParseFunctionCall(input, functionConfig)
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("add"))
Expect(results[0].Arguments).To(Equal(`{"x":5,"y":3}`))
})
It("should parse the function name and arguments correctly with the function key", func() {
input := `{"name": "add", "arguments": {"x": 5, "y": 3}}`
results := ParseFunctionCall(input, functionConfig)
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("add"))
Expect(results[0].Arguments).To(Equal(`{"x":5,"y":3}`))
})
It("should parse the result by matching the JSONRegexMatch", func() {
input := `
<tool_call>
{"name": "add", "arguments": {"x": 5, "y": 3}}
</tool_call>`
functionConfig.JSONRegexMatch = []string{`(?s)<tool_call>(.*?)</tool_call>`}
results := ParseFunctionCall(input, functionConfig)
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("add"))
Expect(results[0].Arguments).To(Equal(`{"x":5,"y":3}`))
})
It("should parse the result by matching the JSONRegexMatch", func() {
input := `
{"name": "add", "arguments": {"x": 5, "y": 3}}
</tool_call>`
functionConfig.JSONRegexMatch = []string{`(?s)(.*?)</tool_call>`}
results := ParseFunctionCall(input, functionConfig)
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("add"))
Expect(results[0].Arguments).To(Equal(`{"x":5,"y":3}`))
})
It("should parse the result even with invalid JSON", func() {
input := `{"name": "add", "arguments": {"x": 5, "y": 3}} invalid {"name": "add", "arguments": {"x": 5, "y": 3}}`
results := ParseFunctionCall(input, functionConfig)
Expect(results).To(HaveLen(2))
Expect(results[0].Name).To(Equal("add"))
Expect(results[0].Arguments).To(Equal(`{"x":5,"y":3}`))
})
})
Context("when using ReplaceResults to clean up input", func() {
It("should replace text before and after JSON blob", func() {
input := `
Some text before the JSON
{"name": "add", "arguments": {"x": 5, "y": 3}}
Some text after the JSON
`
functionConfig.ReplaceFunctionResults = []ReplaceResult{
{Key: `(?s)^[^{\[]*`, Value: ""},
{Key: `(?s)[^}\]]*$`, Value: ""},
}
results := ParseFunctionCall(input, functionConfig)
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("add"))
Expect(results[0].Arguments).To(Equal(`{"x":5,"y":3}`))
})
It("should replace text before and after array JSON blob", func() {
input := `
Some text before the JSON
[{"name": "add", "arguments": {"x": 5, "y": 3}}, {"name": "subtract", "arguments": {"x": 10, "y": 7}}]
Some text after the JSON
`
functionConfig.ReplaceFunctionResults = []ReplaceResult{
{Key: `(?s)^[^{\[]*`, Value: ""},
{Key: `(?s)[^}\]]*$`, Value: ""},
}
results := ParseFunctionCall(input, functionConfig)
Expect(results).To(HaveLen(2))
Expect(results[0].Name).To(Equal("add"))
Expect(results[0].Arguments).To(Equal(`{"x":5,"y":3}`))
Expect(results[1].Name).To(Equal("subtract"))
Expect(results[1].Arguments).To(Equal(`{"x":10,"y":7}`))
})
It("should convert single-quoted key-value pairs to double-quoted and escape double quotes within values", func() {
input := `
Some text before the JSON
{'name': '"add"', 'arguments': {'x': 5, 'z': '"v"', 'y': 'v"value"'}}
Some text after the JSON
`
functionConfig.JSONRegexMatch = []string{`(?s)<tool_call>(.*?)</tool_call>`}
// Regex to match non-JSON characters before the JSON structure
//reBefore := regexp.MustCompile(`(?s)^.*?(?=\{|\[)`)
// Regex to match non-JSON characters after the JSON structure
//reAfter := regexp.MustCompile(`(?s)(?<=\}|\]).*$`)
functionConfig.ReplaceFunctionResults = []ReplaceResult{
{Key: `(?s)^[^{\[]*`, Value: ""},
{Key: `(?s)[^}\]]*$`, Value: ""},
// Regex pattern to match single quotes around keys and values
// Step 1: Replace single quotes around keys and values with double quotes
{Key: `'([^']*?)'`, Value: `_DQUOTE_${1}_DQUOTE_`},
// Step 2: Replace double quotes inside values with placeholders
{Key: `\\"`, Value: `__TEMP_QUOTE__`},
{Key: `"`, Value: `\"`},
{Key: `\'`, Value: `'`},
{Key: `_DQUOTE_`, Value: `"`},
{Key: `__TEMP_QUOTE__`, Value: `"`},
}
results := ParseFunctionCall(input, functionConfig)
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("\"add\""))
Expect(results[0].Arguments).To(Equal(`{"x":5,"y":"v\"value\"","z":"\"v\""}`))
})
It("should convert single-quoted key-value pairs to double-quoted and escape double quotes within values", func() {
input := `
Some text before the JSON
<tool_call>{'name': '"add"', 'arguments': {'x': 5, 'z': '"v"', 'y': 'v"value"'}}</tool_call>
Some text after the JSON
`
functionConfig.JSONRegexMatch = []string{`(?s)<tool_call>(.*?)</tool_call>`}
// Regex to match non-JSON characters before the JSON structure
//reBefore := regexp.MustCompile(`(?s)^.*?(?=\{|\[)`)
// Regex to match non-JSON characters after the JSON structure
//reAfter := regexp.MustCompile(`(?s)(?<=\}|\]).*$`)
functionConfig.ReplaceFunctionResults = []ReplaceResult{
{Key: `(?s)^[^{\[]*`, Value: ""},
{Key: `(?s)[^}\]]*$`, Value: ""},
// Regex pattern to match single quotes around keys and values
// Step 1: Replace single quotes around keys and values with double quotes
{Key: `'([^']*?)'`, Value: `_DQUOTE_${1}_DQUOTE_`},
// Step 2: Replace double quotes inside values with placeholders
{Key: `\\"`, Value: `__TEMP_QUOTE__`},
{Key: `"`, Value: `\"`},
{Key: `\'`, Value: `'`},
{Key: `_DQUOTE_`, Value: `"`},
{Key: `__TEMP_QUOTE__`, Value: `"`},
}
results := ParseFunctionCall(input, functionConfig)
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("\"add\""))
Expect(results[0].Arguments).To(Equal(`{"x":5,"y":"v\"value\"","z":"\"v\""}`))
})
It("should detect multiple functions call where the JSONRegexMatch is repeated", func() {
input := `
Some text before the JSON
<tool_call>{"name": "add", "arguments": {"x": 5, "y": 3}}</tool_call>
<tool_call>{"name": "subtract", "arguments": {"x": 10, "y": 7}}</tool_call>
Some text after the JSON
`
functionConfig.JSONRegexMatch = []string{`(?s)<tool_call>(.*?)</tool_call>`}
results := ParseFunctionCall(input, functionConfig)
Expect(results).To(HaveLen(2))
Expect(results[0].Name).To(Equal("add"))
Expect(results[0].Arguments).To(Equal(`{"x":5,"y":3}`))
Expect(results[1].Name).To(Equal("subtract"))
Expect(results[1].Arguments).To(Equal(`{"x":10,"y":7}`))
})
// Regression test for https://github.com/mudler/LocalAI/issues/9722
// Hermes/NousResearch models wrap a single JSON tool call in <tool_call> tags
// without JSONRegexMatch. Multiple parsers (extractJSON + PEG) must not produce
// duplicate FuncCallResults that then appear at different streaming indices.
It("should return exactly one result for a bare Hermes-style tool_call without JSONRegexMatch", func() {
input := "<tool_call>\n{\"name\": \"bash\", \"arguments\": {\"script\": \"ls /tmp | wc -l\"}}\n</tool_call>"
results := ParseFunctionCall(input, functionConfig)
Expect(results).To(HaveLen(1), "multiple parsers must not produce duplicate entries for the same call")
Expect(results[0].Name).To(Equal("bash"))
Expect(results[0].Arguments).To(Equal(`{"script":"ls /tmp | wc -l"}`))
})
It("should return exactly one result for a bare Hermes-style tool_call with complex arguments", func() {
input := "<tool_call>\n{\"name\": \"search\", \"arguments\": {\"query\": \"golang channels\", \"max_results\": 5}}\n</tool_call>"
results := ParseFunctionCall(input, functionConfig)
Expect(results).To(HaveLen(1), "multiple parsers must not produce duplicate entries for the same call")
Expect(results[0].Name).To(Equal("search"))
})
// Regression test for https://github.com/mudler/LocalAI/issues/9722
// The glm-4.5 XML format auto-detects <tool_call>...</tool_call> blocks and,
// when no <arg_key> element is present, treats the entire content as the function
// name. For Hermes-style output, that content is a JSON object, causing the
// streaming callback to emit a delta with '{"name":"bash",...}' as the tool name.
// ParseXMLIterative must discard such results so the JSON fallback path fires.
It("should not auto-detect Hermes tool_call as glm-4.5 format with JSON function name", func() {
input := "<tool_call>\n{\"name\": \"bash\", \"arguments\": {\"script\": \"ls\"}}\n</tool_call>"
// ParseXMLIterative with nil format (auto-detect) must not return a result
// where the function name is the raw JSON blob.
results, err := ParseXMLIterative(input, nil, false)
Expect(err).ToNot(HaveOccurred())
for _, r := range results {
Expect(r.Name).NotTo(HavePrefix("{"),
"auto-detected XML result must not have a JSON blob as function name, got: %s", r.Name)
}
})
It("should not auto-detect partial Hermes tool_call as glm-4.5 format during streaming", func() {
// Partial output — </tool_call> not yet received.
partial := "<tool_call>\n{\"name\": \"bash\", \"arguments\": {\"script\": \"ls\"}}"
results, err := ParseXMLIterative(partial, nil, true)
Expect(err).ToNot(HaveOccurred())
for _, r := range results {
Expect(r.Name).NotTo(HavePrefix("{"),
"streaming partial XML result must not have a JSON blob as function name")
}
})
})
Context("ParseTextContent", func() {
It("Can extract notes from the LLM result", func() {
input := `
Some text before the JSON
<sketchpad>
roses are red
</sketchpad>
<tool_call>{"name": "subtract", "arguments": {"x": 10, "y": 7}}</tool_call>
Some text after the JSON
`
functionConfig.CaptureLLMResult = []string{`(?s)<sketchpad>(.*?)</sketchpad>`}
results := ParseTextContent(input, functionConfig)
Expect(results).To(Equal("roses are red"))
})
It("Defaults to empty if doesn't catch any", func() {
input := `
Some text before the JSON
<tool_call>{"name": "subtract", "arguments": {"x": 10, "y": 7}}</tool_call>
Some text after the JSON
`
functionConfig.CaptureLLMResult = []string{`(?s)<sketchpad>(.*?)</sketchpad>`}
results := ParseTextContent(input, functionConfig)
Expect(results).To(Equal(""))
})
})
Context("ParseJSON - when given valid JSON strings", func() {
It("should parse multiple JSON objects", func() {
input := `{"key1": "value1"} {"key2": "value2"}`
expected := []map[string]any{
{"key1": "value1"},
{"key2": "value2"},
}
result, err := ParseJSON(input)
Expect(err).NotTo(HaveOccurred())
Expect(result).To(Equal(expected))
})
It("should parse a single JSON object with various types", func() {
input := `{"key1": "value1", "key2": 2}`
expected := []map[string]any{
{"key1": "value1", "key2": float64(2)},
}
result, err := ParseJSON(input)
Expect(err).NotTo(HaveOccurred())
Expect(result).To(Equal(expected))
})
It("should handle JSON without syntax errors gracefully", func() {
input := `{"key1": "value1"}`
expected := []map[string]any{
{"key1": "value1"},
}
result, err := ParseJSON(input)
Expect(err).NotTo(HaveOccurred())
Expect(result).To(Equal(expected))
})
It("should handle JSON without syntax errors gracefully", func() {
input := `[{"key1": "value1"}]`
expected := []map[string]any{
{"key1": "value1"},
}
result, err := ParseJSON(input)
Expect(err).NotTo(HaveOccurred())
Expect(result).To(Equal(expected))
})
})
Context("ParseJSON - when given invalid JSON strings", func() {
It("should return an error for completely invalid JSON", func() {
input := `invalid json`
result, err := ParseJSON(input)
Expect(err).To(HaveOccurred())
Expect(result).To(BeNil())
})
It("should skip invalid JSON parts and parse valid parts", func() {
input := `{"key1": "value1"} invalid {"key2": "value2"}`
expected := []map[string]any{
{"key1": "value1"},
{"key2": "value2"},
}
result, err := ParseJSON(input)
Expect(err).NotTo(HaveOccurred())
Expect(result).To(Equal(expected))
})
PIt("should handle JSON with syntax errors gracefully", func() {
input := `{"key1": "value1", "key2": }`
expected := []map[string]any{
{"key1": "value1"},
}
result, err := ParseJSON(input)
Expect(err).NotTo(HaveOccurred())
Expect(result).To(Equal(expected))
})
})
Context("ParseXML - when given XML tool call strings", func() {
It("should parse a basic XML tool call with tool_call wrapper", func() {
input := `<tool_call>
<function=glob>
<parameter=pattern>
**/package.json
</parameter>
</function>
</tool_call>`
results, err := ParseXML(input, nil)
Expect(err).NotTo(HaveOccurred())
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("glob"))
Expect(results[0].Arguments).To(Equal(`{"pattern":"**/package.json"}`))
})
It("should parse XML tool call without tool_call wrapper", func() {
input := `<function=add>
<parameter=x>
5
</parameter>
<parameter=y>
3
</parameter>
</function>`
// Use PEG parser with a custom format that has no scope and tagged params
config := FunctionsConfig{
XMLFormat: &XMLToolCallFormat{
ToolStart: "<function=",
ToolSep: ">",
ToolEnd: "</function>",
KeyStart: "<parameter=",
KeyValSep: ">",
ValEnd: "</parameter>",
TrimRawArgVal: true,
},
}
results := ParseFunctionCall(input, config)
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("add"))
Expect(results[0].Arguments).To(ContainSubstring(`"x"`))
Expect(results[0].Arguments).To(ContainSubstring(`"y"`))
})
It("should parse XML tool call with multiple parameters", func() {
input := `<tool_call>
<function=function_name>
<parameter=param_1>
param_1_Value
</parameter>
<parameter=param_2>
param_2_Value
</parameter>
</function>
</tool_call>`
results, err := ParseXML(input, nil)
Expect(err).NotTo(HaveOccurred())
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("function_name"))
Expect(results[0].Arguments).To(Equal(`{"param_1":"param_1_Value","param_2":"param_2_Value"}`))
})
It("should parse multiple XML tool calls", func() {
input := `<tool_call>
<function=add>
<parameter=x>
5
</parameter>
<parameter=y>
3
</parameter>
</function>
</tool_call>
<tool_call>
<function=subtract>
<parameter=x>
10
</parameter>
<parameter=y>
7
</parameter>
</function>
</tool_call>`
results, err := ParseXML(input, nil)
Expect(err).NotTo(HaveOccurred())
Expect(results).To(HaveLen(2))
Expect(results[0].Name).To(Equal("add"))
// JSON parsing converts numeric strings to numbers (matching llama.cpp behavior)
Expect(results[0].Arguments).To(Equal(`{"x":5,"y":3}`))
Expect(results[1].Name).To(Equal("subtract"))
Expect(results[1].Arguments).To(Equal(`{"x":10,"y":7}`))
})
It("should handle mixed text and XML tool calls", func() {
input := `A message from the LLM
<tool_call>
<function=glob>
<parameter=pattern>
**/package.json
</parameter>
</function>
</tool_call>
Some text after the tool call`
results, err := ParseXML(input, nil)
Expect(err).NotTo(HaveOccurred())
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("glob"))
Expect(results[0].Arguments).To(Equal(`{"pattern":"**/package.json"}`))
})
It("should handle parameter values with newlines and whitespace", func() {
input := `<tool_call>
<function=search>
<parameter=query>
This is a multi-line
parameter value
with whitespace
</parameter>
</function>
</tool_call>`
results, err := ParseXML(input, nil)
Expect(err).NotTo(HaveOccurred())
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("search"))
// The value should be trimmed but preserve internal structure
args := results[0].Arguments
Expect(args).To(ContainSubstring("query"))
Expect(args).To(ContainSubstring("multi-line"))
})
It("should return empty results for invalid XML", func() {
input := `<tool_call>
<function=test>
<parameter=x>
</function>
</tool_call>`
results, err := ParseXML(input, nil)
Expect(err).NotTo(HaveOccurred())
// Should handle gracefully, might return partial results or empty
Expect(results).NotTo(BeNil())
// Results may be empty for incomplete input, which is acceptable
})
It("should return empty results when no XML tool calls found", func() {
input := `Just some regular text without any XML tool calls`
results, err := ParseXML(input, nil)
Expect(err).NotTo(HaveOccurred())
Expect(results).To(HaveLen(0))
})
It("should handle parameter values that are JSON", func() {
input := `<tool_call>
<function=process>
<parameter=config>
{"key": "value", "number": 42}
</parameter>
</function>
</tool_call>`
results, err := ParseXML(input, nil)
Expect(err).NotTo(HaveOccurred())
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("process"))
// JSON values should be parsed as JSON objects
Expect(results[0].Arguments).To(ContainSubstring("key"))
Expect(results[0].Arguments).To(ContainSubstring("value"))
})
It("should auto-detect Qwen3-Coder format", func() {
input := `<tool_call>
<function=test>
<parameter=key>
value
</parameter>
</function>
</tool_call>`
results, err := ParseXML(input, nil)
Expect(err).NotTo(HaveOccurred())
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("test"))
})
It("should auto-detect GLM 4.5 format", func() {
input := `<tool_call>
test_function
<arg_key>key1</arg_key>
<arg_value>value1</arg_value>
<arg_key>key2</arg_key>
<arg_value>value2</arg_value>
</tool_call>`
results, err := ParseXML(input, nil)
Expect(err).NotTo(HaveOccurred())
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("test_function"))
Expect(results[0].Arguments).To(ContainSubstring("key1"))
Expect(results[0].Arguments).To(ContainSubstring("value1"))
})
It("should auto-detect MiniMax-M2 format", func() {
input := `<minimax:tool_call>
<invoke name="test_function">
<parameter name="key1">value1</parameter>
<parameter name="key2">value2</parameter>
</invoke>
</minimax:tool_call>`
results, err := ParseXML(input, nil)
Expect(err).NotTo(HaveOccurred())
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("test_function"))
Expect(results[0].Arguments).To(ContainSubstring("key1"))
})
It("should auto-detect Functionary format", func() {
input := `<function=test_function>{"key1": "value1", "key2": "value2"}</function>`
results, err := ParseXML(input, nil)
Expect(err).NotTo(HaveOccurred())
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("test_function"))
Expect(results[0].Arguments).To(ContainSubstring("key1"))
})
It("should use forced format when preset is specified via config", func() {
input := `<tool_call>
<function=test>
<parameter=key>
value
</parameter>
</function>
</tool_call>`
functionConfig.XMLFormatPreset = "qwen3-coder"
results := ParseFunctionCall(input, functionConfig)
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("test"))
})
It("should handle GLM 4.5 format with arg_key/arg_value pairs", func() {
input := `<tool_call>
search_function
<arg_key>query</arg_key>
<arg_value>test search</arg_value>
<arg_key>limit</arg_key>
<arg_value>10</arg_value>
</tool_call>`
results, err := ParseXML(input, nil)
Expect(err).NotTo(HaveOccurred())
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("search_function"))
Expect(results[0].Arguments).To(ContainSubstring("query"))
Expect(results[0].Arguments).To(ContainSubstring("test search"))
})
It("should strip Kimi-K2 function name prefixes", func() {
// Kimi-K2 format: <|tool_calls_section_begin|><|tool_call_begin|>functions.name:index<|tool_call_argument_begin|>{JSON}<|tool_call_end|><|tool_calls_section_end|>
// The function name is between tool_start and tool_sep, arguments are JSON between tool_sep and tool_end
input := `<|tool_calls_section_begin|>
<|tool_call_begin|>
functions.search:0<|tool_call_argument_begin|>{"query": "test", "limit": 10}<|tool_call_end|>
<|tool_calls_section_end|>`
// Test auto-detection should find Kimi-K2 format
results, err := ParseXML(input, nil)
Expect(err).NotTo(HaveOccurred())
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("search"))
Expect(results[0].Arguments).To(ContainSubstring("query"))
})
It("should handle formats with last_val_end for last parameter", func() {
// Apriel-1.5 format uses last_val_end (empty string) for last parameter
input := `<tool_calls>[
{"name": "test_function", "arguments": {"key1": "value1", "key2": "value2"}}
]</tool_calls>`
results, err := ParseXML(input, nil)
Expect(err).NotTo(HaveOccurred())
// Should parse JSON-like format
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("test_function"))
})
It("should validate scope_start has only whitespace before it", func() {
// This should NOT match because there's non-whitespace before scope_start
input := `text<minimax:tool_call>
<invoke name="test">
<parameter name="key">value</parameter>
</invoke>
</minimax:tool_call>`
// The scope validation should prevent matching when there's text before scope_start
// However, our current implementation will still match because regex is greedy
// This is a limitation of regex-based parsing vs streaming parser
results, err := ParseXML(input, nil)
// The iterative parser should reject this (scope validation), but ParseXML falls back to regex
// So it should succeed with regex parser
Expect(err).NotTo(HaveOccurred())
// Regex parser accepts it (this is a known limitation)
Expect(results).NotTo(BeNil())
})
It("should handle empty tool calls with no arguments", func() {
// Tool call with no parameters should return empty arguments object
input := `<tool_call>
<function=test_function>
</function>
</tool_call>`
results, err := ParseXML(input, nil)
Expect(err).NotTo(HaveOccurred())
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("test_function"))
Expect(results[0].Arguments).To(Equal("{}"))
})
It("should support partial parsing for streaming", func() {
// Partial XML that ends mid-tag should be detected
input := `<tool_call>
<function=test>
<parameter=key>
value
</parameter>`
// ParseXMLIterative with isPartial=true handles streaming
results, err := ParseXMLIterative(input, nil, true)
Expect(err).NotTo(HaveOccurred())
// Should return partial results (may have 0 complete tool calls since function is not closed)
_ = results
})
It("should parse JSON values correctly in all formats", func() {
// Test that numeric strings are parsed as numbers (not strings)
input := `<tool_call>
<function=test>
<parameter=count>
42
</parameter>
<parameter=enabled>
true
</parameter>
</function>
</tool_call>`
results, err := ParseXML(input, nil)
Expect(err).NotTo(HaveOccurred())
Expect(results).To(HaveLen(1))
// JSON parsing should convert "42" to number 42 and "true" to boolean true
Expect(results[0].Arguments).To(ContainSubstring(`"count":42`))
Expect(results[0].Arguments).To(ContainSubstring(`"enabled":true`))
})
It("should handle reasoning blocks with tool calls", func() {
// Test parsing tool calls that appear after reasoning blocks
// Note: parseMsgWithXMLToolCalls is currently internal, so we test through ParseXML
// which should still parse tool calls even with reasoning blocks present
input := `<think>
I need to search for information.
</think>
<tool_call>
<function=search>
<parameter=query>
test query
</parameter>
</function>
</tool_call>`
// ParseXML should extract tool calls even with reasoning blocks
results, err := ParseXML(input, nil)
Expect(err).NotTo(HaveOccurred())
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("search"))
})
It("should use iterative parser for streaming scenarios", func() {
// Test that ParseXMLIterative works correctly
input := `<tool_call>
<function=test_function>
<parameter=key1>
value1
</parameter>
<parameter=key2>
value2
</parameter>
</function>
</tool_call>`
results, err := ParseXMLIterative(input, nil, false)
Expect(err).NotTo(HaveOccurred())
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("test_function"))
Expect(results[0].Arguments).To(ContainSubstring("key1"))
Expect(results[0].Arguments).To(ContainSubstring("value1"))
})
It("should handle partial parsing with iterative parser", func() {
// Test partial parsing with iterative parser
input := `<tool_call>
<function=test>
<parameter=key>
value
</parameter>`
results, err := ParseXMLIterative(input, nil, true)
// Should handle partial content gracefully
// Either returns partial results or empty, but should not error
Expect(err).NotTo(HaveOccurred())
// Results may be empty or contain partial tool call
Expect(results).NotTo(BeNil())
})
})
Context("ParseFunctionCall with XML tool calls", func() {
It("should parse XML tool calls when JSON parsing fails", func() {
input := `A message from the LLM
<tool_call>
<function=glob>
<parameter=pattern>
**/package.json
</parameter>
</function>
</tool_call>`
results := ParseFunctionCall(input, functionConfig)
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("glob"))
Expect(results[0].Arguments).To(Equal(`{"pattern":"**/package.json"}`))
})
It("should parse tool calls when reasoning (<think>) precedes tool block (Qwen3.5-style)", func() {
input := `<think>
I need to run a command.
</think>
<tool_call>
<function=bash>
<parameter=script>
echo hello
</parameter>
</function>
</tool_call>`
cfg := FunctionsConfig{}
results := ParseFunctionCall(input, cfg)
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("bash"))
Expect(results[0].Arguments).To(ContainSubstring("echo hello"))
})
It("should parse tool calls when reasoning (<think>) precedes tool block (Qwen3.5-style)", func() {
input := `<think>
I need to run a command.
</think>
<tool_call>
<function=bash>
<parameter=script>
echo hello
</parameter>
</function>
</tool_call>`
cfg := FunctionsConfig{}
cfg.XMLFormatPreset = "qwen3.5"
results := ParseFunctionCall(input, cfg)
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("bash"))
Expect(results[0].Arguments).To(ContainSubstring("echo hello"))
})
It("should parse XML tool calls alongside JSON tool calls", func() {
input := `{"name": "add", "arguments": {"x": 5, "y": 3}}
<tool_call>
<function=subtract>
<parameter=x>
10
</parameter>
<parameter=y>
7
</parameter>
</function>
</tool_call>`
results := ParseFunctionCall(input, functionConfig)
// Should find both JSON and XML tool calls
Expect(results).To(HaveLen(2))
// First result should be from JSON
Expect(results[0].Name).To(Equal("add"))
// Second result should be from XML
Expect(results[1].Name).To(Equal("subtract"))
})
It("should handle mixed content with text, JSON, and XML", func() {
input := `Some introductory text
{"name": "first", "arguments": {"a": 1}}
More text in between
<tool_call>
<function=second>
<parameter=b>
2
</parameter>
</function>
</tool_call>
Final text`
results := ParseFunctionCall(input, functionConfig)
Expect(results).To(HaveLen(2))
Expect(results[0].Name).To(Equal("first"))
Expect(results[1].Name).To(Equal("second"))
})
It("should not duplicate parse JSON inside tool_call tags", func() {
// This test reproduces a bug where JSON inside <tool_call> tags
// gets parsed twice: once as JSON (correctly) and once as XML (incorrectly)
// The XML parser should not run when JSON parsing already found valid results
input := `<tool_call>
{"name": "get_current_weather", "arguments": {"location": "Beijing", "unit": "celsius"}}
</tool_call>`
results := ParseFunctionCall(input, functionConfig)
// Should only have 1 result, not 2 (one correct + one malformed)
Expect(results).To(HaveLen(1), "Should not create duplicate entries when JSON is inside XML tags")
Expect(results[0].Name).To(Equal("get_current_weather"))
Expect(results[0].Arguments).To(Equal(`{"location":"Beijing","unit":"celsius"}`))
// Verify the name is not the entire JSON object (which would indicate malformed XML parsing)
Expect(results[0].Name).NotTo(ContainSubstring(`{"name"`), "Function name should not contain JSON object")
})
})
Context("Iterative Parser (ChatMsgParser)", func() {
Describe("Basic functionality", func() {
It("should track position correctly", func() {
parser := NewChatMsgParser("hello world", false)
Expect(parser.Pos()).To(Equal(0))
Expect(parser.Input()).To(Equal("hello world"))
Expect(parser.IsPartial()).To(BeFalse())
err := parser.MoveTo(5)
Expect(err).NotTo(HaveOccurred())
Expect(parser.Pos()).To(Equal(5))
err = parser.MoveBack(2)
Expect(err).NotTo(HaveOccurred())
Expect(parser.Pos()).To(Equal(3))
})
It("should handle position errors", func() {
parser := NewChatMsgParser("test", false)
err := parser.MoveTo(10)
Expect(err).To(HaveOccurred())
err = parser.MoveBack(10)
Expect(err).To(HaveOccurred())
})
It("should find literals correctly", func() {
parser := NewChatMsgParser("hello world test", false)
result := parser.TryFindLiteral("world")
Expect(result).NotTo(BeNil())
Expect(result.Prelude).To(Equal("hello "))
Expect(parser.Pos()).To(Equal(11)) // After "world"
})
It("should consume literals correctly", func() {
parser := NewChatMsgParser("hello world", false)
success := parser.TryConsumeLiteral("hello")
Expect(success).To(BeTrue())
Expect(parser.Pos()).To(Equal(5))
success = parser.TryConsumeLiteral("invalid")
Expect(success).To(BeFalse())
})
It("should consume spaces", func() {
parser := NewChatMsgParser(" hello", false)
consumed := parser.ConsumeSpaces()
Expect(consumed).To(BeTrue())
Expect(parser.Pos()).To(Equal(3))
})
It("should add content and tool calls", func() {
parser := NewChatMsgParser("test", false)
parser.AddContent("hello")
parser.AddReasoningContent("thinking")
parser.AddToolCall("test_func", "", `{"arg":"value"}`)
Expect(parser.Content()).To(Equal("hello"))
Expect(parser.Reasoning()).To(Equal("thinking"))
Expect(parser.ToolCalls()).To(HaveLen(1))
Expect(parser.ToolCalls()[0].Name).To(Equal("test_func"))