template_test.go 8.3 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
	"strconv"
Michael Yang's avatar
Michael Yang committed
12
13
14
	"testing"
	"text/template"

Michael Yang's avatar
Michael Yang committed
15
	"github.com/ollama/ollama/api"
Michael Yang's avatar
Michael Yang committed
16
17
18
	"github.com/ollama/ollama/llm"
)

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
func TestFuncs(t *testing.T) {
	t.Run("toJson", func(t *testing.T) {
		cases := []struct {
			input    any
			expected string
		}{
			{nil, "null"},
			{true, "true"},
			{false, "false"},
			{0, "0"},
			{1, "1"},
			{1.0, "1"},
			{1.1, "1.1"},
			{"", `""`},
			{"hello", `"hello"`},
			{[]int{1, 2, 3}, "[1,2,3]"},
			{[]string{"a", "b", "c"}, `["a","b","c"]`},
			{map[string]int{"a": 1, "b": 2}, `{"a":1,"b":2}`},
			{map[string]string{"a": "b", "c": "d"}, `{"a":"b","c":"d"}`},
		}

		for _, tt := range cases {
			t.Run(tt.expected, func(t *testing.T) {
				toJson, ok := funcs["toJson"].(func(any) string)
				if !ok {
					t.Fatal("toJson is not a function")
				}

				if s := toJson(tt.input); s != tt.expected {
					t.Errorf("expected %q, got %q", tt.expected, s)
				}
			})
		}
	})

	t.Run("add", func(t *testing.T) {
		cases := []struct {
			a, b     int
			expected int
		}{
			{0, 0, 0},
			{0, 1, 1},
			{1, 0, 1},
			{1, 1, 2},
			{1, -1, 0},
			{-1, 1, 0},
			{-1, -1, -2},
		}

		for _, tt := range cases {
			t.Run(strconv.Itoa(tt.expected), func(t *testing.T) {
				add, ok := funcs["add"].(func(int, int) int)
				if !ok {
					t.Fatal("add is not a function")
				}

				if n := add(tt.a, tt.b); n != tt.expected {
					t.Errorf("expected %d, got %d", tt.expected, n)
				}
			})
		}
	})

	t.Run("sub", func(t *testing.T) {
		cases := []struct {
			a, b     int
			expected int
		}{
			{0, 0, 0},
			{0, 1, -1},
			{1, 0, 1},
			{1, 1, 0},
			{1, -1, 2},
			{-1, 1, -2},
			{-1, -1, 0},
		}

		for _, tt := range cases {
			t.Run(strconv.Itoa(tt.expected), func(t *testing.T) {
				sub, ok := funcs["sub"].(func(int, int) int)
				if !ok {
					t.Fatal("sub is not a function")
				}

				if n := sub(tt.a, tt.b); n != tt.expected {
					t.Errorf("expected %d, got %d", tt.expected, n)
				}
			})
		}
	})
}

Michael Yang's avatar
Michael Yang committed
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
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) {
				kv := llm.KV{"tokenizer.chat_template": v}
				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)
				}

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

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

func TestParse(t *testing.T) {
	cases := []struct {
Michael Yang's avatar
Michael Yang committed
158
159
		template string
		vars     []string
Michael Yang's avatar
Michael Yang committed
160
	}{
Michael Yang's avatar
Michael Yang committed
161
162
		{"{{ .Prompt }}", []string{"prompt", "response"}},
		{"{{ .System }} {{ .Prompt }}", []string{"prompt", "response", "system"}},
Michael Yang's avatar
Michael Yang committed
163
		{"{{ .System }} {{ .Prompt }} {{ .Response }}", []string{"prompt", "response", "system"}},
Michael Yang's avatar
Michael Yang committed
164
		{"{{ with .Tools }}{{ . }}{{ end }} {{ .System }} {{ .Prompt }}", []string{"prompt", "response", "system", "tools"}},
Michael Yang's avatar
Michael Yang committed
165
166
167
168
169
170
171
172
173
174
175
176
		{"{{ range .Messages }}{{ .Role }} {{ .Content }}{{ end }}", []string{"content", "messages", "role"}},
		{"{{ range .Messages }}{{ if eq .Role \"system\" }}SYSTEM: {{ .Content }}{{ else if eq .Role \"user\" }}USER: {{ .Content }}{{ else if eq .Role \"assistant\" }}ASSISTANT: {{ .Content }}{{ end }}{{ end }}", []string{"content", "messages", "role"}},
	}

	for _, tt := range cases {
		t.Run("", func(t *testing.T) {
			tmpl, err := Parse(tt.template)
			if err != nil {
				t.Fatal(err)
			}

			vars := tmpl.Vars()
Michael Yang's avatar
Michael Yang committed
177
178
			if !slices.Equal(tt.vars, vars) {
				t.Errorf("expected %v, got %v", tt.vars, vars)
Michael Yang's avatar
Michael Yang committed
179
180
181
182
			}
		})
	}
}
Michael Yang's avatar
Michael Yang committed
183
184

func TestExecuteWithMessages(t *testing.T) {
Michael Yang's avatar
Michael Yang committed
185
186
187
188
	type template struct {
		name     string
		template string
	}
Michael Yang's avatar
Michael Yang committed
189
	cases := []struct {
Michael Yang's avatar
Michael Yang committed
190
191
		name      string
		templates []template
Michael Yang's avatar
Michael Yang committed
192
193
194
195
		values    Values
		expected  string
	}{
		{
Michael Yang's avatar
Michael Yang committed
196
197
198
199
200
201
			"mistral",
			[]template{
				{"no response", `[INST] {{ if .System }}{{ .System }}{{ "\n\n" }}{{ end }}{{ .Prompt }}[/INST] `},
				{"response", `[INST] {{ if .System }}{{ .System }}{{ "\n\n" }}{{ end }}{{ .Prompt }}[/INST] {{ .Response }}`},
				{"messages", `{{- range .Messages }}
{{- if eq .Role "user" }}[INST] {{ if and (eq (index $.Messages (sub (len $.Messages) 1)) .) $.System }}{{ $.System }}{{ "\n\n" }}
Michael Yang's avatar
Michael Yang committed
202
203
{{- end }}{{ .Content }}[/INST] {{ else if eq .Role "assistant" }}{{ .Content }}
{{- end }}
Michael Yang's avatar
Michael Yang committed
204
{{- end }}`},
Michael Yang's avatar
Michael Yang committed
205
206
207
208
209
			},
			Values{
				Messages: []api.Message{
					{Role: "user", Content: "Hello friend!"},
					{Role: "assistant", Content: "Hello human!"},
Michael Yang's avatar
Michael Yang committed
210
					{Role: "user", Content: "What is your name?"},
Michael Yang's avatar
Michael Yang committed
211
212
				},
			},
Michael Yang's avatar
Michael Yang committed
213
			`[INST] Hello friend![/INST] Hello human![INST] What is your name?[/INST] `,
Michael Yang's avatar
Michael Yang committed
214
215
		},
		{
Michael Yang's avatar
Michael Yang committed
216
217
218
219
220
			"mistral system",
			[]template{
				{"no response", `[INST] {{ if .System }}{{ .System }}{{ "\n\n" }}{{ end }}{{ .Prompt }}[/INST] `},
				{"response", `[INST] {{ if .System }}{{ .System }}{{ "\n\n" }}{{ end }}{{ .Prompt }}[/INST] {{ .Response }}`},
				{"messages", `
Michael Yang's avatar
Michael Yang committed
221
{{- range .Messages }}
Michael Yang's avatar
Michael Yang committed
222
{{- if eq .Role "user" }}[INST] {{ if and (eq (index $.Messages (sub (len $.Messages) 1)) .) $.System }}{{ $.System }}{{ "\n\n" }}
Michael Yang's avatar
Michael Yang committed
223
224
{{- end }}{{ .Content }}[/INST] {{ else if eq .Role "assistant" }}{{ .Content }}
{{- end }}
Michael Yang's avatar
Michael Yang committed
225
{{- end }}`},
Michael Yang's avatar
Michael Yang committed
226
227
228
229
230
231
			},
			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
232
					{Role: "user", Content: "What is your name?"},
Michael Yang's avatar
Michael Yang committed
233
234
235
236
				},
			},
			`[INST] Hello friend![/INST] Hello human![INST] You are a helpful assistant!

Michael Yang's avatar
Michael Yang committed
237
What is your name?[/INST] `,
Michael Yang's avatar
Michael Yang committed
238
239
		},
		{
Michael Yang's avatar
Michael Yang committed
240
241
242
243
			"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
244
245
246
247
248
{{ .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
249
250
`},
				{"messages", `
Michael Yang's avatar
Michael Yang committed
251
{{- range .Messages }}
Michael Yang's avatar
Michael Yang committed
252
253
{{- if and (eq .Role "user") (eq (index $.Messages (sub (len $.Messages) 1)) .) $.System }}<|im_start|>system
{{ $.System }}<|im_end|>{{ "\n" }}
Michael Yang's avatar
Michael Yang committed
254
{{- end }}<|im_start|>{{ .Role }}
Michael Yang's avatar
Michael Yang committed
255
{{ .Content }}<|im_end|>{{ "\n" }}
Michael Yang's avatar
Michael Yang committed
256
{{- end }}<|im_start|>assistant
Michael Yang's avatar
Michael Yang committed
257
`},
Michael Yang's avatar
Michael Yang committed
258
259
260
261
262
263
			},
			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
264
					{Role: "user", Content: "What is your name?"},
Michael Yang's avatar
Michael Yang committed
265
266
267
268
269
270
271
272
273
				},
			},
			`<|im_start|>user
Hello friend!<|im_end|>
<|im_start|>assistant
Hello human!<|im_end|>
<|im_start|>system
You are a helpful assistant!<|im_end|>
<|im_start|>user
Michael Yang's avatar
Michael Yang committed
274
What is your name?<|im_end|>
Michael Yang's avatar
Michael Yang committed
275
276
277
278
<|im_start|>assistant
`,
		},
		{
Michael Yang's avatar
Michael Yang committed
279
280
281
282
			"moondream",
			[]template{
				// this does not have a "no response" test because it's impossible to render the same output
				{"response", `{{ if .Prompt }}Question: {{ .Prompt }}
Michael Yang's avatar
Michael Yang committed
283
284
285

{{ end }}Answer: {{ .Response }}

Michael Yang's avatar
Michael Yang committed
286
287
`},
				{"messages", `
Michael Yang's avatar
Michael Yang committed
288
{{- range .Messages }}
Michael Yang's avatar
Michael Yang committed
289
290
{{- if eq .Role "user" }}Question: {{ .Content }}{{ "\n\n" }}
{{- else if eq .Role "assistant" }}Answer: {{ .Content }}{{ "\n\n" }}
Michael Yang's avatar
Michael Yang committed
291
{{- end }}
Michael Yang's avatar
Michael Yang committed
292
{{- end }}Answer: `},
Michael Yang's avatar
Michael Yang committed
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
			},
			Values{
				Messages: []api.Message{
					{Role: "user", Content: "What's in this image?", Images: []api.ImageData{[]byte("")}},
					{Role: "assistant", Content: "It's a hot dog."},
					{Role: "user", Content: "What's in _this_ image?"},
					{Role: "user", Images: []api.ImageData{[]byte("")}},
					{Role: "user", Content: "Is it a hot dog?"},
				},
			},
			`Question: [img-0] What's in this image?

Answer: It's a hot dog.

Question: What's in _this_ image?

[img-1]

Is it a hot dog?

Answer: `,
		},
	}

	for _, tt := range cases {
Michael Yang's avatar
Michael Yang committed
318
319
320
321
		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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
					if err != nil {
						t.Fatal(err)
					}

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

					if b.String() != tt.expected {
						t.Errorf("expected\n%s,\ngot\n%s", tt.expected, b.String())
					}
				})
			}
		})
	}
}