template.go 7.77 KB
Newer Older
Michael Yang's avatar
Michael Yang committed
1
2
3
4
5
6
7
package template

import (
	"bytes"
	"embed"
	"encoding/json"
	"errors"
Michael Yang's avatar
Michael Yang committed
8
	"fmt"
Michael Yang's avatar
Michael Yang committed
9
10
11
12
13
14
15
16
17
	"io"
	"math"
	"slices"
	"strings"
	"sync"
	"text/template"
	"text/template/parse"

	"github.com/agnivade/levenshtein"
Michael Yang's avatar
Michael Yang committed
18
	"github.com/ollama/ollama/api"
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
	"golang.org/x/exp/maps"
)

//go:embed index.json
var indexBytes []byte

//go:embed *.gotmpl
var templatesFS embed.FS

var templatesOnce = sync.OnceValues(func() ([]*named, error) {
	var templates []*named
	if err := json.Unmarshal(indexBytes, &templates); err != nil {
		return nil, err
	}

	for _, t := range templates {
		bts, err := templatesFS.ReadFile(t.Name + ".gotmpl")
		if err != nil {
			return nil, err
		}

		// normalize line endings
		t.Bytes = bytes.ReplaceAll(bts, []byte("\r\n"), []byte("\n"))
	}

	return templates, nil
})

type named struct {
	Name     string `json:"name"`
	Template string `json:"template"`
	Bytes    []byte
}

func (t named) Reader() io.Reader {
	return bytes.NewReader(t.Bytes)
}

func Named(s string) (*named, error) {
	templates, err := templatesOnce()
	if err != nil {
		return nil, err
	}

	var template *named
	score := math.MaxInt
	for _, t := range templates {
		if s := levenshtein.ComputeDistance(s, t.Template); s < score {
			score = s
			template = t
		}
	}

	if score < 100 {
		return template, nil
	}

	return nil, errors.New("no matching template found")
}

Michael Yang's avatar
Michael Yang committed
79
80
var DefaultTemplate, _ = Parse("{{ .Prompt }}")

Michael Yang's avatar
Michael Yang committed
81
82
83
84
85
type Template struct {
	*template.Template
	raw string
}

Michael Yang's avatar
Michael Yang committed
86
// response is a template node that can be added to templates that don't already have one
Michael Yang's avatar
Michael Yang committed
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
var response = parse.ActionNode{
	NodeType: parse.NodeAction,
	Pipe: &parse.PipeNode{
		NodeType: parse.NodePipe,
		Cmds: []*parse.CommandNode{
			{
				NodeType: parse.NodeCommand,
				Args: []parse.Node{
					&parse.FieldNode{
						NodeType: parse.NodeField,
						Ident:    []string{"Response"},
					},
				},
			},
		},
	},
Michael Yang's avatar
Michael Yang committed
103
104
}

105
var funcs = template.FuncMap{
Michael Yang's avatar
Michael Yang committed
106
107
108
	// contents returns the contents of messages with an optional role filter
	"contents": func(v []*api.Message, role ...string) string {
		var parts []string
109
		for _, m := range v {
Michael Yang's avatar
Michael Yang committed
110
111
			if len(role) == 0 || role[0] == "" || m.Role == role[0] {
				parts = append(parts, m.Content)
112
113
114
			}
		}

Michael Yang's avatar
Michael Yang committed
115
		return strings.Join(parts, "\n\n")
116
117
118
	},
}

Michael Yang's avatar
Michael Yang committed
119
func Parse(s string) (*Template, error) {
120
	tmpl := template.New("").Option("missingkey=zero").Funcs(funcs)
Michael Yang's avatar
Michael Yang committed
121
122

	tmpl, err := tmpl.Parse(s)
Michael Yang's avatar
Michael Yang committed
123
124
125
126
	if err != nil {
		return nil, err
	}

Michael Yang's avatar
Michael Yang committed
127
128
129
130
131
132
133
134
135
136
137
	t := Template{Template: tmpl, raw: s}
	if vars := t.Vars(); !slices.Contains(vars, "messages") && !slices.Contains(vars, "response") {
		// touch up the template and append {{ .Response }}
		tmpl.Tree.Root.Nodes = append(tmpl.Tree.Root.Nodes, &response)
	}

	return &t, nil
}

func (t *Template) String() string {
	return t.raw
Michael Yang's avatar
Michael Yang committed
138
139
140
141
}

func (t *Template) Vars() []string {
	var vars []string
Michael Yang's avatar
Michael Yang committed
142
143
144
145
	for _, tt := range t.Templates() {
		for _, n := range tt.Root.Nodes {
			vars = append(vars, parseNode(n)...)
		}
Michael Yang's avatar
Michael Yang committed
146
147
148
149
150
151
152
153
154
155
156
157
	}

	set := make(map[string]struct{})
	for _, n := range vars {
		set[strings.ToLower(n)] = struct{}{}
	}

	vars = maps.Keys(set)
	slices.Sort(vars)
	return vars
}

Michael Yang's avatar
Michael Yang committed
158
159
type Values struct {
	Messages []api.Message
160
161
162

	// forceLegacy is a flag used to test compatibility with legacy templates
	forceLegacy bool
Michael Yang's avatar
Michael Yang committed
163
164
165
}

func (t *Template) Execute(w io.Writer, v Values) error {
166
	collated := collate(v.Messages)
167
	if !v.forceLegacy && slices.Contains(t.Vars(), "messages") {
Michael Yang's avatar
Michael Yang committed
168
169
170
171
172
173
		return t.Template.Execute(w, map[string]any{
			"Messages": collated,
		})
	}

	var b bytes.Buffer
174
	var system, prompt, response string
Michael Yang's avatar
Michael Yang committed
175
	for i, m := range collated {
176
		switch m.Role {
177
178
		case "system":
			system = m.Content
179
		case "user":
Michael Yang's avatar
Michael Yang committed
180
			prompt = m.Content
181
		case "assistant":
Michael Yang's avatar
Michael Yang committed
182
183
184
185
186
			response = m.Content
		}

		if i != len(collated)-1 && prompt != "" && response != "" {
			if err := t.Template.Execute(&b, map[string]any{
187
				"System":   system,
Michael Yang's avatar
Michael Yang committed
188
189
190
191
192
193
				"Prompt":   prompt,
				"Response": response,
			}); err != nil {
				return err
			}

194
			system = ""
Michael Yang's avatar
Michael Yang committed
195
196
197
198
199
200
			prompt = ""
			response = ""
		}
	}

	var cut bool
201
202
203
204
205
206
207
	nodes := deleteNode(t.Template.Root.Copy(), func(n parse.Node) bool {
		switch t := n.(type) {
		case *parse.ActionNode:
		case *parse.FieldNode:
			if slices.Contains(t.Ident, "Response") {
				cut = true
			}
Michael Yang's avatar
Michael Yang committed
208
209
210
211
212
		}

		return cut
	})

213
214
215
	tree := parse.Tree{Root: nodes.(*parse.ListNode)}
	if err := template.Must(template.New("").AddParseTree("", &tree)).Execute(&b, map[string]any{
		"System": "",
Michael Yang's avatar
Michael Yang committed
216
217
218
219
220
221
222
223
224
		"Prompt": prompt,
	}); err != nil {
		return err
	}

	_, err := io.Copy(w, &b)
	return err
}

Michael Yang's avatar
Michael Yang committed
225
226
227
228
// collate messages based on role. consecutive messages of the same role are merged
// into a single message. collate also pulls out and merges messages with Role == "system"
// which are templated separately. As a side effect, it mangles message content adding image
// tags ([img-%d]) as needed
229
func collate(msgs []api.Message) (collated []*api.Message) {
Michael Yang's avatar
Michael Yang committed
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
	var n int
	for i := range msgs {
		msg := msgs[i]
		for range msg.Images {
			imageTag := fmt.Sprintf("[img-%d]", n)
			if !strings.Contains(msg.Content, "[img]") {
				msg.Content = strings.TrimSpace("[img] " + msg.Content)
			}

			msg.Content = strings.Replace(msg.Content, "[img]", imageTag, 1)
			n++
		}

		if len(collated) > 0 && collated[len(collated)-1].Role == msg.Role {
			collated[len(collated)-1].Content += "\n\n" + msg.Content
		} else {
			collated = append(collated, &msg)
		}
	}

	return
}

Michael Yang's avatar
Michael Yang committed
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
func parseNode(n parse.Node) []string {
	switch n := n.(type) {
	case *parse.ActionNode:
		return parseNode(n.Pipe)
	case *parse.IfNode:
		names := parseNode(n.Pipe)
		names = append(names, parseNode(n.List)...)
		if n.ElseList != nil {
			names = append(names, parseNode(n.ElseList)...)
		}
		return names
	case *parse.RangeNode:
		names := parseNode(n.Pipe)
		names = append(names, parseNode(n.List)...)
		if n.ElseList != nil {
			names = append(names, parseNode(n.ElseList)...)
		}
		return names
	case *parse.WithNode:
		names := parseNode(n.Pipe)
		names = append(names, parseNode(n.List)...)
		if n.ElseList != nil {
			names = append(names, parseNode(n.ElseList)...)
		}
		return names
	case *parse.PipeNode:
		var names []string
		for _, c := range n.Cmds {
			for _, a := range c.Args {
				names = append(names, parseNode(a)...)
			}
		}
		return names
	case *parse.ListNode:
		var names []string
		for _, n := range n.Nodes {
			names = append(names, parseNode(n)...)
		}

		return names
	case *parse.FieldNode:
		return n.Ident
Michael Yang's avatar
Michael Yang committed
295
296
	case *parse.TemplateNode:
		return parseNode(n.Pipe)
Michael Yang's avatar
Michael Yang committed
297
298
299
300
	}

	return nil
}
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369

// deleteNode walks the node list and deletes nodes that match the predicate
// this is currently to remove the {{ .Response }} node from templates
func deleteNode(n parse.Node, fn func(parse.Node) bool) parse.Node {
	var walk func(n parse.Node) parse.Node
	walk = func(n parse.Node) parse.Node {
		if fn(n) {
			return nil
		}

		switch t := n.(type) {
		case *parse.ListNode:
			var nodes []parse.Node
			for _, c := range t.Nodes {
				if n := walk(c); n != nil {
					nodes = append(nodes, n)
				}
			}

			t.Nodes = nodes
			return t
		case *parse.IfNode:
			t.BranchNode = *(walk(&t.BranchNode).(*parse.BranchNode))
		case *parse.WithNode:
			t.BranchNode = *(walk(&t.BranchNode).(*parse.BranchNode))
		case *parse.RangeNode:
			t.BranchNode = *(walk(&t.BranchNode).(*parse.BranchNode))
		case *parse.BranchNode:
			t.List = walk(t.List).(*parse.ListNode)
			if t.ElseList != nil {
				t.ElseList = walk(t.ElseList).(*parse.ListNode)
			}
		case *parse.ActionNode:
			n := walk(t.Pipe)
			if n == nil {
				return nil
			}

			t.Pipe = n.(*parse.PipeNode)
		case *parse.PipeNode:
			var commands []*parse.CommandNode
			for _, c := range t.Cmds {
				var args []parse.Node
				for _, a := range c.Args {
					if n := walk(a); n != nil {
						args = append(args, n)
					}
				}

				if len(args) == 0 {
					return nil
				}

				c.Args = args
				commands = append(commands, c)
			}

			if len(commands) == 0 {
				return nil
			}

			t.Cmds = commands
		}

		return n
	}

	return walk(n)
}