template_test.go 20.4 KB
Newer Older
Michael Yang's avatar
Michael Yang committed
1
2
3
4
5
6
7
8
9
10
package template

import (
	"bufio"
	"bytes"
	"encoding/json"
	"io"
	"os"
	"path/filepath"
	"slices"
Michael Yang's avatar
Michael Yang committed
11
	"strings"
Michael Yang's avatar
Michael Yang committed
12
	"testing"
13
	"time"
Michael Yang's avatar
Michael Yang committed
14

Michael Yang's avatar
Michael Yang committed
15
	"github.com/google/go-cmp/cmp"
Michael Yang's avatar
lint  
Michael Yang committed
16

Michael Yang's avatar
Michael Yang committed
17
	"github.com/ollama/ollama/api"
Michael Yang's avatar
Michael Yang committed
18
	"github.com/ollama/ollama/fs/ggml"
Michael Yang's avatar
Michael Yang committed
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
)

func TestNamed(t *testing.T) {
	f, err := os.Open(filepath.Join("testdata", "templates.jsonl"))
	if err != nil {
		t.Fatal(err)
	}
	defer f.Close()

	scanner := bufio.NewScanner(f)
	for scanner.Scan() {
		var ss map[string]string
		if err := json.Unmarshal(scanner.Bytes(), &ss); err != nil {
			t.Fatal(err)
		}

		for k, v := range ss {
			t.Run(k, func(t *testing.T) {
Michael Yang's avatar
Michael Yang committed
37
				kv := ggml.KV{"tokenizer.chat_template": v}
Michael Yang's avatar
Michael Yang committed
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
				s := kv.ChatTemplate()
				r, err := Named(s)
				if err != nil {
					t.Fatal(err)
				}

				if r.Name != k {
					t.Errorf("expected %q, got %q", k, r.Name)
				}

				var b bytes.Buffer
				if _, err := io.Copy(&b, r.Reader()); err != nil {
					t.Fatal(err)
				}

Michael Yang's avatar
Michael Yang committed
53
				tmpl, err := Parse(b.String())
Michael Yang's avatar
Michael Yang committed
54
55
56
57
58
59
60
61
62
63
64
65
				if err != nil {
					t.Fatal(err)
				}

				if tmpl.Tree.Root.String() == "" {
					t.Errorf("empty %s template", k)
				}
			})
		}
	}
}

Michael Yang's avatar
Michael Yang committed
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
func TestTemplate(t *testing.T) {
	cases := make(map[string][]api.Message)
	for _, mm := range [][]api.Message{
		{
			{Role: "user", Content: "Hello, how are you?"},
		},
		{
			{Role: "user", Content: "Hello, how are you?"},
			{Role: "assistant", Content: "I'm doing great. How can I help you today?"},
			{Role: "user", Content: "I'd like to show off how chat templating works!"},
		},
		{
			{Role: "system", Content: "You are a helpful assistant."},
			{Role: "user", Content: "Hello, how are you?"},
			{Role: "assistant", Content: "I'm doing great. How can I help you today?"},
			{Role: "user", Content: "I'd like to show off how chat templating works!"},
		},
	} {
		var roles []string
		for _, m := range mm {
			roles = append(roles, m.Role)
		}

		cases[strings.Join(roles, "-")] = mm
	}

	matches, err := filepath.Glob("*.gotmpl")
	if err != nil {
		t.Fatal(err)
	}

	for _, match := range matches {
		t.Run(match, func(t *testing.T) {
			bts, err := os.ReadFile(match)
			if err != nil {
				t.Fatal(err)
			}

			tmpl, err := Parse(string(bts))
			if err != nil {
				t.Fatal(err)
			}

			for n, tt := range cases {
110
				var actual bytes.Buffer
Michael Yang's avatar
Michael Yang committed
111
112
113
114
115
116
117
118
119
120
				t.Run(n, func(t *testing.T) {
					if err := tmpl.Execute(&actual, Values{Messages: tt}); err != nil {
						t.Fatal(err)
					}

					expect, err := os.ReadFile(filepath.Join("testdata", match, n))
					if err != nil {
						t.Fatal(err)
					}

121
122
123
124
125
126
127
128
					bts := actual.Bytes()

					if slices.Contains([]string{"chatqa.gotmpl", "llama2-chat.gotmpl", "mistral-instruct.gotmpl", "openchat.gotmpl", "vicuna.gotmpl"}, match) && bts[len(bts)-1] == ' ' {
						t.Log("removing trailing space from output")
						bts = bts[:len(bts)-1]
					}

					if diff := cmp.Diff(bts, expect); diff != "" {
Michael Yang's avatar
Michael Yang committed
129
130
131
						t.Errorf("mismatch (-got +want):\n%s", diff)
					}
				})
132
133

				t.Run("legacy", func(t *testing.T) {
134
					t.Skip("legacy outputs are currently default outputs")
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
					var legacy bytes.Buffer
					if err := tmpl.Execute(&legacy, Values{Messages: tt, forceLegacy: true}); err != nil {
						t.Fatal(err)
					}

					legacyBytes := legacy.Bytes()
					if slices.Contains([]string{"chatqa.gotmpl", "openchat.gotmpl", "vicuna.gotmpl"}, match) && legacyBytes[len(legacyBytes)-1] == ' ' {
						t.Log("removing trailing space from legacy output")
						legacyBytes = legacyBytes[:len(legacyBytes)-1]
					} else if slices.Contains([]string{"codellama-70b-instruct.gotmpl", "llama2-chat.gotmpl", "mistral-instruct.gotmpl"}, match) {
						t.Skip("legacy outputs cannot be compared to messages outputs")
					}

					if diff := cmp.Diff(legacyBytes, actual.Bytes()); diff != "" {
						t.Errorf("mismatch (-got +want):\n%s", diff)
					}
				})
Michael Yang's avatar
Michael Yang committed
152
153
154
155
156
			}
		})
	}
}

Michael Yang's avatar
Michael Yang committed
157
func TestParse(t *testing.T) {
158
159
	validCases := []struct {
		name     string
Michael Yang's avatar
Michael Yang committed
160
161
		template string
		vars     []string
Michael Yang's avatar
Michael Yang committed
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
		{
			name:     "PromptOnly",
			template: "{{ .Prompt }}",
			vars:     []string{"prompt", "response"},
		},
		{
			name:     "SystemAndPrompt",
			template: "{{ .System }} {{ .Prompt }}",
			vars:     []string{"prompt", "response", "system"},
		},
		{
			name:     "PromptResponseSystem",
			template: "{{ .System }} {{ .Prompt }} {{ .Response }}",
			vars:     []string{"prompt", "response", "system"},
		},
		{
			name:     "ToolsBlock",
			template: "{{ with .Tools }}{{ . }}{{ end }} {{ .System }} {{ .Prompt }}",
			vars:     []string{"prompt", "response", "system", "tools"},
		},
		{
			name:     "MessagesRange",
			template: "{{ range .Messages }}{{ .Role }} {{ .Content }}{{ end }}",
			vars:     []string{"content", "messages", "role"},
		},
		{
			name:     "ToolResultConditional",
			template: "{{ range .Messages }}{{ if eq .Role \"tool\" }}Tool Result: {{ .ToolName }} {{ .Content }}{{ end }}{{ end }}",
			vars:     []string{"content", "messages", "role", "toolname"},
		},
		{
			name: "MultilineSystemUserAssistant",
			template: `{{- range .Messages }}
196
197
198
{{- if eq .Role "system" }}SYSTEM:
{{- else if eq .Role "user" }}USER:
{{- else if eq .Role "assistant" }}ASSISTANT:
199
{{- else if eq .Role "tool" }}TOOL:
200
{{- end }} {{ .Content }}
201
202
203
204
205
206
{{- end }}`,
			vars: []string{"content", "messages", "role"},
		},
		{
			name: "ChatMLLike",
			template: `{{- if .Messages }}
207
208
209
210
211
212
213
214
215
216
{{- range .Messages }}<|im_start|>{{ .Role }}
{{ .Content }}<|im_end|>
{{ end }}<|im_start|>assistant
{{ else -}}
{{ if .System }}<|im_start|>system
{{ .System }}<|im_end|>
{{ end }}{{ if .Prompt }}<|im_start|>user
{{ .Prompt }}<|im_end|>
{{ end }}<|im_start|>assistant
{{ .Response }}<|im_end|>
217
218
219
{{- end -}}`,
			vars: []string{"content", "messages", "prompt", "response", "role", "system"},
		},
Michael Yang's avatar
Michael Yang committed
220
221
	}

222
223
224
225
	for _, tt := range validCases {
		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()

Michael Yang's avatar
Michael Yang committed
226
227
			tmpl, err := Parse(tt.template)
			if err != nil {
228
				t.Fatalf("Parse returned unexpected error: %v", err)
Michael Yang's avatar
Michael Yang committed
229
230
			}

231
			gotVars, err := tmpl.Vars()
232
			if err != nil {
233
				t.Fatalf("Vars returned unexpected error: %v", err)
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

			if diff := cmp.Diff(gotVars, tt.vars); diff != "" {
				t.Errorf("Vars mismatch (-got +want):\n%s", diff)
			}
		})
	}
}

func TestParseError(t *testing.T) {
	invalidCases := []struct {
		name     string
		template string
		errorStr string
	}{
		{
			"TemplateNotClosed",
			"{{ .Prompt ",
			"unclosed action",
		},
		{
			"Template",
			`{{define "x"}}{{template "x"}}{{end}}{{template "x"}}`,
			"undefined template specified",
		},
	}

	for _, tt := range invalidCases {
		t.Run(tt.name, func(t *testing.T) {
			_, err := Parse(tt.template)
			if err == nil {
				t.Fatalf("expected Parse to return an error for an invalid template, got nil")
			}

			if !strings.Contains(strings.ToLower(err.Error()), strings.ToLower(tt.errorStr)) {
				t.Errorf("unexpected error message.\n got: %q\n want substring (case‑insensitive): %q", err.Error(), tt.errorStr)
Michael Yang's avatar
Michael Yang committed
270
271
272
273
			}
		})
	}
}
Michael Yang's avatar
Michael Yang committed
274
275

func TestExecuteWithMessages(t *testing.T) {
Michael Yang's avatar
Michael Yang committed
276
277
278
279
	type template struct {
		name     string
		template string
	}
Michael Yang's avatar
Michael Yang committed
280
	cases := []struct {
Michael Yang's avatar
Michael Yang committed
281
282
		name      string
		templates []template
Michael Yang's avatar
Michael Yang committed
283
284
285
286
		values    Values
		expected  string
	}{
		{
Michael Yang's avatar
Michael Yang committed
287
288
			"mistral",
			[]template{
289
290
291
292
293
294
				{"no response", `[INST] {{ if .System }}{{ .System }}

{{ end }}{{ .Prompt }}[/INST] `},
				{"response", `[INST] {{ if .System }}{{ .System }}

{{ end }}{{ .Prompt }}[/INST] {{ .Response }}`},
295
				{"messages", `[INST] {{ if .System }}{{ .System }}
296

297
298
299
{{ end }}
{{- range .Messages }}
{{- if eq .Role "user" }}{{ .Content }}[/INST] {{ else if eq .Role "assistant" }}{{ .Content }}[INST] {{ end }}
Michael Yang's avatar
Michael Yang committed
300
{{- end }}`},
Michael Yang's avatar
Michael Yang committed
301
302
303
304
305
			},
			Values{
				Messages: []api.Message{
					{Role: "user", Content: "Hello friend!"},
					{Role: "assistant", Content: "Hello human!"},
Michael Yang's avatar
Michael Yang committed
306
					{Role: "user", Content: "What is your name?"},
Michael Yang's avatar
Michael Yang committed
307
308
				},
			},
Michael Yang's avatar
Michael Yang committed
309
			`[INST] Hello friend![/INST] Hello human![INST] What is your name?[/INST] `,
Michael Yang's avatar
Michael Yang committed
310
311
		},
		{
Michael Yang's avatar
Michael Yang committed
312
313
			"mistral system",
			[]template{
314
315
316
317
318
319
				{"no response", `[INST] {{ if .System }}{{ .System }}

{{ end }}{{ .Prompt }}[/INST] `},
				{"response", `[INST] {{ if .System }}{{ .System }}

{{ end }}{{ .Prompt }}[/INST] {{ .Response }}`},
320
				{"messages", `[INST] {{ if .System }}{{ .System }}
321

322
323
324
{{ end }}
{{- range .Messages }}
{{- if eq .Role "user" }}{{ .Content }}[/INST] {{ else if eq .Role "assistant" }}{{ .Content }}[INST] {{ end }}
Michael Yang's avatar
Michael Yang committed
325
{{- end }}`},
Michael Yang's avatar
Michael Yang committed
326
327
328
329
330
331
			},
			Values{
				Messages: []api.Message{
					{Role: "system", Content: "You are a helpful assistant!"},
					{Role: "user", Content: "Hello friend!"},
					{Role: "assistant", Content: "Hello human!"},
Michael Yang's avatar
Michael Yang committed
332
					{Role: "user", Content: "What is your name?"},
Michael Yang's avatar
Michael Yang committed
333
334
				},
			},
335
			`[INST] You are a helpful assistant!
Michael Yang's avatar
Michael Yang committed
336

337
Hello friend![/INST] Hello human![INST] What is your name?[/INST] `,
Michael Yang's avatar
Michael Yang committed
338
		},
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
		{
			"mistral assistant",
			[]template{
				{"no response", `[INST] {{ .Prompt }}[/INST] `},
				{"response", `[INST] {{ .Prompt }}[/INST] {{ .Response }}`},
				{"messages", `
{{- range $i, $m := .Messages }}
{{- if eq .Role "user" }}[INST] {{ .Content }}[/INST] {{ else if eq .Role "assistant" }}{{ .Content }}{{ end }}
{{- end }}`},
			},
			Values{
				Messages: []api.Message{
					{Role: "user", Content: "Hello friend!"},
					{Role: "assistant", Content: "Hello human!"},
					{Role: "user", Content: "What is your name?"},
					{Role: "assistant", Content: "My name is Ollama and I"},
				},
			},
			`[INST] Hello friend![/INST] Hello human![INST] What is your name?[/INST] My name is Ollama and I`,
		},
Michael Yang's avatar
Michael Yang committed
359
		{
Michael Yang's avatar
Michael Yang committed
360
361
362
363
			"chatml",
			[]template{
				// this does not have a "no response" test because it's impossible to render the same output
				{"response", `{{ if .System }}<|im_start|>system
Michael Yang's avatar
Michael Yang committed
364
365
366
367
368
{{ .System }}<|im_end|>
{{ end }}{{ if .Prompt }}<|im_start|>user
{{ .Prompt }}<|im_end|>
{{ end }}<|im_start|>assistant
{{ .Response }}<|im_end|>
Michael Yang's avatar
Michael Yang committed
369
370
`},
				{"messages", `
371
372
373
{{- range $index, $_ := .Messages }}<|im_start|>{{ .Role }}
{{ .Content }}<|im_end|>
{{ end }}<|im_start|>assistant
Michael Yang's avatar
Michael Yang committed
374
`},
Michael Yang's avatar
Michael Yang committed
375
376
377
378
379
380
			},
			Values{
				Messages: []api.Message{
					{Role: "system", Content: "You are a helpful assistant!"},
					{Role: "user", Content: "Hello friend!"},
					{Role: "assistant", Content: "Hello human!"},
Michael Yang's avatar
Michael Yang committed
381
					{Role: "user", Content: "What is your name?"},
Michael Yang's avatar
Michael Yang committed
382
383
				},
			},
384
385
386
			`<|im_start|>system
You are a helpful assistant!<|im_end|>
<|im_start|>user
Michael Yang's avatar
Michael Yang committed
387
388
389
390
Hello friend!<|im_end|>
<|im_start|>assistant
Hello human!<|im_end|>
<|im_start|>user
Michael Yang's avatar
Michael Yang committed
391
What is your name?<|im_end|>
Michael Yang's avatar
Michael Yang committed
392
393
394
395
396
397
<|im_start|>assistant
`,
		},
	}

	for _, tt := range cases {
Michael Yang's avatar
Michael Yang committed
398
399
400
401
		t.Run(tt.name, func(t *testing.T) {
			for _, ttt := range tt.templates {
				t.Run(ttt.name, func(t *testing.T) {
					tmpl, err := Parse(ttt.template)
Michael Yang's avatar
Michael Yang committed
402
403
404
405
406
407
408
409
410
					if err != nil {
						t.Fatal(err)
					}

					var b bytes.Buffer
					if err := tmpl.Execute(&b, tt.values); err != nil {
						t.Fatal(err)
					}

411
412
					if diff := cmp.Diff(b.String(), tt.expected); diff != "" {
						t.Errorf("mismatch (-got +want):\n%s", diff)
Michael Yang's avatar
Michael Yang committed
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

func TestExecuteWithSuffix(t *testing.T) {
	tmpl, err := Parse(`{{- if .Suffix }}<PRE> {{ .Prompt }} <SUF>{{ .Suffix }} <MID>
{{- else }}{{ .Prompt }}
{{- end }}`)
	if err != nil {
		t.Fatal(err)
	}

	cases := []struct {
		name   string
		values Values
		expect string
	}{
		{
			"message", Values{Messages: []api.Message{{Role: "user", Content: "hello"}}}, "hello",
		},
		{
			"prompt suffix", Values{Prompt: "def add(", Suffix: "return x"}, "<PRE> def add( <SUF>return x <MID>",
		},
	}

	for _, tt := range cases {
		t.Run(tt.name, func(t *testing.T) {
			var b bytes.Buffer
			if err := tmpl.Execute(&b, tt.values); err != nil {
				t.Fatal(err)
			}

			if diff := cmp.Diff(b.String(), tt.expect); diff != "" {
				t.Errorf("mismatch (-got +want):\n%s", diff)
			}
		})
	}
}
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
func TestDateFunctions(t *testing.T) {
	t.Run("currentDate", func(t *testing.T) {
		tmpl, err := Parse("{{- range .Messages }}{{ .Content }}{{ end }} Today is {{ currentDate }}")
		if err != nil {
			t.Fatal(err)
		}

		var b bytes.Buffer
		if err := tmpl.Execute(&b, Values{Messages: []api.Message{{Role: "user", Content: "Hello"}}}); err != nil {
			t.Fatal(err)
		}

		expected := "Hello Today is " + time.Now().Format("2006-01-02")
		if b.String() != expected {
			t.Errorf("got %q, want %q", b.String(), expected)
		}
	})

	t.Run("yesterdayDate", func(t *testing.T) {
		tmpl, err := Parse("{{- range .Messages }}{{ .Content }}{{ end }} Yesterday was {{ yesterdayDate }}")
		if err != nil {
			t.Fatal(err)
		}

		var b bytes.Buffer
		if err := tmpl.Execute(&b, Values{Messages: []api.Message{{Role: "user", Content: "Hello"}}}); err != nil {
			t.Fatal(err)
		}

		expected := "Hello Yesterday was " + time.Now().AddDate(0, 0, -1).Format("2006-01-02")
		if b.String() != expected {
			t.Errorf("got %q, want %q", b.String(), expected)
		}
	})

	t.Run("yesterdayDate format", func(t *testing.T) {
		tmpl, err := Parse("{{- range .Messages }}{{ end }}{{ yesterdayDate }}")
		if err != nil {
			t.Fatal(err)
		}

		var b bytes.Buffer
		if err := tmpl.Execute(&b, Values{Messages: []api.Message{{Role: "user", Content: "Hello"}}}); err != nil {
			t.Fatal(err)
		}

		// Verify the format matches YYYY-MM-DD
		result := b.String()
		if len(result) != 10 {
			t.Errorf("expected date length 10, got %d: %q", len(result), result)
		}

		// Parse and verify it's a valid date
		parsed, err := time.Parse("2006-01-02", result)
		if err != nil {
			t.Errorf("failed to parse date %q: %v", result, err)
		}

		// Verify it's yesterday
		yesterday := time.Now().AddDate(0, 0, -1)
		if parsed.Year() != yesterday.Year() || parsed.Month() != yesterday.Month() || parsed.Day() != yesterday.Day() {
			t.Errorf("expected yesterday's date, got %v", parsed)
		}
	})
}

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
func TestCollate(t *testing.T) {
	cases := []struct {
		name     string
		msgs     []api.Message
		expected []*api.Message
		system   string
	}{
		{
			name: "consecutive user messages are merged",
			msgs: []api.Message{
				{Role: "user", Content: "Hello"},
				{Role: "user", Content: "How are you?"},
			},
			expected: []*api.Message{
				{Role: "user", Content: "Hello\n\nHow are you?"},
			},
			system: "",
		},
		{
			name: "consecutive tool messages are NOT merged",
			msgs: []api.Message{
				{Role: "tool", Content: "sunny", ToolName: "get_weather"},
				{Role: "tool", Content: "72F", ToolName: "get_temperature"},
			},
			expected: []*api.Message{
				{Role: "tool", Content: "sunny", ToolName: "get_weather"},
				{Role: "tool", Content: "72F", ToolName: "get_temperature"},
			},
			system: "",
		},
		{
			name: "tool messages preserve all fields",
			msgs: []api.Message{
				{Role: "user", Content: "What's the weather?"},
				{Role: "tool", Content: "sunny", ToolName: "get_conditions"},
				{Role: "tool", Content: "72F", ToolName: "get_temperature"},
			},
			expected: []*api.Message{
				{Role: "user", Content: "What's the weather?"},
				{Role: "tool", Content: "sunny", ToolName: "get_conditions"},
				{Role: "tool", Content: "72F", ToolName: "get_temperature"},
			},
			system: "",
		},
		{
			name: "mixed messages with system",
			msgs: []api.Message{
				{Role: "system", Content: "You are helpful"},
				{Role: "user", Content: "Hello"},
				{Role: "assistant", Content: "Hi there!"},
				{Role: "user", Content: "What's the weather?"},
				{Role: "tool", Content: "sunny", ToolName: "get_weather"},
				{Role: "tool", Content: "72F", ToolName: "get_temperature"},
				{Role: "user", Content: "Thanks"},
			},
			expected: []*api.Message{
				{Role: "system", Content: "You are helpful"},
				{Role: "user", Content: "Hello"},
				{Role: "assistant", Content: "Hi there!"},
				{Role: "user", Content: "What's the weather?"},
				{Role: "tool", Content: "sunny", ToolName: "get_weather"},
				{Role: "tool", Content: "72F", ToolName: "get_temperature"},
				{Role: "user", Content: "Thanks"},
			},
			system: "You are helpful",
		},
	}

	for _, tt := range cases {
		t.Run(tt.name, func(t *testing.T) {
			system, collated := collate(tt.msgs)
			if diff := cmp.Diff(system, tt.system); diff != "" {
				t.Errorf("system mismatch (-got +want):\n%s", diff)
			}

			// Compare the messages
			if len(collated) != len(tt.expected) {
				t.Errorf("expected %d messages, got %d", len(tt.expected), len(collated))
				return
			}

			for i := range collated {
				if collated[i].Role != tt.expected[i].Role {
					t.Errorf("message %d role mismatch: got %q, want %q", i, collated[i].Role, tt.expected[i].Role)
				}
				if collated[i].Content != tt.expected[i].Content {
					t.Errorf("message %d content mismatch: got %q, want %q", i, collated[i].Content, tt.expected[i].Content)
				}
				if collated[i].ToolName != tt.expected[i].ToolName {
					t.Errorf("message %d tool name mismatch: got %q, want %q", i, collated[i].ToolName, tt.expected[i].ToolName)
				}
			}
		})
	}
}
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

func TestTemplateArgumentsJSON(t *testing.T) {
	// Test that {{ .Function.Arguments }} outputs valid JSON, not map[key:value]
	tmpl := `{{- range .Messages }}{{- range .ToolCalls }}{{ .Function.Arguments }}{{- end }}{{- end }}`

	template, err := Parse(tmpl)
	if err != nil {
		t.Fatal(err)
	}

	args := api.NewToolCallFunctionArguments()
	args.Set("location", "Tokyo")
	args.Set("unit", "celsius")

	var buf bytes.Buffer
	err = template.Execute(&buf, Values{
		Messages: []api.Message{{
			Role: "assistant",
			ToolCalls: []api.ToolCall{{
				Function: api.ToolCallFunction{
					Name:      "get_weather",
					Arguments: args,
				},
			}},
		}},
	})
	if err != nil {
		t.Fatal(err)
	}

	got := buf.String()
	// Should be valid JSON, not "map[location:Tokyo unit:celsius]"
	if strings.HasPrefix(got, "map[") {
		t.Errorf("Arguments output as Go map format: %s", got)
	}

	var parsed map[string]any
	if err := json.Unmarshal([]byte(got), &parsed); err != nil {
		t.Errorf("Arguments not valid JSON: %s, error: %v", got, err)
	}
}

func TestTemplatePropertiesJSON(t *testing.T) {
	// Test that {{ .Function.Parameters.Properties }} outputs valid JSON
	// Note: template must reference .Messages to trigger the modern code path that converts Tools
	tmpl := `{{- range .Messages }}{{- end }}{{- range .Tools }}{{ .Function.Parameters.Properties }}{{- end }}`

	template, err := Parse(tmpl)
	if err != nil {
		t.Fatal(err)
	}

	props := api.NewToolPropertiesMap()
	props.Set("location", api.ToolProperty{Type: api.PropertyType{"string"}, Description: "City name"})

	var buf bytes.Buffer
	err = template.Execute(&buf, Values{
		Messages: []api.Message{{Role: "user", Content: "test"}},
		Tools: api.Tools{{
			Type: "function",
			Function: api.ToolFunction{
				Name:        "get_weather",
				Description: "Get weather",
				Parameters: api.ToolFunctionParameters{
					Type:       "object",
					Properties: props,
				},
			},
		}},
	})
	if err != nil {
		t.Fatal(err)
	}

	got := buf.String()
	// Should be valid JSON, not "map[location:{...}]"
	if strings.HasPrefix(got, "map[") {
		t.Errorf("Properties output as Go map format: %s", got)
	}

	var parsed map[string]any
	if err := json.Unmarshal([]byte(got), &parsed); err != nil {
		t.Errorf("Properties not valid JSON: %s, error: %v", got, err)
	}
}

func TestTemplateArgumentsRange(t *testing.T) {
	// Test that we can range over Arguments in templates
	tmpl := `{{- range .Messages }}{{- range .ToolCalls }}{{- range $k, $v := .Function.Arguments }}{{ $k }}={{ $v }};{{- end }}{{- end }}{{- end }}`

	template, err := Parse(tmpl)
	if err != nil {
		t.Fatal(err)
	}

	args := api.NewToolCallFunctionArguments()
	args.Set("city", "Tokyo")

	var buf bytes.Buffer
	err = template.Execute(&buf, Values{
		Messages: []api.Message{{
			Role: "assistant",
			ToolCalls: []api.ToolCall{{
				Function: api.ToolCallFunction{
					Name:      "get_weather",
					Arguments: args,
				},
			}},
		}},
	})
	if err != nil {
		t.Fatal(err)
	}

	got := buf.String()
	if got != "city=Tokyo;" {
		t.Errorf("Range over Arguments failed, got: %s, want: city=Tokyo;", got)
	}
}

func TestTemplatePropertiesRange(t *testing.T) {
	// Test that we can range over Properties in templates
	// Note: template must reference .Messages to trigger the modern code path that converts Tools
	tmpl := `{{- range .Messages }}{{- end }}{{- range .Tools }}{{- range $name, $prop := .Function.Parameters.Properties }}{{ $name }}:{{ $prop.Type }};{{- end }}{{- end }}`

	template, err := Parse(tmpl)
	if err != nil {
		t.Fatal(err)
	}

	props := api.NewToolPropertiesMap()
	props.Set("location", api.ToolProperty{Type: api.PropertyType{"string"}})

	var buf bytes.Buffer
	err = template.Execute(&buf, Values{
		Messages: []api.Message{{Role: "user", Content: "test"}},
		Tools: api.Tools{{
			Type: "function",
			Function: api.ToolFunction{
				Name: "get_weather",
				Parameters: api.ToolFunctionParameters{
					Type:       "object",
					Properties: props,
				},
			},
		}},
	})
	if err != nil {
		t.Fatal(err)
	}

	got := buf.String()
	if got != "location:string;" {
		t.Errorf("Range over Properties failed, got: %s, want: location:string;", got)
	}
}