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

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

	"github.com/agnivade/levenshtein"
Michael Yang's avatar
lint  
Michael Yang committed
19
20

	"github.com/ollama/ollama/api"
Michael Yang's avatar
Michael Yang committed
21
22
23
24
25
26
)

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

//go:embed *.gotmpl
27
//go:embed *.json
Michael Yang's avatar
Michael Yang committed
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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"))
44
45
46
47
48
49
50
51
52

		params, err := templatesFS.ReadFile(t.Name + ".json")
		if err != nil {
			continue
		}

		if err := json.Unmarshal(params, &t.Parameters); err != nil {
			return nil, err
		}
Michael Yang's avatar
Michael Yang committed
53
54
55
56
57
58
59
60
61
	}

	return templates, nil
})

type named struct {
	Name     string `json:"name"`
	Template string `json:"template"`
	Bytes    []byte
62
63
64
65

	Parameters *struct {
		Stop []string `json:"stop"`
	}
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
}

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
94
95
var DefaultTemplate, _ = Parse("{{ .Prompt }}")

Michael Yang's avatar
Michael Yang committed
96
97
98
99
100
type Template struct {
	*template.Template
	raw string
}

Michael Yang's avatar
Michael Yang committed
101
// response is a template node that can be added to templates that don't already have one
Michael Yang's avatar
Michael Yang committed
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
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
118
119
}

Michael Yang's avatar
tools  
Michael Yang committed
120
121
122
123
124
var funcs = template.FuncMap{
	"json": func(v any) string {
		b, _ := json.Marshal(v)
		return string(b)
	},
Michael Yang's avatar
Michael Yang committed
125
126
127
128
129
	"currentDate": func(args ...string) string {
		// Currently ignoring the format argument, but accepting it for future use
		// Default format is YYYY-MM-DD
		return time.Now().Format("2006-01-02")
	},
130
131
132
	"yesterdayDate": func(args ...string) string {
		return time.Now().AddDate(0, 0, -1).Format("2006-01-02")
	},
Devon Rifkin's avatar
Devon Rifkin committed
133
134
135
136
137
138
139
140
141
142
	"toTypeScriptType": func(v any) string {
		if param, ok := v.(api.ToolProperty); ok {
			return param.ToTypeScriptType()
		}
		// Handle pointer case
		if param, ok := v.(*api.ToolProperty); ok && param != nil {
			return param.ToTypeScriptType()
		}
		return "any"
	},
Michael Yang's avatar
tools  
Michael Yang committed
143
144
}

Michael Yang's avatar
Michael Yang committed
145
func Parse(s string) (*Template, error) {
Michael Yang's avatar
tools  
Michael Yang committed
146
	tmpl := template.New("").Option("missingkey=zero").Funcs(funcs)
Michael Yang's avatar
Michael Yang committed
147
148

	tmpl, err := tmpl.Parse(s)
Michael Yang's avatar
Michael Yang committed
149
150
151
152
	if err != nil {
		return nil, err
	}

Michael Yang's avatar
Michael Yang committed
153
	t := Template{Template: tmpl, raw: s}
154
155
156
157
158
159
	vars, err := t.Vars()
	if err != nil {
		return nil, err
	}

	if !slices.Contains(vars, "messages") && !slices.Contains(vars, "response") {
Michael Yang's avatar
Michael Yang committed
160
161
162
163
164
165
166
167
168
		// 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
169
170
}

171
func (t *Template) Vars() ([]string, error) {
Michael Yang's avatar
Michael Yang committed
172
	var vars []string
Michael Yang's avatar
Michael Yang committed
173
174
	for _, tt := range t.Templates() {
		for _, n := range tt.Root.Nodes {
175
176
177
178
179
			v, err := Identifiers(n)
			if err != nil {
				return vars, err
			}
			vars = append(vars, v...)
Michael Yang's avatar
Michael Yang committed
180
		}
Michael Yang's avatar
Michael Yang committed
181
182
183
184
185
186
187
	}

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

188
	return slices.Sorted(maps.Keys(set)), nil
Michael Yang's avatar
Michael Yang committed
189
190
}

Michael Yang's avatar
Michael Yang committed
191
192
193
194
func (t *Template) Contains(s string) bool {
	return strings.Contains(t.raw, s)
}

Michael Yang's avatar
Michael Yang committed
195
196
type Values struct {
	Messages []api.Message
197
198
199
	api.Tools
	Prompt string
	Suffix string
200
	Think  bool
Michael Yang's avatar
Michael Yang committed
201
202
	// ThinkLevel contains the thinking level if Think is true and a string value was provided
	ThinkLevel string
203
204
205
	// whether or not the user explicitly set the thinking flag (vs. it being
	// implicitly false). Templates can't see whether `Think` is nil
	IsThinkSet bool
206
207
208

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

Michael Yang's avatar
tools  
Michael Yang committed
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
func (t *Template) Subtree(fn func(parse.Node) bool) *template.Template {
	var walk func(parse.Node) parse.Node
	walk = func(n parse.Node) parse.Node {
		if fn(n) {
			return n
		}

		switch t := n.(type) {
		case *parse.ListNode:
			for _, c := range t.Nodes {
				if n := walk(c); n != nil {
					return n
				}
			}
		case *parse.BranchNode:
			for _, n := range []*parse.ListNode{t.List, t.ElseList} {
				if n != nil {
					if n := walk(n); n != nil {
						return n
					}
				}
			}
		case *parse.IfNode:
			return walk(&t.BranchNode)
		case *parse.WithNode:
			return walk(&t.BranchNode)
		case *parse.RangeNode:
			return walk(&t.BranchNode)
		}

		return nil
	}

	if n := walk(t.Tree.Root); n != nil {
		return (&template.Template{
			Tree: &parse.Tree{
				Root: &parse.ListNode{
					Nodes: []parse.Node{n},
				},
			},
		}).Funcs(funcs)
	}

	return nil
}

Michael Yang's avatar
Michael Yang committed
257
func (t *Template) Execute(w io.Writer, v Values) error {
Michael Yang's avatar
Michael Yang committed
258
	system, messages := collate(v.Messages)
259
260
261
262
	vars, err := t.Vars()
	if err != nil {
		return err
	}
263
264
	if v.Prompt != "" && v.Suffix != "" {
		return t.Template.Execute(w, map[string]any{
265
266
267
268
			"Prompt":     v.Prompt,
			"Suffix":     v.Suffix,
			"Response":   "",
			"Think":      v.Think,
Michael Yang's avatar
Michael Yang committed
269
			"ThinkLevel": v.ThinkLevel,
270
			"IsThinkSet": v.IsThinkSet,
271
		})
272
	} else if !v.forceLegacy && slices.Contains(vars, "messages") {
Michael Yang's avatar
Michael Yang committed
273
		return t.Template.Execute(w, map[string]any{
274
			"System":     system,
275
276
			"Messages":   convertMessagesForTemplate(messages),
			"Tools":      convertToolsForTemplate(v.Tools),
277
278
			"Response":   "",
			"Think":      v.Think,
Michael Yang's avatar
Michael Yang committed
279
			"ThinkLevel": v.ThinkLevel,
280
			"IsThinkSet": v.IsThinkSet,
Michael Yang's avatar
Michael Yang committed
281
282
283
		})
	}

Michael Yang's avatar
Michael Yang committed
284
	system = ""
Michael Yang's avatar
Michael Yang committed
285
	var b bytes.Buffer
286
	var prompt, response string
Michael Yang's avatar
Michael Yang committed
287
	for _, m := range messages {
Michael Yang's avatar
tools  
Michael Yang committed
288
		execute := func() error {
Michael Yang's avatar
Michael Yang committed
289
			if err := t.Template.Execute(&b, map[string]any{
290
291
292
293
				"System":     system,
				"Prompt":     prompt,
				"Response":   response,
				"Think":      v.Think,
Michael Yang's avatar
Michael Yang committed
294
				"ThinkLevel": v.ThinkLevel,
295
				"IsThinkSet": v.IsThinkSet,
Michael Yang's avatar
Michael Yang committed
296
297
298
299
			}); err != nil {
				return err
			}

300
			system = ""
Michael Yang's avatar
Michael Yang committed
301
302
			prompt = ""
			response = ""
Michael Yang's avatar
Michael Yang committed
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
			return nil
		}

		switch m.Role {
		case "system":
			if prompt != "" || response != "" {
				if err := execute(); err != nil {
					return err
				}
			}
			system = m.Content
		case "user":
			if response != "" {
				if err := execute(); err != nil {
					return err
				}
			}
			prompt = m.Content
		case "assistant":
			response = m.Content
Michael Yang's avatar
Michael Yang committed
323
324
325
326
		}
	}

	var cut bool
327
	nodes := deleteNode(t.Template.Root.Copy(), func(n parse.Node) bool {
Michael Yang's avatar
tools  
Michael Yang committed
328
329
		if field, ok := n.(*parse.FieldNode); ok && slices.Contains(field.Ident, "Response") {
			cut = true
330
			return false
Michael Yang's avatar
Michael Yang committed
331
332
333
334
335
		}

		return cut
	})

336
337
	tree := parse.Tree{Root: nodes.(*parse.ListNode)}
	if err := template.Must(template.New("").AddParseTree("", &tree)).Execute(&b, map[string]any{
338
339
340
341
		"System":     system,
		"Prompt":     prompt,
		"Response":   response,
		"Think":      v.Think,
Michael Yang's avatar
Michael Yang committed
342
		"ThinkLevel": v.ThinkLevel,
343
		"IsThinkSet": v.IsThinkSet,
Michael Yang's avatar
Michael Yang committed
344
345
346
347
	}); err != nil {
		return err
	}

348
	_, err = io.Copy(w, &b)
Michael Yang's avatar
Michael Yang committed
349
350
351
	return err
}

Michael Yang's avatar
Michael Yang committed
352
// collate messages based on role. consecutive messages of the same role are merged
353
354
// into a single message (except for tool messages which preserve individual metadata).
// collate also collects and returns all system messages.
355
// collate mutates message content adding image tags ([img-%d]) as needed
356
// todo(parthsareen): revisit for contextual image support
357
358
359
func collate(msgs []api.Message) (string, []*api.Message) {
	var system []string
	var collated []*api.Message
Michael Yang's avatar
Michael Yang committed
360
	for i := range msgs {
361
362
		if msgs[i].Role == "system" {
			system = append(system, msgs[i].Content)
363
364
		}

365
366
367
		// merges consecutive messages of the same role into a single message (except for tool messages)
		if len(collated) > 0 && collated[len(collated)-1].Role == msgs[i].Role && msgs[i].Role != "tool" {
			collated[len(collated)-1].Content += "\n\n" + msgs[i].Content
Michael Yang's avatar
Michael Yang committed
368
		} else {
369
			collated = append(collated, &msgs[i])
Michael Yang's avatar
Michael Yang committed
370
371
372
		}
	}

373
	return strings.Join(system, "\n\n"), collated
Michael Yang's avatar
Michael Yang committed
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
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
475
476
477
478
479
480
481
482
483
484
485
486
487
// templateTools is a slice of templateTool that marshals to JSON.
type templateTools []templateTool

func (t templateTools) String() string {
	bts, _ := json.Marshal(t)
	return string(bts)
}

// templateTool is a template-compatible representation of api.Tool
// with Properties as a regular map for template ranging.
type templateTool struct {
	Type     string               `json:"type"`
	Items    any                  `json:"items,omitempty"`
	Function templateToolFunction `json:"function"`
}

type templateToolFunction struct {
	Name        string                         `json:"name"`
	Description string                         `json:"description"`
	Parameters  templateToolFunctionParameters `json:"parameters"`
}

type templateToolFunctionParameters struct {
	Type       string                      `json:"type"`
	Defs       any                         `json:"$defs,omitempty"`
	Items      any                         `json:"items,omitempty"`
	Required   []string                    `json:"required,omitempty"`
	Properties map[string]api.ToolProperty `json:"properties"`
}

// templateToolCall is a template-compatible representation of api.ToolCall
// with Arguments as a regular map for template ranging.
type templateToolCall struct {
	ID       string
	Function templateToolCallFunction
}

type templateToolCallFunction struct {
	Index     int
	Name      string
	Arguments map[string]any
}

// templateMessage is a template-compatible representation of api.Message
// with ToolCalls converted for template use.
type templateMessage struct {
	Role       string
	Content    string
	Thinking   string
	Images     []api.ImageData
	ToolCalls  []templateToolCall
	ToolName   string
	ToolCallID string
}

// convertToolsForTemplate converts Tools to template-compatible format.
func convertToolsForTemplate(tools api.Tools) templateTools {
	if tools == nil {
		return nil
	}
	result := make(templateTools, len(tools))
	for i, tool := range tools {
		result[i] = templateTool{
			Type:  tool.Type,
			Items: tool.Items,
			Function: templateToolFunction{
				Name:        tool.Function.Name,
				Description: tool.Function.Description,
				Parameters: templateToolFunctionParameters{
					Type:       tool.Function.Parameters.Type,
					Defs:       tool.Function.Parameters.Defs,
					Items:      tool.Function.Parameters.Items,
					Required:   tool.Function.Parameters.Required,
					Properties: tool.Function.Parameters.Properties.ToMap(),
				},
			},
		}
	}
	return result
}

// convertMessagesForTemplate converts Messages to template-compatible format.
func convertMessagesForTemplate(messages []*api.Message) []*templateMessage {
	if messages == nil {
		return nil
	}
	result := make([]*templateMessage, len(messages))
	for i, msg := range messages {
		var toolCalls []templateToolCall
		for _, tc := range msg.ToolCalls {
			toolCalls = append(toolCalls, templateToolCall{
				ID: tc.ID,
				Function: templateToolCallFunction{
					Index:     tc.Function.Index,
					Name:      tc.Function.Name,
					Arguments: tc.Function.Arguments.ToMap(),
				},
			})
		}
		result[i] = &templateMessage{
			Role:       msg.Role,
			Content:    msg.Content,
			Thinking:   msg.Thinking,
			Images:     msg.Images,
			ToolCalls:  toolCalls,
			ToolName:   msg.ToolName,
			ToolCallID: msg.ToolCallID,
		}
	}
	return result
}

Michael Yang's avatar
tools  
Michael Yang committed
488
// Identifiers walks the node tree returning any identifiers it finds along the way
489
func Identifiers(n parse.Node) ([]string, error) {
Michael Yang's avatar
Michael Yang committed
490
	switch n := n.(type) {
Michael Yang's avatar
tools  
Michael Yang committed
491
492
493
	case *parse.ListNode:
		var names []string
		for _, n := range n.Nodes {
494
495
496
497
498
			i, err := Identifiers(n)
			if err != nil {
				return names, err
			}
			names = append(names, i...)
Michael Yang's avatar
Michael Yang committed
499
		}
Michael Yang's avatar
tools  
Michael Yang committed
500

501
		return names, nil
Michael Yang's avatar
tools  
Michael Yang committed
502
	case *parse.TemplateNode:
503
504
505
		if n.Pipe == nil {
			return nil, errors.New("undefined template specified")
		}
Michael Yang's avatar
tools  
Michael Yang committed
506
507
		return Identifiers(n.Pipe)
	case *parse.ActionNode:
508
509
510
		if n.Pipe == nil {
			return nil, errors.New("undefined action in template")
		}
Michael Yang's avatar
tools  
Michael Yang committed
511
512
		return Identifiers(n.Pipe)
	case *parse.BranchNode:
513
514
515
516
517
518
519
		if n.Pipe == nil {
			return nil, errors.New("undefined branch")
		}
		names, err := Identifiers(n.Pipe)
		if err != nil {
			return names, err
		}
Michael Yang's avatar
tools  
Michael Yang committed
520
521
		for _, n := range []*parse.ListNode{n.List, n.ElseList} {
			if n != nil {
522
523
524
525
526
				i, err := Identifiers(n)
				if err != nil {
					return names, err
				}
				names = append(names, i...)
Michael Yang's avatar
tools  
Michael Yang committed
527
			}
Michael Yang's avatar
Michael Yang committed
528
		}
529
		return names, nil
Michael Yang's avatar
tools  
Michael Yang committed
530
531
532
533
	case *parse.IfNode:
		return Identifiers(&n.BranchNode)
	case *parse.RangeNode:
		return Identifiers(&n.BranchNode)
Michael Yang's avatar
Michael Yang committed
534
	case *parse.WithNode:
Michael Yang's avatar
tools  
Michael Yang committed
535
		return Identifiers(&n.BranchNode)
Michael Yang's avatar
Michael Yang committed
536
537
538
539
	case *parse.PipeNode:
		var names []string
		for _, c := range n.Cmds {
			for _, a := range c.Args {
540
541
542
543
544
				i, err := Identifiers(a)
				if err != nil {
					return names, err
				}
				names = append(names, i...)
Michael Yang's avatar
Michael Yang committed
545
546
			}
		}
547
		return names, nil
Michael Yang's avatar
Michael Yang committed
548
	case *parse.FieldNode:
549
		return n.Ident, nil
Michael Yang's avatar
tools  
Michael Yang committed
550
	case *parse.VariableNode:
551
		return n.Ident, nil
Michael Yang's avatar
Michael Yang committed
552
553
	}

554
	return nil, nil
Michael Yang's avatar
Michael Yang committed
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
616
617
618
619
620
621
622
623
624

// 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)
}