routes_test.go 13.8 KB
Newer Older
mashun1's avatar
v1  
mashun1 committed
1
2
3
4
5
6
7
8
9
package server

import (
	"bytes"
	"context"
	"encoding/binary"
	"encoding/json"
	"fmt"
	"io"
xuxzh1's avatar
init  
xuxzh1 committed
10
	"math"
mashun1's avatar
v1  
mashun1 committed
11
12
13
14
15
16
17
18
	"net/http"
	"net/http/httptest"
	"os"
	"sort"
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"
xuxzh1's avatar
init  
xuxzh1 committed
19
	"github.com/stretchr/testify/require"
mashun1's avatar
v1  
mashun1 committed
20
21

	"github.com/ollama/ollama/api"
xuxzh1's avatar
init  
xuxzh1 committed
22
23
	"github.com/ollama/ollama/llm"
	"github.com/ollama/ollama/openai"
mashun1's avatar
v1  
mashun1 committed
24
	"github.com/ollama/ollama/parser"
xuxzh1's avatar
init  
xuxzh1 committed
25
	"github.com/ollama/ollama/types/model"
mashun1's avatar
v1  
mashun1 committed
26
27
28
29
30
31
32
	"github.com/ollama/ollama/version"
)

func createTestFile(t *testing.T, name string) string {
	t.Helper()

	f, err := os.CreateTemp(t.TempDir(), name)
xuxzh1's avatar
init  
xuxzh1 committed
33
	require.NoError(t, err)
mashun1's avatar
v1  
mashun1 committed
34
35
36
	defer f.Close()

	err = binary.Write(f, binary.LittleEndian, []byte("GGUF"))
xuxzh1's avatar
init  
xuxzh1 committed
37
	require.NoError(t, err)
mashun1's avatar
v1  
mashun1 committed
38
39

	err = binary.Write(f, binary.LittleEndian, uint32(3))
xuxzh1's avatar
init  
xuxzh1 committed
40
	require.NoError(t, err)
mashun1's avatar
v1  
mashun1 committed
41
42

	err = binary.Write(f, binary.LittleEndian, uint64(0))
xuxzh1's avatar
init  
xuxzh1 committed
43
	require.NoError(t, err)
mashun1's avatar
v1  
mashun1 committed
44
45

	err = binary.Write(f, binary.LittleEndian, uint64(0))
xuxzh1's avatar
init  
xuxzh1 committed
46
	require.NoError(t, err)
mashun1's avatar
v1  
mashun1 committed
47
48
49
50
51
52
53
54
55
56
57
58
59
60

	return f.Name()
}

func Test_Routes(t *testing.T) {
	type testCase struct {
		Name     string
		Method   string
		Path     string
		Setup    func(t *testing.T, req *http.Request)
		Expected func(t *testing.T, resp *http.Response)
	}

	createTestModel := func(t *testing.T, name string) {
xuxzh1's avatar
init  
xuxzh1 committed
61
62
		t.Helper()

mashun1's avatar
v1  
mashun1 committed
63
64
65
66
		fname := createTestFile(t, "ollama-model")

		r := strings.NewReader(fmt.Sprintf("FROM %s\nPARAMETER seed 42\nPARAMETER top_p 0.9\nPARAMETER stop foo\nPARAMETER stop bar", fname))
		modelfile, err := parser.ParseFile(r)
xuxzh1's avatar
init  
xuxzh1 committed
67
		require.NoError(t, err)
mashun1's avatar
v1  
mashun1 committed
68
69
70
		fn := func(resp api.ProgressResponse) {
			t.Logf("Status: %s", resp.Status)
		}
xuxzh1's avatar
init  
xuxzh1 committed
71
72
		err = CreateModel(context.TODO(), model.ParseName(name), "", "", modelfile, fn)
		require.NoError(t, err)
mashun1's avatar
v1  
mashun1 committed
73
74
75
76
77
78
79
80
81
82
83
	}

	testCases := []testCase{
		{
			Name:   "Version Handler",
			Method: http.MethodGet,
			Path:   "/api/version",
			Setup: func(t *testing.T, req *http.Request) {
			},
			Expected: func(t *testing.T, resp *http.Response) {
				contentType := resp.Header.Get("Content-Type")
xuxzh1's avatar
init  
xuxzh1 committed
84
				assert.Equal(t, "application/json; charset=utf-8", contentType)
mashun1's avatar
v1  
mashun1 committed
85
				body, err := io.ReadAll(resp.Body)
xuxzh1's avatar
init  
xuxzh1 committed
86
				require.NoError(t, err)
mashun1's avatar
v1  
mashun1 committed
87
88
89
90
91
92
93
94
95
				assert.Equal(t, fmt.Sprintf(`{"version":"%s"}`, version.Version), string(body))
			},
		},
		{
			Name:   "Tags Handler (no tags)",
			Method: http.MethodGet,
			Path:   "/api/tags",
			Expected: func(t *testing.T, resp *http.Response) {
				contentType := resp.Header.Get("Content-Type")
xuxzh1's avatar
init  
xuxzh1 committed
96
				assert.Equal(t, "application/json; charset=utf-8", contentType)
mashun1's avatar
v1  
mashun1 committed
97
				body, err := io.ReadAll(resp.Body)
xuxzh1's avatar
init  
xuxzh1 committed
98
				require.NoError(t, err)
mashun1's avatar
v1  
mashun1 committed
99
100
101
102

				var modelList api.ListResponse

				err = json.Unmarshal(body, &modelList)
xuxzh1's avatar
init  
xuxzh1 committed
103
				require.NoError(t, err)
mashun1's avatar
v1  
mashun1 committed
104
105

				assert.NotNil(t, modelList.Models)
xuxzh1's avatar
init  
xuxzh1 committed
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
				assert.Empty(t, len(modelList.Models))
			},
		},
		{
			Name:   "openai empty list",
			Method: http.MethodGet,
			Path:   "/v1/models",
			Expected: func(t *testing.T, resp *http.Response) {
				contentType := resp.Header.Get("Content-Type")
				assert.Equal(t, "application/json", contentType)
				body, err := io.ReadAll(resp.Body)
				require.NoError(t, err)

				var modelList openai.ListCompletion
				err = json.Unmarshal(body, &modelList)
				require.NoError(t, err)

				assert.Equal(t, "list", modelList.Object)
				assert.Empty(t, modelList.Data)
mashun1's avatar
v1  
mashun1 committed
125
126
127
128
129
130
131
132
133
134
135
			},
		},
		{
			Name:   "Tags Handler (yes tags)",
			Method: http.MethodGet,
			Path:   "/api/tags",
			Setup: func(t *testing.T, req *http.Request) {
				createTestModel(t, "test-model")
			},
			Expected: func(t *testing.T, resp *http.Response) {
				contentType := resp.Header.Get("Content-Type")
xuxzh1's avatar
init  
xuxzh1 committed
136
				assert.Equal(t, "application/json; charset=utf-8", contentType)
mashun1's avatar
v1  
mashun1 committed
137
				body, err := io.ReadAll(resp.Body)
xuxzh1's avatar
init  
xuxzh1 committed
138
139
140
				require.NoError(t, err)

				assert.NotContains(t, string(body), "expires_at")
mashun1's avatar
v1  
mashun1 committed
141
142
143

				var modelList api.ListResponse
				err = json.Unmarshal(body, &modelList)
xuxzh1's avatar
init  
xuxzh1 committed
144
				require.NoError(t, err)
mashun1's avatar
v1  
mashun1 committed
145

xuxzh1's avatar
init  
xuxzh1 committed
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
				assert.Len(t, modelList.Models, 1)
				assert.Equal(t, "test-model:latest", modelList.Models[0].Name)
			},
		},
		{
			Name:   "openai list models with tags",
			Method: http.MethodGet,
			Path:   "/v1/models",
			Expected: func(t *testing.T, resp *http.Response) {
				contentType := resp.Header.Get("Content-Type")
				assert.Equal(t, "application/json", contentType)
				body, err := io.ReadAll(resp.Body)
				require.NoError(t, err)

				var modelList openai.ListCompletion
				err = json.Unmarshal(body, &modelList)
				require.NoError(t, err)

				assert.Len(t, modelList.Data, 1)
				assert.Equal(t, "test-model:latest", modelList.Data[0].Id)
				assert.Equal(t, "library", modelList.Data[0].OwnedBy)
mashun1's avatar
v1  
mashun1 committed
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
			},
		},
		{
			Name:   "Create Model Handler",
			Method: http.MethodPost,
			Path:   "/api/create",
			Setup: func(t *testing.T, req *http.Request) {
				fname := createTestFile(t, "ollama-model")

				stream := false
				createReq := api.CreateRequest{
					Name:      "t-bone",
					Modelfile: fmt.Sprintf("FROM %s", fname),
					Stream:    &stream,
				}
				jsonData, err := json.Marshal(createReq)
xuxzh1's avatar
init  
xuxzh1 committed
183
				require.NoError(t, err)
mashun1's avatar
v1  
mashun1 committed
184
185
186
187
188
189
190

				req.Body = io.NopCloser(bytes.NewReader(jsonData))
			},
			Expected: func(t *testing.T, resp *http.Response) {
				contentType := resp.Header.Get("Content-Type")
				assert.Equal(t, "application/json", contentType)
				_, err := io.ReadAll(resp.Body)
xuxzh1's avatar
init  
xuxzh1 committed
191
192
				require.NoError(t, err)
				assert.Equal(t, 200, resp.StatusCode)
mashun1's avatar
v1  
mashun1 committed
193
194

				model, err := GetModel("t-bone")
xuxzh1's avatar
init  
xuxzh1 committed
195
				require.NoError(t, err)
mashun1's avatar
v1  
mashun1 committed
196
197
198
199
200
201
202
203
204
205
206
207
208
209
				assert.Equal(t, "t-bone:latest", model.ShortName)
			},
		},
		{
			Name:   "Copy Model Handler",
			Method: http.MethodPost,
			Path:   "/api/copy",
			Setup: func(t *testing.T, req *http.Request) {
				createTestModel(t, "hamshank")
				copyReq := api.CopyRequest{
					Source:      "hamshank",
					Destination: "beefsteak",
				}
				jsonData, err := json.Marshal(copyReq)
xuxzh1's avatar
init  
xuxzh1 committed
210
				require.NoError(t, err)
mashun1's avatar
v1  
mashun1 committed
211
212
213
214
215

				req.Body = io.NopCloser(bytes.NewReader(jsonData))
			},
			Expected: func(t *testing.T, resp *http.Response) {
				model, err := GetModel("beefsteak")
xuxzh1's avatar
init  
xuxzh1 committed
216
				require.NoError(t, err)
mashun1's avatar
v1  
mashun1 committed
217
218
219
220
221
222
223
224
225
226
227
				assert.Equal(t, "beefsteak:latest", model.ShortName)
			},
		},
		{
			Name:   "Show Model Handler",
			Method: http.MethodPost,
			Path:   "/api/show",
			Setup: func(t *testing.T, req *http.Request) {
				createTestModel(t, "show-model")
				showReq := api.ShowRequest{Model: "show-model"}
				jsonData, err := json.Marshal(showReq)
xuxzh1's avatar
init  
xuxzh1 committed
228
				require.NoError(t, err)
mashun1's avatar
v1  
mashun1 committed
229
230
231
232
				req.Body = io.NopCloser(bytes.NewReader(jsonData))
			},
			Expected: func(t *testing.T, resp *http.Response) {
				contentType := resp.Header.Get("Content-Type")
xuxzh1's avatar
init  
xuxzh1 committed
233
				assert.Equal(t, "application/json; charset=utf-8", contentType)
mashun1's avatar
v1  
mashun1 committed
234
				body, err := io.ReadAll(resp.Body)
xuxzh1's avatar
init  
xuxzh1 committed
235
				require.NoError(t, err)
mashun1's avatar
v1  
mashun1 committed
236
237
238

				var showResp api.ShowResponse
				err = json.Unmarshal(body, &showResp)
xuxzh1's avatar
init  
xuxzh1 committed
239
				require.NoError(t, err)
mashun1's avatar
v1  
mashun1 committed
240
241
242
243
244
245
246
247
248
249
250
251
252
253

				var params []string
				paramsSplit := strings.Split(showResp.Parameters, "\n")
				for _, p := range paramsSplit {
					params = append(params, strings.Join(strings.Fields(p), " "))
				}
				sort.Strings(params)
				expectedParams := []string{
					"seed 42",
					"stop \"bar\"",
					"stop \"foo\"",
					"top_p 0.9",
				}
				assert.Equal(t, expectedParams, params)
xuxzh1's avatar
init  
xuxzh1 committed
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
295
296
297
298
299
300
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
				assert.InDelta(t, 0, showResp.ModelInfo["general.parameter_count"], 1e-9, "Parameter count should be 0")
			},
		},
		{
			Name:   "openai retrieve model handler",
			Method: http.MethodGet,
			Path:   "/v1/models/show-model",
			Expected: func(t *testing.T, resp *http.Response) {
				contentType := resp.Header.Get("Content-Type")
				assert.Equal(t, "application/json", contentType)
				body, err := io.ReadAll(resp.Body)
				require.NoError(t, err)

				var retrieveResp api.RetrieveModelResponse
				err = json.Unmarshal(body, &retrieveResp)
				require.NoError(t, err)

				assert.Equal(t, "show-model", retrieveResp.Id)
				assert.Equal(t, "library", retrieveResp.OwnedBy)
			},
		},
		{
			Name:   "Embed Handler Empty Input",
			Method: http.MethodPost,
			Path:   "/api/embed",
			Setup: func(t *testing.T, req *http.Request) {
				embedReq := api.EmbedRequest{
					Model: "t-bone",
					Input: "",
				}
				jsonData, err := json.Marshal(embedReq)
				require.NoError(t, err)
				req.Body = io.NopCloser(bytes.NewReader(jsonData))
			},
			Expected: func(t *testing.T, resp *http.Response) {
				contentType := resp.Header.Get("Content-Type")
				if contentType != "application/json; charset=utf-8" {
					t.Fatalf("expected content type application/json; charset=utf-8, got %s", contentType)
				}
				body, err := io.ReadAll(resp.Body)
				if err != nil {
					t.Fatal(err)
				}

				var embedResp api.EmbedResponse
				err = json.Unmarshal(body, &embedResp)
				if err != nil {
					t.Fatal(err)
				}

				if embedResp.Model != "t-bone" {
					t.Fatalf("expected model t-bone, got %s", embedResp.Model)
				}

				if embedResp.Embeddings == nil {
					t.Fatalf("expected embeddings to not be nil, got %v", embedResp.Embeddings)
				}

				if len(embedResp.Embeddings) != 0 {
					t.Fatalf("expected embeddings to be empty, got %v", embedResp.Embeddings)
				}
			},
		},
		{
			Name:   "Embed Handler Invalid Input",
			Method: http.MethodPost,
			Path:   "/api/embed",
			Setup: func(t *testing.T, req *http.Request) {
				embedReq := api.EmbedRequest{
					Model: "t-bone",
					Input: 2,
				}
				jsonData, err := json.Marshal(embedReq)
				require.NoError(t, err)
				req.Body = io.NopCloser(bytes.NewReader(jsonData))
			},
			Expected: func(t *testing.T, resp *http.Response) {
				contentType := resp.Header.Get("Content-Type")
				if contentType != "application/json; charset=utf-8" {
					t.Fatalf("expected content type application/json; charset=utf-8, got %s", contentType)
				}
				_, err := io.ReadAll(resp.Body)
				if err != nil {
					t.Fatal(err)
				}

				if resp.StatusCode != http.StatusBadRequest {
					t.Fatalf("expected status code 400, got %d", resp.StatusCode)
				}
mashun1's avatar
v1  
mashun1 committed
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
			},
		},
	}

	t.Setenv("OLLAMA_MODELS", t.TempDir())

	s := &Server{}
	router := s.GenerateRoutes()

	httpSrv := httptest.NewServer(router)
	t.Cleanup(httpSrv.Close)

	for _, tc := range testCases {
		t.Run(tc.Name, func(t *testing.T) {
			u := httpSrv.URL + tc.Path
			req, err := http.NewRequestWithContext(context.TODO(), tc.Method, u, nil)
xuxzh1's avatar
init  
xuxzh1 committed
359
			require.NoError(t, err)
mashun1's avatar
v1  
mashun1 committed
360
361
362
363
364
365

			if tc.Setup != nil {
				tc.Setup(t, req)
			}

			resp, err := httpSrv.Client().Do(req)
xuxzh1's avatar
init  
xuxzh1 committed
366
			require.NoError(t, err)
mashun1's avatar
v1  
mashun1 committed
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
			defer resp.Body.Close()

			if tc.Expected != nil {
				tc.Expected(t, resp)
			}
		})
	}
}

func TestCase(t *testing.T) {
	t.Setenv("OLLAMA_MODELS", t.TempDir())

	cases := []string{
		"mistral",
		"llama3:latest",
		"library/phi3:q4_0",
		"registry.ollama.ai/library/gemma:q5_K_M",
		// TODO: host:port currently fails on windows (#4107)
		// "localhost:5000/alice/bob:latest",
	}

	var s Server
	for _, tt := range cases {
		t.Run(tt, func(t *testing.T) {
			w := createRequest(t, s.CreateModelHandler, api.CreateRequest{
				Name:      tt,
xuxzh1's avatar
init  
xuxzh1 committed
393
				Modelfile: fmt.Sprintf("FROM %s", createBinFile(t, nil, nil)),
mashun1's avatar
v1  
mashun1 committed
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
				Stream:    &stream,
			})

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

			expect, err := json.Marshal(map[string]string{"error": "a model with that name already exists"})
			if err != nil {
				t.Fatal(err)
			}

			t.Run("create", func(t *testing.T) {
				w = createRequest(t, s.CreateModelHandler, api.CreateRequest{
					Name:      strings.ToUpper(tt),
xuxzh1's avatar
init  
xuxzh1 committed
409
					Modelfile: fmt.Sprintf("FROM %s", createBinFile(t, nil, nil)),
mashun1's avatar
v1  
mashun1 committed
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
					Stream:    &stream,
				})

				if w.Code != http.StatusBadRequest {
					t.Fatalf("expected status 500 got %d", w.Code)
				}

				if !bytes.Equal(w.Body.Bytes(), expect) {
					t.Fatalf("expected error %s got %s", expect, w.Body.String())
				}
			})

			t.Run("pull", func(t *testing.T) {
				w := createRequest(t, s.PullModelHandler, api.PullRequest{
					Name:   strings.ToUpper(tt),
					Stream: &stream,
				})

				if w.Code != http.StatusBadRequest {
					t.Fatalf("expected status 500 got %d", w.Code)
				}

				if !bytes.Equal(w.Body.Bytes(), expect) {
					t.Fatalf("expected error %s got %s", expect, w.Body.String())
				}
			})

			t.Run("copy", func(t *testing.T) {
				w := createRequest(t, s.CopyModelHandler, api.CopyRequest{
					Source:      tt,
					Destination: strings.ToUpper(tt),
				})

				if w.Code != http.StatusBadRequest {
					t.Fatalf("expected status 500 got %d", w.Code)
				}

				if !bytes.Equal(w.Body.Bytes(), expect) {
					t.Fatalf("expected error %s got %s", expect, w.Body.String())
				}
			})
		})
	}
}
xuxzh1's avatar
init  
xuxzh1 committed
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
521
522
523
524

func TestShow(t *testing.T) {
	t.Setenv("OLLAMA_MODELS", t.TempDir())

	var s Server

	createRequest(t, s.CreateModelHandler, api.CreateRequest{
		Name: "show-model",
		Modelfile: fmt.Sprintf(
			"FROM %s\nFROM %s",
			createBinFile(t, llm.KV{"general.architecture": "test"}, nil),
			createBinFile(t, llm.KV{"general.architecture": "clip"}, nil),
		),
	})

	w := createRequest(t, s.ShowModelHandler, api.ShowRequest{
		Name: "show-model",
	})

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

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

	if resp.ModelInfo["general.architecture"] != "test" {
		t.Fatal("Expected model architecture to be 'test', but got", resp.ModelInfo["general.architecture"])
	}

	if resp.ProjectorInfo["general.architecture"] != "clip" {
		t.Fatal("Expected projector architecture to be 'clip', but got", resp.ProjectorInfo["general.architecture"])
	}
}

func TestNormalize(t *testing.T) {
	type testCase struct {
		input []float32
	}

	testCases := []testCase{
		{input: []float32{1}},
		{input: []float32{0, 1, 2, 3}},
		{input: []float32{0.1, 0.2, 0.3}},
		{input: []float32{-0.1, 0.2, 0.3, -0.4}},
		{input: []float32{0, 0, 0}},
	}

	isNormalized := func(vec []float32) (res bool) {
		sum := 0.0
		for _, v := range vec {
			sum += float64(v * v)
		}
		if math.Abs(sum-1) > 1e-6 {
			return sum == 0
		} else {
			return true
		}
	}

	for _, tc := range testCases {
		t.Run("", func(t *testing.T) {
			normalized := normalize(tc.input)
			if !isNormalized(normalized) {
				t.Errorf("Vector %v is not normalized", tc.input)
			}
		})
	}
}