tools_test.go 32.5 KB
Newer Older
1
2
3
package tools

import (
4
	"strings"
5
	"testing"
6
	"text/template"
7
8
9
10
11

	"github.com/google/go-cmp/cmp"
	"github.com/ollama/ollama/api"
)

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// argsComparer provides cmp options for comparing ToolCallFunctionArguments by value (order-insensitive)
var argsComparer = cmp.Comparer(func(a, b api.ToolCallFunctionArguments) bool {
	return cmp.Equal(a.ToMap(), b.ToMap())
})

// testPropsMap creates a ToolPropertiesMap from a map (convenience function for tests, order not preserved)
func testPropsMap(m map[string]api.ToolProperty) *api.ToolPropertiesMap {
	props := api.NewToolPropertiesMap()
	for k, v := range m {
		props.Set(k, v)
	}
	return props
}

// testArgs creates ToolCallFunctionArguments from a map (convenience function for tests, order not preserved)
func testArgs(m map[string]any) api.ToolCallFunctionArguments {
	args := api.NewToolCallFunctionArguments()
	for k, v := range m {
		args.Set(k, v)
	}
	return args
}

35
36
37
38
39
func TestParser(t *testing.T) {
	qwen, err := template.New("qwen").Parse(`{{if .ToolCalls}}<tool_call>{{range .ToolCalls}}{"name": "{{.Function.Name}}", "arguments": {{.Function.Arguments}}}{{end}}</tool_call>{{end}}`)
	if err != nil {
		t.Fatalf("Failed to parse template: %v", err)
	}
40

41
	deepseek, err := template.New("deepseek").Parse("{{if .ToolCalls}}<|tool▁calls▁begin|>{{range .ToolCalls}}<|tool▁call▁begin|>function<|tool▁sep|>get_current_weather\n```json\n{\"location\": \"Tokyo\"}\n```<|tool▁call▁end|>{{end}}<|tool▁calls▁end|><|end▁of▁sentence|>{{end}}")
42
	if err != nil {
43
		t.Fatalf("Failed to parse template: %v", err)
44
45
	}

46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
	json, err := template.New("json").Parse(`{{if .ToolCalls}}{{range .ToolCalls}}{"name": "{{.Function.Name}}", "arguments": {{.Function.Arguments}}}{{end}}{{end}}`)
	if err != nil {
		t.Fatalf("Failed to parse template: %v", err)
	}

	mistral, err := template.New("mistral").Parse(`{{if .ToolCalls}}[TOOL_CALLS] [{{range .ToolCalls}}{"name": "{{.Function.Name}}", "arguments": {{.Function.Arguments}}}{{end}}][/TOOL_CALLS]{{end}}`)
	if err != nil {
		t.Fatalf("Failed to parse template: %v", err)
	}

	list, err := template.New("list").Parse(`{{if .ToolCalls}}[{{range .ToolCalls}}{"name": "{{.Function.Name}}", "arguments": {{.Function.Arguments}}}{{end}}]{{end}}`)
	if err != nil {
		t.Fatalf("Failed to parse template: %v", err)
	}

	tools := []api.Tool{
		{
			Type: "function",
			Function: api.ToolFunction{
				Name:        "get_temperature",
				Description: "Retrieve the temperature for a given location",
67
				Parameters: api.ToolFunctionParameters{
68
69
					Type:     "object",
					Required: []string{"city"},
70
					Properties: testPropsMap(map[string]api.ToolProperty{
71
72
73
74
75
76
77
78
79
						"format": {
							Type:        api.PropertyType{"string"},
							Description: "The format to return the temperature in",
							Enum:        []any{"fahrenheit", "celsius"},
						},
						"city": {
							Type:        api.PropertyType{"string"},
							Description: "The city to get the temperature for",
						},
80
					}),
81
82
83
84
85
86
87
88
				},
			},
		},
		{
			Type: "function",
			Function: api.ToolFunction{
				Name:        "get_conditions",
				Description: "Retrieve the current weather conditions for a given location",
89
				Parameters: api.ToolFunctionParameters{
90
					Type: "object",
91
					Properties: testPropsMap(map[string]api.ToolProperty{
92
93
94
95
						"location": {
							Type:        api.PropertyType{"string"},
							Description: "The location to get the weather conditions for",
						},
96
					}),
97
98
99
				},
			},
		},
100
101
102
103
104
105
106
		{
			Type: "function",
			Function: api.ToolFunction{
				Name:        "say_hello",
				Description: "Say hello",
			},
		},
107
108
109
110
111
112
113
114
115
116
117
118
		{
			Type: "function",
			Function: api.ToolFunction{
				Name:        "say_hello_world",
				Description: "Say hello world",
			},
		},
		{
			Type: "function",
			Function: api.ToolFunction{
				Name:        "get_address",
				Description: "Get the address of a given location",
119
				Parameters: api.ToolFunctionParameters{
120
					Type: "object",
121
					Properties: testPropsMap(map[string]api.ToolProperty{
122
123
124
125
						"location": {
							Type:        api.PropertyType{"string"},
							Description: "The location to get the address for",
						},
126
					}),
127
128
129
130
131
132
133
134
				},
			},
		},
		{
			Type: "function",
			Function: api.ToolFunction{
				Name:        "add",
				Description: "Add two numbers",
135
				Parameters: api.ToolFunctionParameters{
136
					Type: "object",
137
					Properties: testPropsMap(map[string]api.ToolProperty{
138
139
140
141
142
143
144
145
						"a": {
							Type:        api.PropertyType{"string"},
							Description: "The first number to add",
						},
						"b": {
							Type:        api.PropertyType{"string"},
							Description: "The second number to add",
						},
146
					}),
147
148
149
				},
			},
		},
150
	}
151
152

	tests := []struct {
153
154
155
156
157
		name    string
		inputs  []string
		tmpl    *template.Template
		content string
		calls   []api.ToolCall
158
159
	}{
		{
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
			name:    "no tool calls - just text",
			inputs:  []string{"Hello, how can I help you today?"},
			content: "Hello, how can I help you today?",
			tmpl:    qwen,
			calls:   nil,
		},
		{
			name:    "empty input",
			inputs:  []string{""},
			content: "",
			tmpl:    qwen,
			calls:   nil,
		},
		{
			name:    "tool call",
			inputs:  []string{`<tool_call>{"name": "get_conditions", "arguments": {"location": "San Francisco"}}</tool_call>`},
			content: "",
			tmpl:    qwen,
			calls: []api.ToolCall{
179
180
				{
					Function: api.ToolCallFunction{
181
182
						Index: 0,
						Name:  "get_conditions",
183
						Arguments: testArgs(map[string]any{
184
							"location": "San Francisco",
185
						}),
186
187
188
					},
				},
			},
189
		},
190
		{
191
192
193
194
195
196
197
198
199
			name:    "empty args",
			inputs:  []string{`<tool_call>{"name": "get_conditions", "arguments": {}}</tool_call>`},
			content: "",
			tmpl:    qwen,
			calls: []api.ToolCall{
				{
					Function: api.ToolCallFunction{
						Index:     0,
						Name:      "get_conditions",
200
						Arguments: api.NewToolCallFunctionArguments(),
201
202
203
204
					},
				},
			},
		},
205
206
207
208
209
210
		{
			name:    "text before tool call",
			inputs:  []string{`Let me check the weather. <tool_call>{"name": "get_temperature", "arguments": {"city": "New York"}}</tool_call>`},
			content: "Let me check the weather. ",
			tmpl:    qwen,
			calls: []api.ToolCall{
211
212
				{
					Function: api.ToolCallFunction{
213
214
						Index: 0,
						Name:  "get_temperature",
215
						Arguments: testArgs(map[string]any{
216
							"city": "New York",
217
						}),
218
219
220
221
					},
				},
			},
		},
222
223
224
225
226
227
228
		{
			name:    "qwen no args with text",
			inputs:  []string{"Let me say hello to the user. I'll use the say_hello tool. "},
			content: "Let me say hello to the user. I'll use the say_hello tool. ",
			tmpl:    qwen,
			calls:   nil,
		},
229
230
231
232
233
234
235
236
237
238
		{
			name:    "two tool calls in a list",
			inputs:  []string{`[TOOL_CALLS] [{"name": "get_temperature", "arguments": {"city": "London", "format": "fahrenheit"}}, {"name": "get_conditions", "arguments": {"location": "Tokyo"}}][/TOOL_CALLS]`},
			content: "",
			tmpl:    mistral,
			calls: []api.ToolCall{
				{
					Function: api.ToolCallFunction{
						Index: 0,
						Name:  "get_temperature",
239
						Arguments: testArgs(map[string]any{
240
241
							"city":   "London",
							"format": "fahrenheit",
242
						}),
243
244
245
246
					},
				},
				{
					Function: api.ToolCallFunction{
247
248
						Index: 1,
						Name:  "get_conditions",
249
						Arguments: testArgs(map[string]any{
250
							"location": "Tokyo",
251
						}),
252
253
254
					},
				},
			},
255
256
		},
		{
257
			name:    "qwen two tool calls",
258
259
260
261
			inputs:  []string{`Okay, let's call both tools! <tool_call>{"name": "get_temperature", "arguments": {"city": "London", "format": "fahrenheit"}}</tool_call><tool_call>{"name": "get_conditions", "arguments": {"location": "Tokyo"}}</tool_call>`},
			content: "Okay, let's call both tools! ",
			tmpl:    qwen,
			calls: []api.ToolCall{
262
263
				{
					Function: api.ToolCallFunction{
264
265
						Index: 0,
						Name:  "get_temperature",
266
						Arguments: testArgs(map[string]any{
267
268
							"city":   "London",
							"format": "fahrenheit",
269
						}),
270
271
272
273
					},
				},
				{
					Function: api.ToolCallFunction{
274
275
						Index: 1,
						Name:  "get_conditions",
276
						Arguments: testArgs(map[string]any{
277
							"location": "Tokyo",
278
						}),
279
280
281
					},
				},
			},
282
		},
283
		{
284
285
286
			name:    "empty args followed by args",
			inputs:  []string{`Let me say hello and check the weather. <tool_call>{"name": "say_hello", "arguments": {}}</tool_call><tool_call>{"name": "get_temperature", "arguments": {"city": "London", "format": "fahrenheit"}}</tool_call>`},
			content: "Let me say hello and check the weather. ",
287
288
289
290
			tmpl:    qwen,
			calls: []api.ToolCall{
				{
					Function: api.ToolCallFunction{
291
292
						Index:     0,
						Name:      "say_hello",
293
						Arguments: api.NewToolCallFunctionArguments(),
294
295
					},
				},
296
297
298
299
				{
					Function: api.ToolCallFunction{
						Index: 1,
						Name:  "get_temperature",
300
						Arguments: testArgs(map[string]any{
301
302
							"city":   "London",
							"format": "fahrenheit",
303
						}),
304
305
306
307
308
309
310
311
312
313
314
315
316
317
					},
				},
			},
		},
		{
			name:    "qwen empty followed by args",
			inputs:  []string{`Let me check the weather. <tool_call>{"name": "get_conditions", "arguments": {}}</tool_call><tool_call>{"name": "get_conditions", "arguments": {"location": "Tokyo"}}`},
			content: "Let me check the weather. ",
			tmpl:    qwen,
			calls: []api.ToolCall{
				{
					Function: api.ToolCallFunction{
						Index:     0,
						Name:      "get_conditions",
318
						Arguments: api.NewToolCallFunctionArguments(),
319
320
					},
				},
321
322
323
324
				{
					Function: api.ToolCallFunction{
						Index: 1,
						Name:  "get_conditions",
325
						Arguments: testArgs(map[string]any{
326
							"location": "Tokyo",
327
						}),
328
329
330
331
					},
				},
			},
		},
332
333
334
335
336
337
		{
			name:    "deepseek",
			inputs:  []string{"<think>Wait, I need to call a tool</think><|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>get_temperature\n```json\n{\"city\": \"Tokyo\"}\n```<|tool▁call▁end|><|tool▁calls▁end|><|end▁of▁sentence|>"},
			content: "<think>Wait, I need to call a tool</think>",
			tmpl:    deepseek,
			calls: []api.ToolCall{
338
339
				{
					Function: api.ToolCallFunction{
340
341
						Index: 0,
						Name:  "get_temperature",
342
						Arguments: testArgs(map[string]any{
343
							"city": "Tokyo",
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
			},
		},
		{
			name: "deepseek incremental",
			inputs: []string{
				"<think>Wait",
				", I need",
				" to call",
				" a tool</think><|too",
				"l▁calls▁begin",
				"|>",
				"<|tool▁call▁begin|>function<|tool▁sep|>get_temperature\n",
				"```json\n",
				"{\"city\": \"Tokyo\"}\n",
				"```",
				"<|tool▁c", "all▁end|>",
				"<|tool▁calls▁end|>",
				"<|end▁of▁sentence|>",
			},
			content: "<think>Wait, I need to call a tool</think>",
			tmpl:    deepseek,
			calls: []api.ToolCall{
369
370
				{
					Function: api.ToolCallFunction{
371
372
						Index: 0,
						Name:  "get_temperature",
373
						Arguments: testArgs(map[string]any{
374
							"city": "Tokyo",
375
						}),
376
377
378
379
380
					},
				},
			},
		},
		{
381
382
383
384
385
386
387
388
389
390
391
392
			name: "json",
			inputs: []string{
				"{",
				"\"name\": \"get_temperature\",",
				"\"arguments\": {",
				"\"city\": \"Tokyo\"",
				"}",
				"}",
			},
			content: "",
			tmpl:    json,
			calls: []api.ToolCall{
393
394
				{
					Function: api.ToolCallFunction{
395
396
						Index: 0,
						Name:  "get_temperature",
397
						Arguments: testArgs(map[string]any{
398
							"city": "Tokyo",
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
		},
		{
			name: "json maybe a tool call",
			inputs: []string{
				"{",
				"\"name\": \"get_temperature\",",
				"\"arguments\": {",
			},
			content: "",
			tmpl:    json,
			calls:   nil,
		},
		{
			name: "json not a tool call",
			inputs: []string{
				"{",
				"\"name\": \"search\", ",
				"\"arguments\": {",
				"\"query\": \"What is the capital of Canada?\"",
				"}",
				"}",
			},
			content: "{\"name\": \"search\", \"arguments\": {\"query\": \"What is the capital of Canada?\"}}",
			tmpl:    json,
			calls:   nil,
		},
		{
			name: "json object followed by tool call",
			inputs: []string{
				"{\"name\": \"jeff\"}",
				"{\"name\": \"get_conditions\", \"arguments\": {\"location\": \"San Francisco\"}}",
			},
			content: "{\"name\": \"jeff\"}{\"name\": \"get_conditions\", \"arguments\": {\"location\": \"San Francisco\"}}",
			tmpl:    json,
		},
		{
			name: "json object followed by tool call split",
			inputs: []string{
				"{\"name\": \"jeff\"} {",
				"\"name\": \"get_conditions\", \"arguments\": {\"location\": \"San Francisco\"}}",
			},
			content: "{\"name\": \"jeff\"} {\"name\": \"get_conditions\", \"arguments\": {\"location\": \"San Francisco\"}}",
			tmpl:    json,
		},
		{
			name: "json code",
			inputs: []string{
				"for { fmt.Println(\"hello\") }",
			},
			content: "for { fmt.Println(\"hello\") }",
			tmpl:    json,
		},
		{
			name: "list multiple",
			inputs: []string{
				"[",
				"{",
				"\"name\": \"get_temperature\", ",
				"\"arguments\": {",
				"\"city\": \"London\"",
				"}",
				"},",
				"{",
				"\"name\": \"get_conditions\", ",
				"\"arguments\": {",
				"\"location\": \"Tokyo\"",
				"}",
				"}]",
			},
			content: "",
			tmpl:    list,
			calls: []api.ToolCall{
475
476
				{
					Function: api.ToolCallFunction{
477
478
						Index: 0,
						Name:  "get_temperature",
479
						Arguments: testArgs(map[string]any{
480
							"city": "London",
481
						}),
482
483
					},
				},
484
485
486
487
				{
					Function: api.ToolCallFunction{
						Index: 1,
						Name:  "get_conditions",
488
						Arguments: testArgs(map[string]any{
489
							"location": "Tokyo",
490
						}),
491
492
493
494
495
496
					},
				},
			},
		},
		{
			name: "list partial",
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
			inputs: []string{
				"[{",
				"\"name\": \"get_conditions\", ",
				"\"arguments\": {",
				"\"location\": \"Tokyo\"",
				"}",
				"}",
			},
			content: "",
			tmpl:    list,
			calls: []api.ToolCall{
				{
					Function: api.ToolCallFunction{
						Index: 0,
						Name:  "get_conditions",
512
						Arguments: testArgs(map[string]any{
513
							"location": "Tokyo",
514
						}),
515
516
517
518
519
520
					},
				},
			},
		},
		{
			name: "list invalid",
521
522
523
524
525
526
527
528
529
530
531
532
533
			inputs: []string{
				"[",
				"{",
				"\"name\": \"search\", ",
				"\"arguments\": {",
				"\"query\": \"What is the capital of Canada?\"",
				"}",
				"}",
			},
			content: "",
			tmpl:    list,
			calls:   nil,
		},
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
		{
			name: "list trailing ]",
			inputs: []string{
				"[",
				"{",
				"\"name\": \"get_conditions\", ",
				"\"arguments\": {",
				"\"location\": \"Tokyo\"",
				"}",
				"}",
				"]",
				"]",
			},
			content: "",
			tmpl:    list,
			calls: []api.ToolCall{
				{
					Function: api.ToolCallFunction{
						Index: 0,
						Name:  "get_conditions",
554
						Arguments: testArgs(map[string]any{
555
							"location": "Tokyo",
556
						}),
557
558
559
560
					},
				},
			},
		},
561
562
563
564
565
566
		{
			name: "list not a tool call",
			inputs: []string{
				"[special",
				" del",
				"ivery]",
567
			},
568
569
570
			content: "[special delivery]",
			tmpl:    list,
			calls:   nil,
571
		},
572
573
574
575
576
577
578
		{
			name: "tool name with collision",
			inputs: []string{
				"<tool_call>",
				"{",
				"\"name\": \"say_hello",
				"_world\",",
579
				"\"arguments\": {}}",
580
581
582
583
584
585
586
587
588
				"}",
			},
			content: "",
			tmpl:    qwen,
			calls: []api.ToolCall{
				{
					Function: api.ToolCallFunction{
						Index:     0,
						Name:      "say_hello_world",
589
						Arguments: api.NewToolCallFunctionArguments(),
590
591
592
593
594
595
596
597
598
599
600
					},
				},
			},
		},
		{
			name: "tool name with collision multiple",
			inputs: []string{
				"<tool_call>",
				"{",
				"\"name\": \"say_hello",
				"_world\",",
601
				"\"arguments\": {}}",
602
603
604
605
606
				"</tool_call>",
				"<tool_call>",
				"{",
				"\"name\": \"say_hello",
				"\",",
607
				"\"arguments\": {}}",
608
609
610
611
612
613
614
615
616
				"</tool_call>",
			},
			content: "",
			tmpl:    qwen,
			calls: []api.ToolCall{
				{
					Function: api.ToolCallFunction{
						Index:     0,
						Name:      "say_hello_world",
617
						Arguments: api.NewToolCallFunctionArguments(),
618
619
620
621
622
623
					},
				},
				{
					Function: api.ToolCallFunction{
						Index:     1,
						Name:      "say_hello",
624
						Arguments: api.NewToolCallFunctionArguments(),
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
					},
				},
			},
		},
		{
			name: "tool name with collision non streaming",
			inputs: []string{
				`<tool_call>{"name": "say_hello`,
			},
			content: "",
			tmpl:    qwen,
			calls:   nil,
		},
		{
			name: "tool name with collision non streaming multiple",
			inputs: []string{
641
				`<tool_call>{"name": "say_hello", "arguments": {}}</tool_call><tool_call>{"name": "say_hello_world", "arguments": {}}`,
642
643
644
645
646
647
648
649
			},
			content: "",
			tmpl:    qwen,
			calls: []api.ToolCall{
				{
					Function: api.ToolCallFunction{
						Index:     0,
						Name:      "say_hello",
650
						Arguments: api.NewToolCallFunctionArguments(),
651
652
653
654
655
656
					},
				},
				{
					Function: api.ToolCallFunction{
						Index:     1,
						Name:      "say_hello_world",
657
						Arguments: api.NewToolCallFunctionArguments(),
658
659
660
661
662
663
664
					},
				},
			},
		},
		{
			name: "tool name with collision non streaming shorter",
			inputs: []string{
665
				`<tool_call>{"name": "say_hello", "arguments": {}}</tool_call>`,
666
667
668
669
670
671
672
673
			},
			content: "",
			tmpl:    qwen,
			calls: []api.ToolCall{
				{
					Function: api.ToolCallFunction{
						Index:     0,
						Name:      "say_hello",
674
						Arguments: api.NewToolCallFunctionArguments(),
675
676
677
678
679
680
681
					},
				},
			},
		},
		{
			name: "tool name with collision non streaming longer",
			inputs: []string{
682
				`<tool_call>{"name": "say_hello_world", "arguments": {}}</tool_call>`,
683
684
685
686
687
688
689
690
			},
			content: "",
			tmpl:    qwen,
			calls: []api.ToolCall{
				{
					Function: api.ToolCallFunction{
						Index:     0,
						Name:      "say_hello_world",
691
						Arguments: api.NewToolCallFunctionArguments(),
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
					},
				},
			},
		},
		{
			name: "tool name with substring of another",
			inputs: []string{
				"{",
				"\"name\": \"get_address\",",
				"\"arguments\": {",
				"\"location\": \"London\"",
				"}",
				"}",
			},
			content: "",
			tmpl:    json,
			calls: []api.ToolCall{
				{
					Function: api.ToolCallFunction{
						Index: 0,
						Name:  "get_address",
713
						Arguments: testArgs(map[string]any{
714
							"location": "London",
715
						}),
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
					},
				},
			},
		},
		{
			name: "tool name with substring of another",
			inputs: []string{
				`<tool_call>{"name": "get_address", "arguments": {"location": "London"}}</tool_call>`,
			},
			content: "",
			tmpl:    qwen,
			calls: []api.ToolCall{
				{
					Function: api.ToolCallFunction{
						Index: 0,
						Name:  "get_address",
732
						Arguments: testArgs(map[string]any{
733
							"location": "London",
734
						}),
735
736
737
738
					},
				},
			},
		},
739
740
741
742
743
744
745
746
747
748
749
750
		{
			name: "args before name",
			inputs: []string{
				`<tool_call>{"arguments": {"a": "5", "b": "10"}, "name": "add"}</tool_call>`,
			},
			content: "",
			tmpl:    qwen,
			calls: []api.ToolCall{
				{
					Function: api.ToolCallFunction{
						Index: 0,
						Name:  "add",
751
						Arguments: testArgs(map[string]any{
752
753
							"a": "5",
							"b": "10",
754
						}),
755
756
757
758
					},
				},
			},
		},
759
760
761
762
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
763
			parser := NewParser(tt.tmpl, tools)
764

765
766
767
768
769
770
			var calls []api.ToolCall
			var content string
			for _, input := range tt.inputs {
				tcs, c := parser.Add(input)
				calls = append(calls, tcs...)
				content += c
771
772
			}

773
774
			if content != tt.content {
				t.Errorf("Expected content %q, got %q", tt.content, content)
775
776
			}

777
778
779
780
781
			if len(calls) != len(tt.calls) {
				t.Fatalf("Expected %d tool calls, got %d", len(tt.calls), len(calls))
			}

			for i, want := range tt.calls {
782
				if diff := cmp.Diff(calls[i], want, argsComparer); diff != "" {
783
784
					t.Errorf("Tool call %d mismatch (-got +want):\n%s", i, diff)
				}
785
786
787
788
789
			}
		})
	}
}

790
791
792
793
794
795
func TestDone(t *testing.T) {
	tests := []struct {
		name   string
		tag    string
		buffer []byte
		want   bool
796
797
	}{
		{
798
799
800
801
			name:   "empty",
			tag:    "<tool_call>",
			buffer: []byte{},
			want:   false,
802
803
		},
		{
804
805
806
807
			name:   "empty",
			tag:    "<tool_call>",
			buffer: []byte{},
			want:   false,
808
809
		},
		{
810
811
812
813
			name:   "json open",
			tag:    "{",
			buffer: []byte("{\"name\": \"get_weather\""),
			want:   false,
814
815
		},
		{
816
817
818
819
			name:   "json closed",
			tag:    "{",
			buffer: []byte("{\"name\": \"get_weather\"}"),
			want:   true,
820
821
		},
		{
822
823
824
825
			name:   "json empty",
			tag:    "{",
			buffer: []byte("{}"),
			want:   true,
826
827
		},
		{
828
829
830
831
			name:   "list open",
			tag:    "[",
			buffer: []byte("[{\"name\": \"get_weather\""),
			want:   false,
832
833
		},
		{
834
835
836
837
			name:   "list closed",
			tag:    "[",
			buffer: []byte("[{\"name\": \"get_weather\"}]"),
			want:   true,
838
839
		},
		{
840
841
842
843
			name:   "list empty",
			tag:    "[",
			buffer: []byte("[]"),
			want:   true,
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
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			parser := &Parser{
				tag:    tt.tag,
				buffer: tt.buffer,
			}
			got := parser.done()
			if got != tt.want {
				t.Errorf("done() = %t, want %t", got, tt.want)
			}
		})
	}
}

func TestContent(t *testing.T) {
	tests := []struct {
		name    string
		tag     string
		content []byte
		want    string
		n       int
	}{
869
		{
870
871
872
873
874
			name:    "empty",
			content: []byte{},
			tag:     "{",
			want:    "",
			n:       0,
875
876
		},
		{
877
878
879
880
881
			name:    "tag",
			tag:     "<tool_call>",
			content: []byte("<tool_call>{\"name\": \"get_temperature\""),
			want:    "",
			n:       0,
882
883
		},
		{
884
885
886
887
888
			name:    "json object",
			tag:     "{",
			content: []byte("{\"name\": \"get_temperature\"}"),
			want:    "{\"name\": \"get_temperature\"}",
			n:       0,
889
890
		},
		{
891
892
893
894
895
			name:    "json object after called",
			tag:     "{",
			content: []byte("{\"hello\": \"world\"}"),
			want:    "{\"hello\": \"world\"}",
			n:       0,
896
897
		},
		{
898
899
900
901
902
			name:    "json object after called",
			tag:     "{",
			content: []byte("{\"hello\": \"world\"}"),
			want:    "",
			n:       1,
903
904
		},
		{
905
906
907
908
909
			name:    "list",
			tag:     "[",
			content: []byte("[{\"name\": \"get_temperature\"}]"),
			want:    "[{\"name\": \"get_temperature\"}]",
			n:       0,
910
911
		},
		{
912
913
914
915
916
			name:    "code",
			tag:     "{",
			content: []byte("{ fmt.Println(\"hello\")"),
			want:    "{ fmt.Println(\"hello\")",
			n:       0,
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
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			parser := &Parser{
				tag:    tt.tag,
				buffer: tt.content,
				n:      tt.n,
			}
			got := parser.Content()
			if got != tt.want {
				t.Errorf("Content() = %q, want %q", got, tt.want)
			}
		})
	}
}

func TestFindTag(t *testing.T) {
	cases := []struct {
		name   string
		buffer []byte
		tag    string
		i      int
		found  bool
	}{
943
		{
944
945
946
947
948
			name:   "no overlap",
			buffer: []byte("hello world"),
			tag:    "<tool_call>",
			i:      -1,
			found:  false,
949
950
		},
		{
951
952
953
954
955
			name:   "full overlap",
			buffer: []byte("<tool_call>"),
			tag:    "<tool_call>",
			i:      0,
			found:  true,
956
957
		},
		{
958
959
960
961
962
			name:   "whitespace",
			buffer: []byte("    <tool_call>\n {\"name\": \"bob\"}"),
			tag:    "<tool_call>",
			i:      4,
			found:  true,
963
964
		},
		{
965
966
967
968
969
			name:   "over",
			buffer: []byte("<tool_call>{\"name\""),
			tag:    "<tool_call>",
			i:      0,
			found:  true,
970
971
		},
		{
972
973
974
975
976
			name:   "partial overlap",
			buffer: []byte("text <tool_call>"),
			tag:    "<tool_call>",
			i:      5,
			found:  true,
977
978
		},
		{
979
980
981
982
983
			name:   "overlap with extra",
			buffer: []byte("<tool_calls><tool_call>"),
			tag:    "<tool_calls>",
			i:      0,
			found:  true,
984
985
		},
		{
986
987
988
989
990
			name:   "delimiter longer than string",
			buffer: []byte("<tool>"),
			tag:    "<tool_call>",
			i:      -1,
			found:  false,
991
992
		},
		{
993
994
995
996
997
			name:   "empty string",
			buffer: []byte{},
			tag:    "<tool_call>",
			i:      -1,
			found:  false,
998
999
		},
		{
1000
1001
1002
1003
1004
			name:   "single char overlap",
			buffer: []byte("test<"),
			tag:    "<tool_call>",
			i:      4,
			found:  false,
1005
1006
		},
		{
1007
1008
1009
1010
1011
			name:   "partial tool call",
			buffer: []byte("hello <tool_"),
			tag:    "<tool_call>",
			i:      6,
			found:  false,
1012
1013
		},
		{
1014
1015
1016
1017
1018
			name:   "square bracket",
			buffer: []byte("calling tools: ["),
			tag:    "[",
			i:      15,
			found:  true,
1019
1020
		},
		{
1021
1022
1023
1024
1025
			name:   "bracket",
			buffer: []byte("{\"name\": \"bob\""),
			tag:    "{",
			i:      0,
			found:  true,
1026
1027
		},
		{
1028
1029
1030
1031
1032
			name:   "bracket with whitespace",
			buffer: []byte("\n\n{\n\"name\": \"bob\""),
			tag:    "{",
			i:      2,
			found:  true,
1033
		},
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
	}

	for _, tt := range cases {
		t.Run(tt.name, func(t *testing.T) {
			parser := &Parser{
				tag:    tt.tag,
				buffer: tt.buffer,
				n:      0,
			}
			i, found := parser.findTag()
			if i != tt.i {
				t.Errorf("findTag(%q, %q) = %d; want %d", tt.buffer, tt.tag, i, tt.i)
			}
			if found != tt.found {
				t.Errorf("findTag(%q, %q) = %t; want %t", tt.buffer, tt.tag, found, tt.found)
			}
		})
	}
}

func TestFindArguments(t *testing.T) {
	tests := []struct {
		name   string
		buffer []byte
		want   map[string]any
1059
		tool   string
1060
	}{
1061
		{
1062
1063
1064
			name:   "empty string",
			buffer: []byte{},
			want:   nil,
1065
1066
		},
		{
1067
1068
1069
			name:   "whitespace only",
			buffer: []byte("   \n\t  "),
			want:   nil,
1070
1071
		},
		{
1072
1073
1074
			name:   "unbalanced braces - missing closing",
			buffer: []byte(`{"format": "fahrenheit", "location": "San Francisco"`),
			want:   nil,
1075
1076
		},
		{
1077
1078
1079
1080
1081
			name:   "unbalanced braces - extra closing",
			buffer: []byte(`{"format": "fahrenheit"}}`),
			want: map[string]any{
				"format": "fahrenheit",
			},
1082
1083
		},
		{
1084
1085
1086
			name:   "invalid JSON",
			buffer: []byte(`{format: fahrenheit, location: "San Francisco"}`),
			want:   nil,
1087
1088
		},
		{
1089
1090
1091
1092
1093
1094
			name:   "valid json",
			buffer: []byte(`{"name": "get_temperature", "arguments": {"format": "fahrenheit", "location": "San Francisco, CA"}}`),
			want: map[string]any{
				"format":   "fahrenheit",
				"location": "San Francisco, CA",
			},
1095
1096
		},
		{
1097
1098
1099
1100
1101
1102
			name:   "valid arguments with special tokens",
			buffer: []byte(`[tool]get_temperature[args]{"format": "fahrenheit", "location": "San Francisco, CA"}[end]`),
			want: map[string]any{
				"format":   "fahrenheit",
				"location": "San Francisco, CA",
			},
1103
1104
		},
		{
1105
			name:   "valid arguments in array",
1106
			buffer: []byte(`[{"name": "get_temperature", "arguments": {"format": "fahrenheit", "location": "San Francisco, CA"}}`),
1107
1108
1109
1110
			want: map[string]any{
				"format":   "fahrenheit",
				"location": "San Francisco, CA",
			},
1111
1112
		},
		{
1113
1114
1115
1116
1117
1118
			name:   "nested deep",
			buffer: []byte(`{"function": {"name": "get_temperature", "arguments": {"format": "fahrenheit", "location": "San Francisco, CA"}}}`),
			want: map[string]any{
				"format":   "fahrenheit",
				"location": "San Francisco, CA",
			},
1119
1120
		},
		{
1121
			name:   "one arg",
1122
			buffer: []byte(`get_temperature({"location": "San Francisco, CA"})`),
1123
1124
1125
			want: map[string]any{
				"location": "San Francisco, CA",
			},
1126
1127
		},
		{
1128
			name:   "two args",
1129
			buffer: []byte(`[{"name": "get_temperature", "arguments": {"location": "San Francisco, CA", "format": "fahrenheit"}}, {"name": "get_weather", "arguments": {"location": "San Francisco, CA", "format": "fahrenheit"}}]`),
1130
1131
1132
1133
			want: map[string]any{
				"location": "San Francisco, CA",
				"format":   "fahrenheit",
			},
1134
1135
		},
		{
1136
			name:   "deepseek",
1137
			buffer: []byte("<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>get_temperature\n```json\n{\"location\": \"Tokyo\"}\n```<|tool▁call▁end|><|tool▁calls▁end|><|end▁of▁sentence|>"),
1138
1139
1140
			want: map[string]any{
				"location": "Tokyo",
			},
1141
		},
1142
1143
		{
			name:   "deepseek",
1144
			buffer: []byte(`"arguments": {"location": "Tokyo"}}</tool_call>`),
1145
1146
1147
1148
			want: map[string]any{
				"location": "Tokyo",
			},
		},
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
		{
			name:   "string with braces",
			buffer: []byte(`{"name": "process_code", "arguments": {"code": "if (x > 0) { return true; }"}}`),
			want: map[string]any{
				"code": "if (x > 0) { return true; }",
			},
		},
		{
			name:   "string with nested json",
			buffer: []byte(`{"name": "send_data", "arguments": {"payload": "{\"nested\": {\"key\": \"value\"}}"}}`),
			want: map[string]any{
				"payload": `{"nested": {"key": "value"}}`,
			},
		},
		{
			name:   "string with escaped quotes and braces",
			buffer: []byte(`{"name": "analyze", "arguments": {"text": "The JSON is: {\"key\": \"val{ue}\"}"}}`),
			want: map[string]any{
				"text": `The JSON is: {"key": "val{ue}"}`,
			},
		},
		{
			name:   "multiple objects with string containing braces",
			buffer: []byte(`{"name": "test", "arguments": {"query": "find } in text"}} {"name": "other"}`),
			want: map[string]any{
				"query": "find } in text",
			},
		},
		{
			name:   "unmatched closing brace in string",
			buffer: []byte(`{"name": "search", "arguments": {"pattern": "regex: }"}}`),
			want: map[string]any{
				"pattern": "regex: }",
			},
		},
		{
			name:   "complex nested with mixed braces",
			buffer: []byte(`{"name": "analyze", "arguments": {"data": "{\"items\": [{\"value\": \"}\"}, {\"code\": \"if (x) { return y; }\"}]}"}}`),
			want: map[string]any{
				"data": `{"items": [{"value": "}"}, {"code": "if (x) { return y; }"}]}`,
			},
		},
		{
			name:   "string with newline and braces",
			buffer: []byte(`{"name": "format", "arguments": {"template": "{\n  \"key\": \"value\"\n}"}}`),
			want: map[string]any{
				"template": "{\n  \"key\": \"value\"\n}",
			},
		},
		{
			name:   "string with unicode escape",
			buffer: []byte(`{"name": "test", "arguments": {"text": "Unicode: \u007B and \u007D"}}`),
			want: map[string]any{
				"text": "Unicode: { and }",
			},
		},
		{
			name:   "array arguments",
			buffer: []byte(`{"name": "batch", "arguments": ["item1", "item2", "{\"nested\": true}"]}`),
			want:   nil, // This should return nil because arguments is not a map
		},
		{
			name:   "escaped backslash before quote",
			buffer: []byte(`{"name": "path", "arguments": {"dir": "C:\\Program Files\\{App}\\"}}`),
			want: map[string]any{
				"dir": `C:\Program Files\{App}\`,
			},
		},
		{
			name:   "single quotes not treated as string delimiters",
			buffer: []byte(`{"name": "query", "arguments": {"sql": "SELECT * FROM users WHERE name = '{admin}'"}}`),
			want: map[string]any{
				"sql": "SELECT * FROM users WHERE name = '{admin}'",
			},
		},
		{
			name:   "incomplete json at buffer end",
			buffer: []byte(`{"name": "test", "arguments": {"data": "some {"`),
			want:   nil,
		},
		{
			name:   "multiple escaped quotes",
			buffer: []byte(`{"name": "echo", "arguments": {"msg": "He said \"Hello {World}\" loudly"}}`),
			want: map[string]any{
				"msg": `He said "Hello {World}" loudly`,
			},
		},
		{
			name:   "json with comments style string",
			buffer: []byte(`{"name": "code", "arguments": {"snippet": "// This is a comment with { and }"}}`),
			want: map[string]any{
				"snippet": "// This is a comment with { and }",
			},
		},
		{
			name:   "consecutive escaped backslashes",
			buffer: []byte(`{"name": "test", "arguments": {"path": "C:\\\\{folder}\\\\"}}`),
			want: map[string]any{
				"path": `C:\\{folder}\\`,
			},
		},
		{
			name:   "empty string with braces after",
			buffer: []byte(`{"name": "test", "arguments": {"a": "", "b": "{value}"}}`),
			want: map[string]any{
				"a": "",
				"b": "{value}",
			},
		},
		{
			name:   "unicode in key names",
			buffer: []byte(`{"name": "test", "arguments": {"key{": "value", "key}": "value2"}}`),
			want: map[string]any{
				"key{": "value",
				"key}": "value2",
			},
		},
		{
			name:   "very long string with braces",
			buffer: []byte(`{"name": "test", "arguments": {"data": "` + strings.Repeat("a{b}c", 100) + `"}}`),
			want: map[string]any{
				"data": strings.Repeat("a{b}c", 100),
			},
		},
		{
			name:   "tab characters and braces",
			buffer: []byte(`{"name": "test", "arguments": {"code": "\tif (true) {\n\t\treturn;\n\t}"}}`),
			want: map[string]any{
				"code": "\tif (true) {\n\t\treturn;\n\t}",
			},
		},
		{
			name:   "null byte in string",
			buffer: []byte(`{"name": "test", "arguments": {"data": "before\u0000{after}"}}`),
			want: map[string]any{
				"data": "before\x00{after}",
			},
		},
		{
			name:   "escaped quote at end of string",
			buffer: []byte(`{"name": "test", "arguments": {"data": "text with quote at end\\\""}}`),
			want: map[string]any{
				"data": `text with quote at end\"`,
			},
		},
		{
			name:   "mixed array and object in arguments",
			buffer: []byte(`{"name": "test", "arguments": {"items": ["{", "}", {"key": "value"}]}}`),
			want: map[string]any{
				"items": []any{"{", "}", map[string]any{"key": "value"}},
			},
		},
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
		{
			name:   "stringified arguments",
			buffer: []byte(`{"name": "get_temperature", "arguments": "{\"format\": \"fahrenheit\", \"location\": \"San Francisco, CA\"}"}`),
			want: map[string]any{
				"format":   "fahrenheit",
				"location": "San Francisco, CA",
			},
		},
		{
			name:   "stringified parameters",
			buffer: []byte(`{"name": "get_temperature", "parameters": "{\"format\": \"fahrenheit\", \"location\": \"San Francisco, CA\"}"}`),
			want: map[string]any{
				"format":   "fahrenheit",
				"location": "San Francisco, CA",
			},
		},
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
		{
			name:   "simple tool call",
			tool:   "get_temperature",
			buffer: []byte(`{"get_temperature": {"format": "fahrenheit", "location": "San Francisco, CA"}}`),
			want: map[string]any{
				"format":   "fahrenheit",
				"location": "San Francisco, CA",
			},
		},
		{
			name:   "stringified simple tool call",
			tool:   "get_temperature",
			buffer: []byte(`{"get_temperature": "{\"format\": \"fahrenheit\", \"location\": \"San Francisco, CA\"}"}`),
			want: map[string]any{
				"format":   "fahrenheit",
				"location": "San Francisco, CA",
			},
		},
1335
1336
	}

1337
	for _, tt := range tests {
1338
		t.Run(tt.name, func(t *testing.T) {
1339
			got, _ := findArguments(&api.Tool{Function: api.ToolFunction{Name: tt.tool}}, tt.buffer)
1340

1341
			if diff := cmp.Diff(got, tt.want); diff != "" {
1342
				t.Errorf("findArguments() args mismatch (-got +want):\n%s", diff)
1343
			}
1344
1345
1346
		})
	}
}