tools_test.go 24.9 KB
Newer Older
1
2
3
4
package tools

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

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

11
12
13
14
15
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)
	}
16

17
	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}}")
18
	if err != nil {
19
		t.Fatalf("Failed to parse template: %v", err)
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
	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",
				Parameters: struct {
					Type       string   `json:"type"`
					Defs       any      `json:"$defs,omitempty"`
					Items      any      `json:"items,omitempty"`
					Required   []string `json:"required"`
					Properties map[string]struct {
						Type        api.PropertyType `json:"type"`
						Items       any              `json:"items,omitempty"`
						Description string           `json:"description"`
						Enum        []any            `json:"enum,omitempty"`
					} `json:"properties"`
				}{
					Type: "object",
					Properties: map[string]struct {
						Type        api.PropertyType `json:"type"`
						Items       any              `json:"items,omitempty"`
						Description string           `json:"description"`
						Enum        []any            `json:"enum,omitempty"`
					}{
						"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",
						},
					},
				},
			},
		},
		{
			Type: "function",
			Function: api.ToolFunction{
				Name:        "get_conditions",
				Description: "Retrieve the current weather conditions for a given location",
				Parameters: struct {
					Type       string   `json:"type"`
					Defs       any      `json:"$defs,omitempty"`
					Items      any      `json:"items,omitempty"`
					Required   []string `json:"required"`
					Properties map[string]struct {
						Type        api.PropertyType `json:"type"`
						Items       any              `json:"items,omitempty"`
						Description string           `json:"description"`
						Enum        []any            `json:"enum,omitempty"`
					} `json:"properties"`
				}{
					Type: "object",
					Properties: map[string]struct {
						Type        api.PropertyType `json:"type"`
						Items       any              `json:"items,omitempty"`
						Description string           `json:"description"`
						Enum        []any            `json:"enum,omitempty"`
					}{
						"location": {
							Type:        api.PropertyType{"string"},
							Description: "The location to get the weather conditions for",
						},
					},
				},
			},
		},
107
108
109
110
111
112
113
		{
			Type: "function",
			Function: api.ToolFunction{
				Name:        "say_hello",
				Description: "Say hello",
			},
		},
114
	}
115
116

	tests := []struct {
117
118
119
120
121
		name    string
		inputs  []string
		tmpl    *template.Template
		content string
		calls   []api.ToolCall
122
123
	}{
		{
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
			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{
143
144
				{
					Function: api.ToolCallFunction{
145
146
147
148
						Index: 0,
						Name:  "get_conditions",
						Arguments: api.ToolCallFunctionArguments{
							"location": "San Francisco",
149
150
151
152
						},
					},
				},
			},
153
		},
154
155
156
157
158
159
160
161
162
163
164
165
166
167
		{
			name:    "invalid arguments",
			inputs:  []string{`<tool_call>{"name": "get_conditions", "arguments": {"city": "San Francisco"}}</tool_call>`},
			content: "",
			tmpl:    qwen,
			calls:   nil,
		},
		{
			name:    "missing args",
			inputs:  []string{`<tool_call>{"name": "get_conditions"}</tool_call>`},
			content: "",
			tmpl:    qwen,
			calls:   nil,
		},
168
169
170
171
172
173
		{
			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{
174
175
				{
					Function: api.ToolCallFunction{
176
177
178
179
180
181
182
183
184
						Index: 0,
						Name:  "get_temperature",
						Arguments: api.ToolCallFunctionArguments{
							"city": "New York",
						},
					},
				},
			},
		},
185
186
187
188
189
190
191
192
		{
			name:    "qwen no args tool call",
			inputs:  []string{`Let me say hello to the user. I'll use the say_hello tool <tool_call>{"name": "say_hello"}</tool_call>`},
			content: "Let me say hello to the user. I'll use the say_hello tool ",
			tmpl:    qwen,
			calls: []api.ToolCall{
				{
					Function: api.ToolCallFunction{
193
194
195
						Index:     0,
						Name:      "say_hello",
						Arguments: api.ToolCallFunctionArguments{},
196
197
198
199
200
201
202
203
204
205
206
					},
				},
			},
		},
		{
			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,
		},
207
208
209
210
211
212
213
214
215
216
217
218
219
		{
			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",
						Arguments: api.ToolCallFunctionArguments{
							"city":   "London",
							"format": "fahrenheit",
220
221
222
223
224
						},
					},
				},
				{
					Function: api.ToolCallFunction{
225
226
227
228
						Index: 1,
						Name:  "get_conditions",
						Arguments: api.ToolCallFunctionArguments{
							"location": "Tokyo",
229
230
231
232
						},
					},
				},
			},
233
234
		},
		{
235
			name:    "qwen two tool calls",
236
237
238
239
			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{
240
241
				{
					Function: api.ToolCallFunction{
242
243
244
245
246
						Index: 0,
						Name:  "get_temperature",
						Arguments: api.ToolCallFunctionArguments{
							"city":   "London",
							"format": "fahrenheit",
247
248
249
250
251
						},
					},
				},
				{
					Function: api.ToolCallFunction{
252
253
254
255
						Index: 1,
						Name:  "get_conditions",
						Arguments: api.ToolCallFunctionArguments{
							"location": "Tokyo",
256
257
258
259
						},
					},
				},
			},
260
		},
261
262
263
264
265
266
267
268
		{
			name:    "qwen two tool calls one with no args",
			inputs:  []string{`Let me check the weather. <tool_call>{"name": "say_hello"}</tool_call><tool_call>{"name": "get_conditions", "arguments": {"location": "Tokyo"}}`},
			content: "Let me check the weather. ",
			tmpl:    qwen,
			calls: []api.ToolCall{
				{
					Function: api.ToolCallFunction{
269
270
271
						Index:     0,
						Name:      "say_hello",
						Arguments: api.ToolCallFunctionArguments{},
272
273
274
275
276
277
278
279
280
281
282
283
284
					},
				},
				{
					Function: api.ToolCallFunction{
						Index: 1,
						Name:  "get_conditions",
						Arguments: api.ToolCallFunctionArguments{
							"location": "Tokyo",
						},
					},
				},
			},
		},
285
286
287
288
289
290
		{
			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{
291
292
				{
					Function: api.ToolCallFunction{
293
294
295
296
						Index: 0,
						Name:  "get_temperature",
						Arguments: api.ToolCallFunctionArguments{
							"city": "Tokyo",
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
			},
		},
		{
			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{
322
323
				{
					Function: api.ToolCallFunction{
324
325
326
327
						Index: 0,
						Name:  "get_temperature",
						Arguments: api.ToolCallFunctionArguments{
							"city": "Tokyo",
328
329
330
331
332
333
						},
					},
				},
			},
		},
		{
334
335
336
337
338
339
340
341
342
343
344
345
			name: "json",
			inputs: []string{
				"{",
				"\"name\": \"get_temperature\",",
				"\"arguments\": {",
				"\"city\": \"Tokyo\"",
				"}",
				"}",
			},
			content: "",
			tmpl:    json,
			calls: []api.ToolCall{
346
347
				{
					Function: api.ToolCallFunction{
348
349
350
351
						Index: 0,
						Name:  "get_temperature",
						Arguments: api.ToolCallFunctionArguments{
							"city": "Tokyo",
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
		},
		{
			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,
		},
408
409
410
411
412
413
414
415
416
417
		{
			name: "json no args tool call",
			inputs: []string{
				"{\"name\": \"say_hello\"}",
			},
			content: "",
			tmpl:    json,
			calls: []api.ToolCall{
				{
					Function: api.ToolCallFunction{
418
419
420
						Index:     0,
						Name:      "say_hello",
						Arguments: api.ToolCallFunctionArguments{},
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
					},
				},
			},
		},
		{
			name: "json no args no tool call",
			inputs: []string{
				"I'll use the say_hello tool to say hello to the user.",
			},
			content: "I'll use the say_hello tool to say hello to the user.",
			tmpl:    json,
			calls:   nil,
		},

		// TODO (jmorganca): this is a false positive, we should
		// not be parsing this as a tool call
		{
			name: "json no args false positive",
			inputs: []string{
				`{say_hello!!!}`,
			},
			content: "",
			tmpl:    json,
			calls: []api.ToolCall{
				{
					Function: api.ToolCallFunction{
447
448
449
						Index:     0,
						Name:      "say_hello",
						Arguments: api.ToolCallFunctionArguments{},
450
451
452
453
					},
				},
			},
		},
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
		{
			name: "list multiple",
			inputs: []string{
				"[",
				"{",
				"\"name\": \"get_temperature\", ",
				"\"arguments\": {",
				"\"city\": \"London\"",
				"}",
				"},",
				"{",
				"\"name\": \"get_conditions\", ",
				"\"arguments\": {",
				"\"location\": \"Tokyo\"",
				"}",
				"}]",
			},
			content: "",
			tmpl:    list,
			calls: []api.ToolCall{
474
475
				{
					Function: api.ToolCallFunction{
476
477
478
479
						Index: 0,
						Name:  "get_temperature",
						Arguments: api.ToolCallFunctionArguments{
							"city": "London",
480
481
482
						},
					},
				},
483
484
485
486
487
488
489
490
491
492
493
494
495
				{
					Function: api.ToolCallFunction{
						Index: 1,
						Name:  "get_conditions",
						Arguments: api.ToolCallFunctionArguments{
							"location": "Tokyo",
						},
					},
				},
			},
		},
		{
			name: "list partial",
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
			inputs: []string{
				"[{",
				"\"name\": \"get_conditions\", ",
				"\"arguments\": {",
				"\"location\": \"Tokyo\"",
				"}",
				"}",
			},
			content: "",
			tmpl:    list,
			calls: []api.ToolCall{
				{
					Function: api.ToolCallFunction{
						Index: 0,
						Name:  "get_conditions",
						Arguments: api.ToolCallFunctionArguments{
							"location": "Tokyo",
						},
					},
				},
			},
		},
		{
			name: "list invalid",
520
521
522
523
524
525
526
527
528
529
530
531
532
			inputs: []string{
				"[",
				"{",
				"\"name\": \"search\", ",
				"\"arguments\": {",
				"\"query\": \"What is the capital of Canada?\"",
				"}",
				"}",
			},
			content: "",
			tmpl:    list,
			calls:   nil,
		},
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
		{
			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",
						Arguments: api.ToolCallFunctionArguments{
							"location": "Tokyo",
						},
					},
				},
			},
		},
560
561
562
563
564
565
		{
			name: "list not a tool call",
			inputs: []string{
				"[special",
				" del",
				"ivery]",
566
			},
567
568
569
			content: "[special delivery]",
			tmpl:    list,
			calls:   nil,
570
		},
571
572
573
574
575
576
577
578
579
580
581
582
583
		{
			name: "list with no arguments",
			inputs: []string{
				"[",
				"{",
				"\"name\": \"say_hello\"",
				"}",
			},
			content: "",
			tmpl:    list,
			calls: []api.ToolCall{
				{
					Function: api.ToolCallFunction{
584
585
586
						Index:     0,
						Name:      "say_hello",
						Arguments: api.ToolCallFunctionArguments{},
587
588
589
590
					},
				},
			},
		},
591
592
593
594
	}

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

597
598
599
600
601
602
			var calls []api.ToolCall
			var content string
			for _, input := range tt.inputs {
				tcs, c := parser.Add(input)
				calls = append(calls, tcs...)
				content += c
603
604
			}

605
606
			if content != tt.content {
				t.Errorf("Expected content %q, got %q", tt.content, content)
607
608
			}

609
610
611
612
613
614
615
616
			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 {
				if diff := cmp.Diff(calls[i], want); diff != "" {
					t.Errorf("Tool call %d mismatch (-got +want):\n%s", i, diff)
				}
617
618
619
620
621
			}
		})
	}
}

622
623
624
625
626
627
func TestDone(t *testing.T) {
	tests := []struct {
		name   string
		tag    string
		buffer []byte
		want   bool
628
629
	}{
		{
630
631
632
633
			name:   "empty",
			tag:    "<tool_call>",
			buffer: []byte{},
			want:   false,
634
635
		},
		{
636
637
638
639
			name:   "empty",
			tag:    "<tool_call>",
			buffer: []byte{},
			want:   false,
640
641
		},
		{
642
643
644
645
			name:   "json open",
			tag:    "{",
			buffer: []byte("{\"name\": \"get_weather\""),
			want:   false,
646
647
		},
		{
648
649
650
651
			name:   "json closed",
			tag:    "{",
			buffer: []byte("{\"name\": \"get_weather\"}"),
			want:   true,
652
653
		},
		{
654
655
656
657
			name:   "json empty",
			tag:    "{",
			buffer: []byte("{}"),
			want:   true,
658
659
		},
		{
660
661
662
663
			name:   "list open",
			tag:    "[",
			buffer: []byte("[{\"name\": \"get_weather\""),
			want:   false,
664
665
		},
		{
666
667
668
669
			name:   "list closed",
			tag:    "[",
			buffer: []byte("[{\"name\": \"get_weather\"}]"),
			want:   true,
670
671
		},
		{
672
673
674
675
			name:   "list empty",
			tag:    "[",
			buffer: []byte("[]"),
			want:   true,
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
	}

	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
	}{
701
		{
702
703
704
705
706
			name:    "empty",
			content: []byte{},
			tag:     "{",
			want:    "",
			n:       0,
707
708
		},
		{
709
710
711
712
713
			name:    "tag",
			tag:     "<tool_call>",
			content: []byte("<tool_call>{\"name\": \"get_temperature\""),
			want:    "",
			n:       0,
714
715
		},
		{
716
717
718
719
720
			name:    "json object",
			tag:     "{",
			content: []byte("{\"name\": \"get_temperature\"}"),
			want:    "{\"name\": \"get_temperature\"}",
			n:       0,
721
722
		},
		{
723
724
725
726
727
			name:    "json object after called",
			tag:     "{",
			content: []byte("{\"hello\": \"world\"}"),
			want:    "{\"hello\": \"world\"}",
			n:       0,
728
729
		},
		{
730
731
732
733
734
			name:    "json object after called",
			tag:     "{",
			content: []byte("{\"hello\": \"world\"}"),
			want:    "",
			n:       1,
735
736
		},
		{
737
738
739
740
741
			name:    "list",
			tag:     "[",
			content: []byte("[{\"name\": \"get_temperature\"}]"),
			want:    "[{\"name\": \"get_temperature\"}]",
			n:       0,
742
743
		},
		{
744
745
746
747
748
			name:    "code",
			tag:     "{",
			content: []byte("{ fmt.Println(\"hello\")"),
			want:    "{ fmt.Println(\"hello\")",
			n:       0,
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
	}

	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
	}{
775
		{
776
777
778
779
780
			name:   "no overlap",
			buffer: []byte("hello world"),
			tag:    "<tool_call>",
			i:      -1,
			found:  false,
781
782
		},
		{
783
784
785
786
787
			name:   "full overlap",
			buffer: []byte("<tool_call>"),
			tag:    "<tool_call>",
			i:      0,
			found:  true,
788
789
		},
		{
790
791
792
793
794
			name:   "whitespace",
			buffer: []byte("    <tool_call>\n {\"name\": \"bob\"}"),
			tag:    "<tool_call>",
			i:      4,
			found:  true,
795
796
		},
		{
797
798
799
800
801
			name:   "over",
			buffer: []byte("<tool_call>{\"name\""),
			tag:    "<tool_call>",
			i:      0,
			found:  true,
802
803
		},
		{
804
805
806
807
808
			name:   "partial overlap",
			buffer: []byte("text <tool_call>"),
			tag:    "<tool_call>",
			i:      5,
			found:  true,
809
810
		},
		{
811
812
813
814
815
			name:   "overlap with extra",
			buffer: []byte("<tool_calls><tool_call>"),
			tag:    "<tool_calls>",
			i:      0,
			found:  true,
816
817
		},
		{
818
819
820
821
822
			name:   "delimiter longer than string",
			buffer: []byte("<tool>"),
			tag:    "<tool_call>",
			i:      -1,
			found:  false,
823
824
		},
		{
825
826
827
828
829
			name:   "empty string",
			buffer: []byte{},
			tag:    "<tool_call>",
			i:      -1,
			found:  false,
830
831
		},
		{
832
833
834
835
836
			name:   "single char overlap",
			buffer: []byte("test<"),
			tag:    "<tool_call>",
			i:      4,
			found:  false,
837
838
		},
		{
839
840
841
842
843
			name:   "partial tool call",
			buffer: []byte("hello <tool_"),
			tag:    "<tool_call>",
			i:      6,
			found:  false,
844
845
		},
		{
846
847
848
849
850
			name:   "square bracket",
			buffer: []byte("calling tools: ["),
			tag:    "[",
			i:      15,
			found:  true,
851
852
		},
		{
853
854
855
856
857
			name:   "bracket",
			buffer: []byte("{\"name\": \"bob\""),
			tag:    "{",
			i:      0,
			found:  true,
858
859
		},
		{
860
861
862
863
864
			name:   "bracket with whitespace",
			buffer: []byte("\n\n{\n\"name\": \"bob\""),
			tag:    "{",
			i:      2,
			found:  true,
865
		},
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
	}

	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) {
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
	tool := api.Tool{
		Type: "function",
		Function: api.ToolFunction{
			Name:        "get_temperature",
			Description: "Retrieve the temperature for a given location",
			Parameters: struct {
				Type       string   `json:"type"`
				Defs       any      `json:"$defs,omitempty"`
				Items      any      `json:"items,omitempty"`
				Required   []string `json:"required"`
				Properties map[string]struct {
					Type        api.PropertyType `json:"type"`
					Items       any              `json:"items,omitempty"`
					Description string           `json:"description"`
					Enum        []any            `json:"enum,omitempty"`
				} `json:"properties"`
			}{
				Type: "object",
				Properties: map[string]struct {
					Type        api.PropertyType `json:"type"`
					Items       any              `json:"items,omitempty"`
					Description string           `json:"description"`
					Enum        []any            `json:"enum,omitempty"`
				}{
					"format": {
						Type:        api.PropertyType{"string"},
						Description: "The format to return the temperature in",
						Enum:        []any{"fahrenheit", "celsius"},
					},
					"location": {
						Type:        api.PropertyType{"string"},
						Description: "The location to get the temperature for",
					},
				},
			},
		},
	}

	tool2 := api.Tool{
		Type: "function",
		Function: api.ToolFunction{
			Name:        "say_hello",
			Description: "Say hello to the user",
		},
	}

933
934
935
936
	tests := []struct {
		name   string
		buffer []byte
		want   map[string]any
937
		tool   api.Tool
938
	}{
939
		{
940
941
942
			name:   "empty string",
			buffer: []byte{},
			want:   nil,
943
			tool:   tool,
944
945
		},
		{
946
947
948
			name:   "whitespace only",
			buffer: []byte("   \n\t  "),
			want:   nil,
949
			tool:   tool,
950
951
		},
		{
952
953
954
			name:   "unbalanced braces - missing closing",
			buffer: []byte(`{"format": "fahrenheit", "location": "San Francisco"`),
			want:   nil,
955
			tool:   tool,
956
957
		},
		{
958
959
960
961
962
			name:   "unbalanced braces - extra closing",
			buffer: []byte(`{"format": "fahrenheit"}}`),
			want: map[string]any{
				"format": "fahrenheit",
			},
963
			tool: tool,
964
965
		},
		{
966
967
968
			name:   "invalid JSON",
			buffer: []byte(`{format: fahrenheit, location: "San Francisco"}`),
			want:   nil,
969
			tool:   tool,
970
971
		},
		{
972
973
974
975
976
977
			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",
			},
978
			tool: tool,
979
980
		},
		{
981
982
983
984
985
986
			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",
			},
987
			tool: tool,
988
989
		},
		{
990
991
992
993
994
995
			name:   "valid arguments in array",
			buffer: []byte(`[{"arguments": {"format": "fahrenheit", "location": "San Francisco, CA"}}`),
			want: map[string]any{
				"format":   "fahrenheit",
				"location": "San Francisco, CA",
			},
996
			tool: tool,
997
998
		},
		{
999
1000
1001
1002
1003
1004
			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",
			},
1005
			tool: tool,
1006
1007
		},
		{
1008
			name:   "one arg",
1009
			buffer: []byte(`get_temperature({"location": "San Francisco, CA"})`),
1010
1011
1012
			want: map[string]any{
				"location": "San Francisco, CA",
			},
1013
			tool: tool,
1014
1015
		},
		{
1016
			name:   "two args",
1017
			buffer: []byte(`[{"name": "get_temperature", "arguments": {"location": "San Francisco, CA", "format": "fahrenheit"}}, {"name": "get_weather", "arguments": {"location": "San Francisco, CA", "format": "fahrenheit"}}]`),
1018
1019
1020
1021
			want: map[string]any{
				"location": "San Francisco, CA",
				"format":   "fahrenheit",
			},
1022
1023
1024
1025
1026
1027
1028
			tool: tool,
		},
		{
			name:   "no args",
			buffer: []byte(`{"name": "say_hello"}`),
			want:   nil,
			tool:   tool2,
1029
1030
		},
		{
1031
			name:   "deepseek",
1032
			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|>"),
1033
1034
1035
			want: map[string]any{
				"location": "Tokyo",
			},
1036
			tool: tool,
1037
1038
1039
		},
	}

1040
1041
	for _, tt := range tests {
		parser := &Parser{
1042
1043
			buffer: tt.buffer,
			tools:  []api.Tool{tool, tool2},
1044
		}
1045
1046

		t.Run(tt.name, func(t *testing.T) {
1047
			got, _ := parser.findArguments(tool)
1048

1049
1050
1051
			if diff := cmp.Diff(got, tt.want); diff != "" {
				t.Errorf("scanArguments() args mismatch (-got +want):\n%s", diff)
			}
1052
1053
1054
		})
	}
}