routes_create_test.go 28 KB
Newer Older
Michael Yang's avatar
Michael Yang committed
1
2
3
4
package server

import (
	"bytes"
Michael Yang's avatar
Michael Yang committed
5
	"cmp"
6
	"crypto/sha256"
Michael Yang's avatar
Michael Yang committed
7
8
9
	"encoding/json"
	"fmt"
	"io"
10
	"maps"
Michael Yang's avatar
Michael Yang committed
11
12
13
14
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
15
	"reflect"
Michael Yang's avatar
Michael Yang committed
16
	"slices"
17
	"strings"
Michael Yang's avatar
Michael Yang committed
18
19
20
	"testing"

	"github.com/gin-gonic/gin"
21
22
	gocmp "github.com/google/go-cmp/cmp"
	gocmpopts "github.com/google/go-cmp/cmp/cmpopts"
Michael Yang's avatar
lint  
Michael Yang committed
23

Michael Yang's avatar
Michael Yang committed
24
	"github.com/ollama/ollama/api"
25
	"github.com/ollama/ollama/convert"
26
	"github.com/ollama/ollama/envconfig"
Michael Yang's avatar
Michael Yang committed
27
	"github.com/ollama/ollama/fs/ggml"
28
	"github.com/ollama/ollama/types/model"
Michael Yang's avatar
Michael Yang committed
29
30
31
32
)

var stream bool = false

33
func createBinFile(t *testing.T, kv map[string]any, ti []*ggml.Tensor) (string, string) {
Michael Yang's avatar
Michael Yang committed
34
	t.Helper()
35
36
37
	t.Setenv("OLLAMA_MODELS", cmp.Or(os.Getenv("OLLAMA_MODELS"), t.TempDir()))

	modelDir := envconfig.Models()
Michael Yang's avatar
Michael Yang committed
38
39
40
41
42
43
44

	f, err := os.CreateTemp(t.TempDir(), "")
	if err != nil {
		t.Fatal(err)
	}
	defer f.Close()

45
	var base convert.KV = map[string]any{"general.architecture": "test"}
46
47
48
	maps.Copy(base, kv)

	if err := ggml.WriteGGUF(f, base, ti); err != nil {
Michael Yang's avatar
Michael Yang committed
49
50
		t.Fatal(err)
	}
51
52
53
54
55
56
57
58
59
	// Calculate sha256 of file
	if _, err := f.Seek(0, 0); err != nil {
		t.Fatal(err)
	}

	digest, _ := GetSHA256Digest(f)
	if err := f.Close(); err != nil {
		t.Fatal(err)
	}
Michael Yang's avatar
Michael Yang committed
60

61
62
63
64
65
	if err := createLink(f.Name(), filepath.Join(modelDir, "blobs", fmt.Sprintf("sha256-%s", strings.TrimPrefix(digest, "sha256:")))); err != nil {
		t.Fatal(err)
	}

	return f.Name(), digest
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
}

type responseRecorder struct {
	*httptest.ResponseRecorder
	http.CloseNotifier
}

func NewRecorder() *responseRecorder {
	return &responseRecorder{
		ResponseRecorder: httptest.NewRecorder(),
	}
}

func (t *responseRecorder) CloseNotify() <-chan bool {
	return make(chan bool)
}

func createRequest(t *testing.T, fn func(*gin.Context), body any) *httptest.ResponseRecorder {
	t.Helper()
Michael Yang's avatar
Michael Yang committed
85
86
	// if OLLAMA_MODELS is not set, set it to the temp directory
	t.Setenv("OLLAMA_MODELS", cmp.Or(os.Getenv("OLLAMA_MODELS"), t.TempDir()))
Michael Yang's avatar
Michael Yang committed
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111

	w := NewRecorder()
	c, _ := gin.CreateTestContext(w)

	var b bytes.Buffer
	if err := json.NewEncoder(&b).Encode(body); err != nil {
		t.Fatal(err)
	}

	c.Request = &http.Request{
		Body: io.NopCloser(&b),
	}

	fn(c)
	return w.ResponseRecorder
}

func checkFileExists(t *testing.T, p string, expect []string) {
	t.Helper()

	actual, err := filepath.Glob(p)
	if err != nil {
		t.Fatal(err)
	}

112
113
	if diff := gocmp.Diff(expect, actual, gocmpopts.SortSlices(strings.Compare), gocmpopts.EquateEmpty()); diff != "" {
		t.Errorf("file exists mismatch (-want +got):\n%s", diff)
Michael Yang's avatar
Michael Yang committed
114
115
116
117
	}
}

func TestCreateFromBin(t *testing.T) {
118
119
	gin.SetMode(gin.TestMode)

Michael Yang's avatar
Michael Yang committed
120
121
122
123
	p := t.TempDir()
	t.Setenv("OLLAMA_MODELS", p)

	var s Server
124
125
126

	_, digest := createBinFile(t, nil, nil)

127
	w := createRequest(t, s.CreateHandler, api.CreateRequest{
128
129
130
		Name:   "test",
		Files:  map[string]string{"test.gguf": digest},
		Stream: &stream,
Michael Yang's avatar
Michael Yang committed
131
132
133
	})

	if w.Code != http.StatusOK {
134
		fmt.Println(w)
Michael Yang's avatar
Michael Yang committed
135
136
137
138
139
140
141
142
		t.Fatalf("expected status code 200, actual %d", w.Code)
	}

	checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
		filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
	})

	checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
143
144
		filepath.Join(p, "blobs", "sha256-6bcdb8859d417753645538d7bbfbd7ca91a3f0c191aef5379c53c05e86b669dd"),
		filepath.Join(p, "blobs", "sha256-89a2116c3a82d6a97f59f748d86ed4417214353fd178ee54df418fde32495fad"),
Michael Yang's avatar
Michael Yang committed
145
146
147
148
	})
}

func TestCreateFromModel(t *testing.T) {
149
150
	gin.SetMode(gin.TestMode)

Michael Yang's avatar
Michael Yang committed
151
152
153
154
	p := t.TempDir()
	t.Setenv("OLLAMA_MODELS", p)
	var s Server

155
156
	_, digest := createBinFile(t, nil, nil)

157
	w := createRequest(t, s.CreateHandler, api.CreateRequest{
158
159
160
		Name:   "test",
		Files:  map[string]string{"test.gguf": digest},
		Stream: &stream,
Michael Yang's avatar
Michael Yang committed
161
162
163
164
165
166
167
168
169
170
	})

	if w.Code != http.StatusOK {
		t.Fatalf("expected status code 200, actual %d", w.Code)
	}

	checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
		filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
	})

171
	w = createRequest(t, s.CreateHandler, api.CreateRequest{
172
173
174
		Name:   "test2",
		From:   "test",
		Stream: &stream,
Michael Yang's avatar
Michael Yang committed
175
176
177
178
179
180
181
182
183
184
185
186
	})

	if w.Code != http.StatusOK {
		t.Fatalf("expected status code 200, actual %d", w.Code)
	}

	checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
		filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
		filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test2", "latest"),
	})

	checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
187
188
		filepath.Join(p, "blobs", "sha256-6bcdb8859d417753645538d7bbfbd7ca91a3f0c191aef5379c53c05e86b669dd"),
		filepath.Join(p, "blobs", "sha256-89a2116c3a82d6a97f59f748d86ed4417214353fd178ee54df418fde32495fad"),
Michael Yang's avatar
Michael Yang committed
189
190
	})
}
191

192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
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
func TestCreateFromModelInheritsRendererParser(t *testing.T) {
	gin.SetMode(gin.TestMode)

	p := t.TempDir()
	t.Setenv("OLLAMA_MODELS", p)
	var s Server

	const (
		renderer = "custom-renderer"
		parser   = "custom-parser"
	)

	_, digest := createBinFile(t, nil, nil)

	w := createRequest(t, s.CreateHandler, api.CreateRequest{
		Name:     "base",
		Files:    map[string]string{"base.gguf": digest},
		Renderer: renderer,
		Parser:   parser,
		Stream:   &stream,
	})
	if w.Code != http.StatusOK {
		t.Fatalf("expected status code 200, actual %d", w.Code)
	}

	w = createRequest(t, s.CreateHandler, api.CreateRequest{
		Name:   "child",
		From:   "base",
		Stream: &stream,
	})
	if w.Code != http.StatusOK {
		t.Fatalf("expected status code 200, actual %d", w.Code)
	}

	manifest, err := ParseNamedManifest(model.ParseName("child"))
	if err != nil {
		t.Fatalf("parse manifest: %v", err)
	}
	if manifest.Config.Digest == "" {
		t.Fatalf("unexpected empty config digest for child manifest")
	}

	configPath, err := GetBlobsPath(manifest.Config.Digest)
	if err != nil {
		t.Fatalf("config blob path: %v", err)
	}

	cfgFile, err := os.Open(configPath)
	if err != nil {
		t.Fatalf("open config blob: %v", err)
	}
	defer cfgFile.Close()

245
	var cfg model.ConfigV2
246
247
248
249
250
251
252
253
254
255
256
257
	if err := json.NewDecoder(cfgFile).Decode(&cfg); err != nil {
		t.Fatalf("decode config: %v", err)
	}

	if cfg.Renderer != renderer {
		t.Fatalf("expected renderer %q, got %q", renderer, cfg.Renderer)
	}
	if cfg.Parser != parser {
		t.Fatalf("expected parser %q, got %q", parser, cfg.Parser)
	}
}

258
func TestCreateRemovesLayers(t *testing.T) {
259
260
	gin.SetMode(gin.TestMode)

261
262
263
264
	p := t.TempDir()
	t.Setenv("OLLAMA_MODELS", p)
	var s Server

265
	_, digest := createBinFile(t, nil, nil)
266
	w := createRequest(t, s.CreateHandler, api.CreateRequest{
267
268
269
270
		Name:     "test",
		Files:    map[string]string{"test.gguf": digest},
		Template: "{{ .Prompt }}",
		Stream:   &stream,
271
272
273
274
275
276
277
278
279
280
281
	})

	if w.Code != http.StatusOK {
		t.Fatalf("expected status code 200, actual %d", w.Code)
	}

	checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
		filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
	})

	checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
282
		filepath.Join(p, "blobs", "sha256-89a2116c3a82d6a97f59f748d86ed4417214353fd178ee54df418fde32495fad"),
283
		filepath.Join(p, "blobs", "sha256-b507b9c2f6ca642bffcd06665ea7c91f235fd32daeefdf875a0f938db05fb315"),
284
		filepath.Join(p, "blobs", "sha256-f6e7e4b28e0b1d0c635f2d465bd248c5387c3e75b61a48c4374192b26d832a56"),
285
286
	})

287
	w = createRequest(t, s.CreateHandler, api.CreateRequest{
288
289
290
291
		Name:     "test",
		Files:    map[string]string{"test.gguf": digest},
		Template: "{{ .System }} {{ .Prompt }}",
		Stream:   &stream,
292
293
294
295
296
297
298
299
300
301
302
	})

	if w.Code != http.StatusOK {
		t.Fatalf("expected status code 200, actual %d", w.Code)
	}

	checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
		filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
	})

	checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
303
304
		filepath.Join(p, "blobs", "sha256-136bf7c76bac2ec09d6617885507d37829e04b41acc47687d45e512b544e893a"),
		filepath.Join(p, "blobs", "sha256-89a2116c3a82d6a97f59f748d86ed4417214353fd178ee54df418fde32495fad"),
305
306
307
308
309
		filepath.Join(p, "blobs", "sha256-fe7ac77b725cda2ccad03f88a880ecdfd7a33192d6cae08fce2c0ee1455991ed"),
	})
}

func TestCreateUnsetsSystem(t *testing.T) {
310
311
	gin.SetMode(gin.TestMode)

312
313
314
315
	p := t.TempDir()
	t.Setenv("OLLAMA_MODELS", p)
	var s Server

316
	_, digest := createBinFile(t, nil, nil)
317
	w := createRequest(t, s.CreateHandler, api.CreateRequest{
318
319
320
321
		Name:   "test",
		Files:  map[string]string{"test.gguf": digest},
		System: "Say hi!",
		Stream: &stream,
322
323
324
325
326
327
328
329
330
331
332
	})

	if w.Code != http.StatusOK {
		t.Fatalf("expected status code 200, actual %d", w.Code)
	}

	checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
		filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
	})

	checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
333
334
		filepath.Join(p, "blobs", "sha256-0a666d113e8e0a3d27e9c7bd136a0bdfb6241037db50729d81568451ebfdbde8"),
		filepath.Join(p, "blobs", "sha256-89a2116c3a82d6a97f59f748d86ed4417214353fd178ee54df418fde32495fad"),
335
336
337
		filepath.Join(p, "blobs", "sha256-f29e82a8284dbdf5910b1555580ff60b04238b8da9d5e51159ada67a4d0d5851"),
	})

338
	w = createRequest(t, s.CreateHandler, api.CreateRequest{
339
340
341
342
		Name:   "test",
		Files:  map[string]string{"test.gguf": digest},
		System: "",
		Stream: &stream,
343
344
345
346
347
348
349
350
351
352
353
	})

	if w.Code != http.StatusOK {
		t.Fatalf("expected status code 200, actual %d", w.Code)
	}

	checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
		filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
	})

	checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
354
355
		filepath.Join(p, "blobs", "sha256-6bcdb8859d417753645538d7bbfbd7ca91a3f0c191aef5379c53c05e86b669dd"),
		filepath.Join(p, "blobs", "sha256-89a2116c3a82d6a97f59f748d86ed4417214353fd178ee54df418fde32495fad"),
356
357
358
359
	})
}

func TestCreateMergeParameters(t *testing.T) {
360
361
	gin.SetMode(gin.TestMode)

362
363
364
365
	p := t.TempDir()
	t.Setenv("OLLAMA_MODELS", p)
	var s Server

366
	_, digest := createBinFile(t, nil, nil)
367
	w := createRequest(t, s.CreateHandler, api.CreateRequest{
368
369
370
371
372
373
374
375
		Name:  "test",
		Files: map[string]string{"test.gguf": digest},
		Parameters: map[string]any{
			"temperature": 1,
			"top_k":       10,
			"stop":        []string{"USER:", "ASSISTANT:"},
		},
		Stream: &stream,
376
377
378
379
380
381
382
383
384
385
386
387
	})

	if w.Code != http.StatusOK {
		t.Fatalf("expected status code 200, actual %d", w.Code)
	}

	checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
		filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
	})

	checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
		filepath.Join(p, "blobs", "sha256-1d0ad71299d48c2fb7ae2b98e683643e771f8a5b72be34942af90d97a91c1e37"),
388
389
		filepath.Join(p, "blobs", "sha256-6d6e36c1f90fc7deefc33a7300aa21ad4b67c506e33ecdeddfafa98147e60bbf"),
		filepath.Join(p, "blobs", "sha256-89a2116c3a82d6a97f59f748d86ed4417214353fd178ee54df418fde32495fad"),
390
391
392
	})

	// in order to merge parameters, the second model must be created FROM the first
393
	w = createRequest(t, s.CreateHandler, api.CreateRequest{
394
395
396
397
398
399
400
		Name: "test2",
		From: "test",
		Parameters: map[string]any{
			"temperature": 0.6,
			"top_p":       0.7,
		},
		Stream: &stream,
401
402
403
404
405
406
407
408
409
410
411
	})

	if w.Code != http.StatusOK {
		t.Fatalf("expected status code 200, actual %d", w.Code)
	}

	checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
		filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
		filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test2", "latest"),
	})

412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
	// Display contents of each blob in the directory
	blobDir := filepath.Join(p, "blobs")
	entries, err := os.ReadDir(blobDir)
	if err != nil {
		t.Fatalf("failed to read blobs directory: %v", err)
	}

	for _, entry := range entries {
		blobPath := filepath.Join(blobDir, entry.Name())
		content, err := os.ReadFile(blobPath)
		if err != nil {
			t.Fatalf("failed to read blob %s: %v", entry.Name(), err)
		}
		t.Logf("Contents of %s:\n%s", entry.Name(), string(content))
	}

428
429
	checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
		filepath.Join(p, "blobs", "sha256-1d0ad71299d48c2fb7ae2b98e683643e771f8a5b72be34942af90d97a91c1e37"),
430
431
432
		filepath.Join(p, "blobs", "sha256-6d6e36c1f90fc7deefc33a7300aa21ad4b67c506e33ecdeddfafa98147e60bbf"),
		filepath.Join(p, "blobs", "sha256-89a2116c3a82d6a97f59f748d86ed4417214353fd178ee54df418fde32495fad"),
		filepath.Join(p, "blobs", "sha256-bbdce269dabe013033632238b4b2d1e02fac2f97787c5e895f4da84e09cccd5d"),
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
		filepath.Join(p, "blobs", "sha256-e29a7b3c47287a2489c895d21fe413c20f859a85d20e749492f52a838e36e1ba"),
	})

	actual, err := os.ReadFile(filepath.Join(p, "blobs", "sha256-e29a7b3c47287a2489c895d21fe413c20f859a85d20e749492f52a838e36e1ba"))
	if err != nil {
		t.Fatal(err)
	}

	expect, err := json.Marshal(map[string]any{"temperature": 0.6, "top_k": 10, "top_p": 0.7, "stop": []string{"USER:", "ASSISTANT:"}})
	if err != nil {
		t.Fatal(err)
	}

	if !bytes.Equal(bytes.TrimSpace(expect), bytes.TrimSpace(actual)) {
		t.Errorf("expected %s, actual %s", string(expect), string(actual))
	}

	// slices are replaced
451
	w = createRequest(t, s.CreateHandler, api.CreateRequest{
452
453
454
455
456
457
458
459
		Name: "test2",
		From: "test",
		Parameters: map[string]any{
			"temperature": 0.6,
			"top_p":       0.7,
			"stop":        []string{"<|endoftext|>"},
		},
		Stream: &stream,
460
461
462
463
464
465
466
467
468
469
470
471
472
473
	})

	if w.Code != http.StatusOK {
		t.Fatalf("expected status code 200, actual %d", w.Code)
	}

	checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
		filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
		filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test2", "latest"),
	})

	checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
		filepath.Join(p, "blobs", "sha256-12f58bb75cb3042d69a7e013ab87fb3c3c7088f50ddc62f0c77bd332f0d44d35"),
		filepath.Join(p, "blobs", "sha256-1d0ad71299d48c2fb7ae2b98e683643e771f8a5b72be34942af90d97a91c1e37"),
474
475
476
		filepath.Join(p, "blobs", "sha256-6d6e36c1f90fc7deefc33a7300aa21ad4b67c506e33ecdeddfafa98147e60bbf"),
		filepath.Join(p, "blobs", "sha256-89a2116c3a82d6a97f59f748d86ed4417214353fd178ee54df418fde32495fad"),
		filepath.Join(p, "blobs", "sha256-9443591d14be23c1e33d101934d76ad03bdb0715fe0879e8b0d1819e7bb063dd"),
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
	})

	actual, err = os.ReadFile(filepath.Join(p, "blobs", "sha256-12f58bb75cb3042d69a7e013ab87fb3c3c7088f50ddc62f0c77bd332f0d44d35"))
	if err != nil {
		t.Fatal(err)
	}

	expect, err = json.Marshal(map[string]any{"temperature": 0.6, "top_k": 10, "top_p": 0.7, "stop": []string{"<|endoftext|>"}})
	if err != nil {
		t.Fatal(err)
	}

	if !bytes.Equal(bytes.TrimSpace(expect), bytes.TrimSpace(actual)) {
		t.Errorf("expected %s, actual %s", string(expect), string(actual))
	}
}

func TestCreateReplacesMessages(t *testing.T) {
495
496
	gin.SetMode(gin.TestMode)

497
498
499
500
	p := t.TempDir()
	t.Setenv("OLLAMA_MODELS", p)
	var s Server

501
	_, digest := createBinFile(t, nil, nil)
502
	w := createRequest(t, s.CreateHandler, api.CreateRequest{
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
		Name:  "test",
		Files: map[string]string{"test.gguf": digest},
		Messages: []api.Message{
			{
				Role:    "assistant",
				Content: "What is my purpose?",
			},
			{
				Role:    "user",
				Content: "You run tests.",
			},
			{
				Role:    "assistant",
				Content: "Oh, my god.",
			},
		},
		Stream: &stream,
520
521
522
523
524
525
526
527
528
529
530
531
	})

	if w.Code != http.StatusOK {
		t.Fatalf("expected status code 200, actual %d", w.Code)
	}

	checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
		filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
	})

	checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
		filepath.Join(p, "blobs", "sha256-298baeaf6928a60cf666d88d64a1ba606feb43a2865687c39e40652e407bffc4"),
532
533
		filepath.Join(p, "blobs", "sha256-89a2116c3a82d6a97f59f748d86ed4417214353fd178ee54df418fde32495fad"),
		filepath.Join(p, "blobs", "sha256-c84aee28f2af350596f674de51d2a802ea782653ef2930a21d48bd43d5cd5317"),
534
535
	})

536
	w = createRequest(t, s.CreateHandler, api.CreateRequest{
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
		Name: "test2",
		From: "test",
		Messages: []api.Message{
			{
				Role:    "assistant",
				Content: "You're a test, Harry.",
			},
			{
				Role:    "user",
				Content: "I-I'm a what?",
			},
			{
				Role:    "assistant",
				Content: "A test. And a thumping good one at that, I'd wager.",
			},
		},
		Stream: &stream,
554
555
556
557
558
559
560
561
562
563
564
	})

	if w.Code != http.StatusOK {
		t.Fatalf("expected status code 200, actual %d", w.Code)
	}

	checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
		filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
		filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test2", "latest"),
	})

565
	// Old layers will not have been pruned
566
	checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
567
		filepath.Join(p, "blobs", "sha256-09cfac3e6a637e25cb41aa85c24c110dc17ba89634de7df141b564dd2da4168b"),
568
		filepath.Join(p, "blobs", "sha256-298baeaf6928a60cf666d88d64a1ba606feb43a2865687c39e40652e407bffc4"),
569
		filepath.Join(p, "blobs", "sha256-89a2116c3a82d6a97f59f748d86ed4417214353fd178ee54df418fde32495fad"),
570
		filepath.Join(p, "blobs", "sha256-a60ecc9da299ec7ede453f99236e5577fd125e143689b646d9f0ddc9971bf4db"),
571
		filepath.Join(p, "blobs", "sha256-c84aee28f2af350596f674de51d2a802ea782653ef2930a21d48bd43d5cd5317"),
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
	})

	type message struct {
		Role    string `json:"role"`
		Content string `json:"content"`
	}

	f, err := os.Open(filepath.Join(p, "blobs", "sha256-a60ecc9da299ec7ede453f99236e5577fd125e143689b646d9f0ddc9971bf4db"))
	if err != nil {
		t.Fatal(err)
	}
	defer f.Close()

	var actual []message
	if err := json.NewDecoder(f).Decode(&actual); err != nil {
		t.Fatal(err)
	}

	expect := []message{
		{Role: "assistant", Content: "You're a test, Harry."},
		{Role: "user", Content: "I-I'm a what?"},
		{Role: "assistant", Content: "A test. And a thumping good one at that, I'd wager."},
	}

	if !slices.Equal(actual, expect) {
		t.Errorf("expected %s, actual %s", expect, actual)
	}
}

func TestCreateTemplateSystem(t *testing.T) {
602
603
	gin.SetMode(gin.TestMode)

604
605
606
607
	p := t.TempDir()
	t.Setenv("OLLAMA_MODELS", p)
	var s Server

608
	_, digest := createBinFile(t, nil, nil)
609
	w := createRequest(t, s.CreateHandler, api.CreateRequest{
610
611
612
613
614
		Name:     "test",
		Files:    map[string]string{"test.gguf": digest},
		Template: "{{ .System }} {{ .Prompt }}",
		System:   "Say bye!",
		Stream:   &stream,
615
616
617
618
619
620
621
622
623
624
625
	})

	if w.Code != http.StatusOK {
		t.Fatalf("expected status code 200, actual %d", w.Code)
	}

	checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
		filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
	})

	checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
626
		filepath.Join(p, "blobs", "sha256-0a04d979734167da3b80811a1874d734697f366a689f3912589b99d2e86e7ad1"),
627
		filepath.Join(p, "blobs", "sha256-4c5f51faac758fecaff8db42f0b7382891a4d0c0bb885f7b86be88c814a7cc86"),
628
		filepath.Join(p, "blobs", "sha256-89a2116c3a82d6a97f59f748d86ed4417214353fd178ee54df418fde32495fad"),
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
		filepath.Join(p, "blobs", "sha256-fe7ac77b725cda2ccad03f88a880ecdfd7a33192d6cae08fce2c0ee1455991ed"),
	})

	template, err := os.ReadFile(filepath.Join(p, "blobs", "sha256-fe7ac77b725cda2ccad03f88a880ecdfd7a33192d6cae08fce2c0ee1455991ed"))
	if err != nil {
		t.Fatal(err)
	}

	if string(template) != "{{ .System }} {{ .Prompt }}" {
		t.Errorf("expected \"{{ .System }} {{ .Prompt }}\", actual %s", template)
	}

	system, err := os.ReadFile(filepath.Join(p, "blobs", "sha256-4c5f51faac758fecaff8db42f0b7382891a4d0c0bb885f7b86be88c814a7cc86"))
	if err != nil {
		t.Fatal(err)
	}

	if string(system) != "Say bye!" {
		t.Errorf("expected \"Say bye!\", actual %s", system)
	}
Josh's avatar
Josh committed
649
650

	t.Run("incomplete template", func(t *testing.T) {
651
		_, digest := createBinFile(t, nil, nil)
652
		w := createRequest(t, s.CreateHandler, api.CreateRequest{
653
654
655
656
			Name:     "test",
			Files:    map[string]string{"test.gguf": digest},
			Template: "{{ .Prompt",
			Stream:   &stream,
Josh's avatar
Josh committed
657
		})
Michael Yang's avatar
lint  
Michael Yang committed
658

Josh's avatar
Josh committed
659
660
661
662
663
664
		if w.Code != http.StatusBadRequest {
			t.Fatalf("expected status code 400, actual %d", w.Code)
		}
	})

	t.Run("template with unclosed if", func(t *testing.T) {
665
		_, digest := createBinFile(t, nil, nil)
666
		w := createRequest(t, s.CreateHandler, api.CreateRequest{
667
668
669
670
			Name:     "test",
			Files:    map[string]string{"test.gguf": digest},
			Template: "{{ if .Prompt }}",
			Stream:   &stream,
Josh's avatar
Josh committed
671
		})
Michael Yang's avatar
lint  
Michael Yang committed
672

Josh's avatar
Josh committed
673
674
675
676
677
678
		if w.Code != http.StatusBadRequest {
			t.Fatalf("expected status code 400, actual %d", w.Code)
		}
	})

	t.Run("template with undefined function", func(t *testing.T) {
679
		_, digest := createBinFile(t, nil, nil)
680
		w := createRequest(t, s.CreateHandler, api.CreateRequest{
681
682
683
684
			Name:     "test",
			Files:    map[string]string{"test.gguf": digest},
			Template: "{{ Prompt }}",
			Stream:   &stream,
Josh's avatar
Josh committed
685
		})
Michael Yang's avatar
lint  
Michael Yang committed
686

Josh's avatar
Josh committed
687
688
689
690
		if w.Code != http.StatusBadRequest {
			t.Fatalf("expected status code 400, actual %d", w.Code)
		}
	})
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
func TestCreateAndShowRemoteModel(t *testing.T) {
	gin.SetMode(gin.TestMode)

	var s Server

	w := createRequest(t, s.CreateHandler, api.CreateRequest{
		Model:      "test",
		From:       "bob",
		RemoteHost: "https://ollama.com",
		Info: map[string]any{
			"capabilities":       []string{"completion", "tools", "thinking"},
			"model_family":       "gptoss",
			"context_length":     131072,
			"embedding_length":   2880,
			"quantization_level": "MXFP4",
			"parameter_size":     "20.9B",
		},
		Stream: &stream,
	})

	if w.Code != http.StatusOK {
		t.Fatalf("exected status code 200, actual %d", w.Code)
	}

	w = createRequest(t, s.ShowHandler, api.ShowRequest{Model: "test"})
	if w.Code != http.StatusOK {
		t.Fatalf("exected status code 200, actual %d", w.Code)
	}

	var resp api.ShowResponse
	if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
		t.Fatal(err)
	}

	expectedDetails := api.ModelDetails{
		ParentModel:       "",
		Format:            "",
		Family:            "gptoss",
		Families:          []string{"gptoss"},
		ParameterSize:     "20.9B",
		QuantizationLevel: "MXFP4",
	}

	if !reflect.DeepEqual(resp.Details, expectedDetails) {
		t.Errorf("model details: expected %#v, actual %#v", expectedDetails, resp.Details)
	}

	expectedCaps := []model.Capability{
		model.Capability("completion"),
		model.Capability("tools"),
		model.Capability("thinking"),
	}

	if !slices.Equal(resp.Capabilities, expectedCaps) {
		t.Errorf("capabilities: expected %#v, actual %#v", expectedCaps, resp.Capabilities)
	}

	v, ok := resp.ModelInfo["gptoss.context_length"]
	ctxlen := v.(float64)
	if !ok || int(ctxlen) != 131072 {
		t.Errorf("context len: expected %d, actual %d", 131072, int(ctxlen))
	}

	v, ok = resp.ModelInfo["gptoss.embedding_length"]
	embedlen := v.(float64)
	if !ok || int(embedlen) != 2880 {
		t.Errorf("embed len: expected %d, actual %d", 2880, int(embedlen))
	}

	fmt.Printf("resp = %#v\n", resp)
}

765
func TestCreateLicenses(t *testing.T) {
766
767
	gin.SetMode(gin.TestMode)

768
769
770
771
	p := t.TempDir()
	t.Setenv("OLLAMA_MODELS", p)
	var s Server

772
	_, digest := createBinFile(t, nil, nil)
773
	w := createRequest(t, s.CreateHandler, api.CreateRequest{
774
775
776
777
		Name:    "test",
		Files:   map[string]string{"test.gguf": digest},
		License: []string{"MIT", "Apache-2.0"},
		Stream:  &stream,
778
779
780
781
782
783
784
785
786
787
788
789
	})

	if w.Code != http.StatusOK {
		t.Fatalf("expected status code 200, actual %d", w.Code)
	}

	checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
		filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
	})

	checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
		filepath.Join(p, "blobs", "sha256-2af71558e438db0b73a20beab92dc278a94e1bbe974c00c1a33e3ab62d53a608"),
790
791
		filepath.Join(p, "blobs", "sha256-89a2116c3a82d6a97f59f748d86ed4417214353fd178ee54df418fde32495fad"),
		filepath.Join(p, "blobs", "sha256-a762f214df0d96c9a7b82f96da98d99ceb2776c88e3ea7ffa09d1e5835516ec6"),
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
		filepath.Join(p, "blobs", "sha256-e5dcffe836b6ec8a58e492419b550e65fb8cbdc308503979e5dacb33ac7ea3b7"),
	})

	mit, err := os.ReadFile(filepath.Join(p, "blobs", "sha256-e5dcffe836b6ec8a58e492419b550e65fb8cbdc308503979e5dacb33ac7ea3b7"))
	if err != nil {
		t.Fatal(err)
	}

	if string(mit) != "MIT" {
		t.Errorf("expected MIT, actual %s", mit)
	}

	apache, err := os.ReadFile(filepath.Join(p, "blobs", "sha256-2af71558e438db0b73a20beab92dc278a94e1bbe974c00c1a33e3ab62d53a608"))
	if err != nil {
		t.Fatal(err)
	}

	if string(apache) != "Apache-2.0" {
		t.Errorf("expected Apache-2.0, actual %s", apache)
	}
}
813
814

func TestCreateDetectTemplate(t *testing.T) {
815
816
	gin.SetMode(gin.TestMode)

817
818
819
820
821
	p := t.TempDir()
	t.Setenv("OLLAMA_MODELS", p)
	var s Server

	t.Run("matched", func(t *testing.T) {
Michael Yang's avatar
Michael Yang committed
822
		_, digest := createBinFile(t, ggml.KV{
823
824
			"tokenizer.chat_template": "{{ bos_token }}{% for message in messages %}{{'<|' + message['role'] + '|>' + '\n' + message['content'] + '<|end|>\n' }}{% endfor %}{% if add_generation_prompt %}{{ '<|assistant|>\n' }}{% else %}{{ eos_token }}{% endif %}",
		}, nil)
825
		w := createRequest(t, s.CreateHandler, api.CreateRequest{
826
827
			Name:   "test",
			Files:  map[string]string{"test.gguf": digest},
828
829
830
831
832
833
834
835
			Stream: &stream,
		})

		if w.Code != http.StatusOK {
			t.Fatalf("expected status code 200, actual %d", w.Code)
		}

		checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
836
			filepath.Join(p, "blobs", "sha256-0d79f567714c62c048378f2107fb332dabee0135d080c302d884317da9433cc5"),
837
			filepath.Join(p, "blobs", "sha256-3322a0c650c758b7386ff55629d27d07c07b6c3d3515e259dc3e5598c41e9f4e"),
838
			filepath.Join(p, "blobs", "sha256-35360843d0c84fb1506952a131bbef13cd2bb4a541251f22535170c05b56e672"),
839
			filepath.Join(p, "blobs", "sha256-a56c12acca8068cb6c335e237da6643e8a802a92959a63ad5bd17828e3b5e9b0"),
840
841
842
843
		})
	})

	t.Run("unmatched", func(t *testing.T) {
844
		_, digest := createBinFile(t, nil, nil)
845
		w := createRequest(t, s.CreateHandler, api.CreateRequest{
846
847
848
			Name:   "test",
			Files:  map[string]string{"test.gguf": digest},
			Stream: &stream,
849
850
851
852
853
854
855
		})

		if w.Code != http.StatusOK {
			t.Fatalf("expected status code 200, actual %d", w.Code)
		}

		checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
856
857
			filepath.Join(p, "blobs", "sha256-6bcdb8859d417753645538d7bbfbd7ca91a3f0c191aef5379c53c05e86b669dd"),
			filepath.Join(p, "blobs", "sha256-89a2116c3a82d6a97f59f748d86ed4417214353fd178ee54df418fde32495fad"),
858
859
860
		})
	})
}
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
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
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957

func TestDetectModelTypeFromFiles(t *testing.T) {
	t.Run("gguf file", func(t *testing.T) {
		_, digest := createBinFile(t, nil, nil)
		files := map[string]string{
			"model.gguf": digest,
		}

		modelType := detectModelTypeFromFiles(files)
		if modelType != "gguf" {
			t.Fatalf("expected model type 'gguf', got %q", modelType)
		}
	})

	t.Run("gguf file w/o extension", func(t *testing.T) {
		_, digest := createBinFile(t, nil, nil)
		files := map[string]string{
			fmt.Sprintf("%x", digest): digest,
		}

		modelType := detectModelTypeFromFiles(files)
		if modelType != "gguf" {
			t.Fatalf("expected model type 'gguf', got %q", modelType)
		}
	})

	t.Run("safetensors file", func(t *testing.T) {
		files := map[string]string{
			"model.safetensors": "sha256:abc123",
		}

		modelType := detectModelTypeFromFiles(files)
		if modelType != "safetensors" {
			t.Fatalf("expected model type 'safetensors', got %q", modelType)
		}
	})

	t.Run("unsupported file type", func(t *testing.T) {
		p := t.TempDir()
		t.Setenv("OLLAMA_MODELS", p)

		data := []byte("12345678")
		digest := fmt.Sprintf("sha256:%x", sha256.Sum256(data))
		if err := os.MkdirAll(filepath.Join(p, "blobs"), 0o755); err != nil {
			t.Fatal(err)
		}

		f, err := os.Create(filepath.Join(p, "blobs", fmt.Sprintf("sha256-%s", strings.TrimPrefix(digest, "sha256:"))))
		if err != nil {
			t.Fatal(err)
		}
		defer f.Close()

		if _, err := f.Write(data); err != nil {
			t.Fatal(err)
		}

		files := map[string]string{
			"model.bin": digest,
		}

		modelType := detectModelTypeFromFiles(files)
		if modelType != "" {
			t.Fatalf("expected empty model type for unsupported file, got %q", modelType)
		}
	})

	t.Run("file with less than 4 bytes", func(t *testing.T) {
		p := t.TempDir()
		t.Setenv("OLLAMA_MODELS", p)

		data := []byte("123")
		digest := fmt.Sprintf("sha256:%x", sha256.Sum256(data))
		if err := os.MkdirAll(filepath.Join(p, "blobs"), 0o755); err != nil {
			t.Fatal(err)
		}

		f, err := os.Create(filepath.Join(p, "blobs", fmt.Sprintf("sha256-%s", strings.TrimPrefix(digest, "sha256:"))))
		if err != nil {
			t.Fatal(err)
		}
		defer f.Close()

		if _, err := f.Write(data); err != nil {
			t.Fatal(err)
		}

		files := map[string]string{
			"noext": digest,
		}

		modelType := detectModelTypeFromFiles(files)
		if modelType != "" {
			t.Fatalf("expected empty model type for small file, got %q", modelType)
		}
	})
}