api_test.go 11.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//go:build integration

package integration

import (
	"bytes"
	"context"
	"fmt"
	"math/rand"
	"strings"
	"testing"
	"time"

	"github.com/ollama/ollama/api"
)

func TestAPIGenerate(t *testing.T) {
	initialTimeout := 60 * time.Second
	streamTimeout := 30 * time.Second
	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
	defer cancel()
	// Set up the test data
	req := api.GenerateRequest{
		Model:  smol,
25
		Prompt: blueSkyPrompt,
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
111
112
113
114
115
116
117
118
119
120
121
		Options: map[string]interface{}{
			"temperature": 0,
			"seed":        123,
		},
	}

	client, _, cleanup := InitServerConnection(ctx, t)
	defer cleanup()
	if err := PullIfMissing(ctx, client, req.Model); err != nil {
		t.Fatalf("pull failed %s", err)
	}

	tests := []struct {
		name   string
		stream bool
	}{
		{
			name:   "stream",
			stream: true,
		},
		{
			name:   "no_stream",
			stream: false,
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			stallTimer := time.NewTimer(initialTimeout)
			var buf bytes.Buffer
			fn := func(response api.GenerateResponse) error {
				// Fields that must always be present
				if response.Model == "" {
					t.Errorf("response missing model: %#v", response)
				}
				if response.Done {
					// Required fields for final updates:
					if response.DoneReason == "" && *req.Stream {
						// TODO - is the lack of done reason on non-stream a bug?
						t.Errorf("final response missing done_reason: %#v", response)
					}
					if response.Metrics.TotalDuration == 0 {
						t.Errorf("final response missing total_duration: %#v", response)
					}
					if response.Metrics.LoadDuration == 0 {
						t.Errorf("final response missing load_duration: %#v", response)
					}
					if response.Metrics.PromptEvalDuration == 0 {
						t.Errorf("final response missing prompt_eval_duration: %#v", response)
					}
					if response.Metrics.EvalCount == 0 {
						t.Errorf("final response missing eval_count: %#v", response)
					}
					if response.Metrics.EvalDuration == 0 {
						t.Errorf("final response missing eval_duration: %#v", response)
					}
					if len(response.Context) == 0 {
						t.Errorf("final response missing context: %#v", response)
					}

					// Note: caching can result in no prompt eval count, so this can't be verified reliably
					// if response.Metrics.PromptEvalCount == 0 {
					// 	t.Errorf("final response missing prompt_eval_count: %#v", response)
					// }

				} // else incremental response, nothing to check right now...
				buf.Write([]byte(response.Response))
				if !stallTimer.Reset(streamTimeout) {
					return fmt.Errorf("stall was detected while streaming response, aborting")
				}
				return nil
			}

			done := make(chan int)
			var genErr error
			go func() {
				req.Stream = &test.stream
				req.Options["seed"] = rand.Int() // bust cache for prompt eval results
				genErr = client.Generate(ctx, &req, fn)
				done <- 0
			}()

			select {
			case <-stallTimer.C:
				if buf.Len() == 0 {
					t.Errorf("generate never started.  Timed out after :%s", initialTimeout.String())
				} else {
					t.Errorf("generate stalled.  Response so far:%s", buf.String())
				}
			case <-done:
				if genErr != nil {
					t.Fatalf("failed with %s request prompt %s ", req.Model, req.Prompt)
				}
				// Verify the response contains the expected data
				response := buf.String()
				atLeastOne := false
122
				for _, resp := range blueSkyExpected {
123
124
125
126
127
128
					if strings.Contains(strings.ToLower(response), resp) {
						atLeastOne = true
						break
					}
				}
				if !atLeastOne {
129
					t.Errorf("none of %v found in %s", blueSkyExpected, response)
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
				}
			case <-ctx.Done():
				t.Error("outer test context done while waiting for generate")
			}
		})
	}

	// Validate PS while we're at it...
	resp, err := client.ListRunning(ctx)
	if err != nil {
		t.Fatalf("list models API error: %s", err)
	}
	if resp == nil || len(resp.Models) == 0 {
		t.Fatalf("list models API returned empty list while model should still be loaded")
	}
	// Find the model we just loaded and verify some attributes
	found := false
	for _, model := range resp.Models {
		if strings.Contains(model.Name, req.Model) {
			found = true
			if model.Model == "" {
				t.Errorf("model field omitted: %#v", model)
			}
			if model.Size == 0 {
				t.Errorf("size omitted: %#v", model)
			}
			if model.Digest == "" {
				t.Errorf("digest omitted: %#v", model)
			}
			verifyModelDetails(t, model.Details)
			var nilTime time.Time
			if model.ExpiresAt == nilTime {
				t.Errorf("expires_at omitted: %#v", model)
			}
			// SizeVRAM could be zero.
		}
	}
	if !found {
		t.Errorf("unable to locate running model: %#v", resp)
	}
}

func TestAPIChat(t *testing.T) {
	initialTimeout := 60 * time.Second
	streamTimeout := 30 * time.Second
	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
	defer cancel()
	// Set up the test data
	req := api.ChatRequest{
		Model: smol,
		Messages: []api.Message{
			{
				Role:    "user",
183
				Content: blueSkyPrompt,
184
185
186
187
188
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
245
246
247
248
249
250
251
252
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
			},
		},
		Options: map[string]interface{}{
			"temperature": 0,
			"seed":        123,
		},
	}

	client, _, cleanup := InitServerConnection(ctx, t)
	defer cleanup()
	if err := PullIfMissing(ctx, client, req.Model); err != nil {
		t.Fatalf("pull failed %s", err)
	}

	tests := []struct {
		name   string
		stream bool
	}{
		{
			name:   "stream",
			stream: true,
		},
		{
			name:   "no_stream",
			stream: false,
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			stallTimer := time.NewTimer(initialTimeout)
			var buf bytes.Buffer
			fn := func(response api.ChatResponse) error {
				// Fields that must always be present
				if response.Model == "" {
					t.Errorf("response missing model: %#v", response)
				}
				if response.Done {
					// Required fields for final updates:
					var nilTime time.Time
					if response.CreatedAt == nilTime {
						t.Errorf("final response missing total_duration: %#v", response)
					}
					if response.DoneReason == "" {
						t.Errorf("final response missing done_reason: %#v", response)
					}
					if response.Metrics.TotalDuration == 0 {
						t.Errorf("final response missing total_duration: %#v", response)
					}
					if response.Metrics.LoadDuration == 0 {
						t.Errorf("final response missing load_duration: %#v", response)
					}
					if response.Metrics.PromptEvalDuration == 0 {
						t.Errorf("final response missing prompt_eval_duration: %#v", response)
					}
					if response.Metrics.EvalCount == 0 {
						t.Errorf("final response missing eval_count: %#v", response)
					}
					if response.Metrics.EvalDuration == 0 {
						t.Errorf("final response missing eval_duration: %#v", response)
					}

					if response.Metrics.PromptEvalCount == 0 {
						t.Errorf("final response missing prompt_eval_count: %#v", response)
					}
				} // else incremental response, nothing to check right now...
				buf.Write([]byte(response.Message.Content))
				if !stallTimer.Reset(streamTimeout) {
					return fmt.Errorf("stall was detected while streaming response, aborting")
				}
				return nil
			}

			done := make(chan int)
			var genErr error
			go func() {
				req.Stream = &test.stream
				req.Options["seed"] = rand.Int() // bust cache for prompt eval results
				genErr = client.Chat(ctx, &req, fn)
				done <- 0
			}()

			select {
			case <-stallTimer.C:
				if buf.Len() == 0 {
					t.Errorf("chat never started.  Timed out after :%s", initialTimeout.String())
				} else {
					t.Errorf("chat stalled.  Response so far:%s", buf.String())
				}
			case <-done:
				if genErr != nil {
					t.Fatalf("failed with %s request prompt %v", req.Model, req.Messages)
				}
				// Verify the response contains the expected data
				response := buf.String()
				atLeastOne := false
280
				for _, resp := range blueSkyExpected {
281
282
283
284
285
286
					if strings.Contains(strings.ToLower(response), resp) {
						atLeastOne = true
						break
					}
				}
				if !atLeastOne {
287
					t.Errorf("none of %v found in %s", blueSkyExpected, response)
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
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
				}
			case <-ctx.Done():
				t.Error("outer test context done while waiting for chat")
			}
		})
	}
}

func TestAPIListModels(t *testing.T) {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	client, _, cleanup := InitServerConnection(ctx, t)
	defer cleanup()

	// Make sure we have at least one model so an empty list can be considered a failure
	if err := PullIfMissing(ctx, client, smol); err != nil {
		t.Fatalf("pull failed %s", err)
	}

	resp, err := client.List(ctx)
	if err != nil {
		t.Fatalf("unable to list models: %s", err)
	}
	if len(resp.Models) == 0 {
		t.Fatalf("list should not be empty")
	}
	model := resp.Models[0]
	if model.Name == "" {
		t.Errorf("first model name empty: %#v", model)
	}
	var nilTime time.Time
	if model.ModifiedAt == nilTime {
		t.Errorf("first model modified_at empty: %#v", model)
	}
	if model.Size == 0 {
		t.Errorf("first model size empty: %#v", model)
	}
	if model.Digest == "" {
		t.Errorf("first model digest empty: %#v", model)
	}
	verifyModelDetails(t, model.Details)
}

func verifyModelDetails(t *testing.T, details api.ModelDetails) {
	if details.Format == "" {
		t.Errorf("first model details.format empty: %#v", details)
	}
	if details.Family == "" {
		t.Errorf("first model details.family empty: %#v", details)
	}
	if details.ParameterSize == "" {
		t.Errorf("first model details.parameter_size empty: %#v", details)
	}
	if details.QuantizationLevel == "" {
		t.Errorf("first model details.quantization_level empty: %#v", details)
	}
}

func TestAPIShowModel(t *testing.T) {
	modelName := "llama3.2"
	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
	defer cancel()
	client, _, cleanup := InitServerConnection(ctx, t)
	defer cleanup()

	if err := PullIfMissing(ctx, client, modelName); err != nil {
		t.Fatalf("pull failed %s", err)
	}
	resp, err := client.Show(ctx, &api.ShowRequest{Name: modelName})
	if err != nil {
		t.Fatalf("unable to show model: %s", err)
	}
	if resp.License == "" {
		t.Errorf("%s missing license: %#v", modelName, resp)
	}
	if resp.Modelfile == "" {
		t.Errorf("%s missing modelfile: %#v", modelName, resp)
	}
	if resp.Parameters == "" {
		t.Errorf("%s missing parameters: %#v", modelName, resp)
	}
	if resp.Template == "" {
		t.Errorf("%s missing template: %#v", modelName, resp)
	}
	// llama3 omits system
	verifyModelDetails(t, resp.Details)
	// llama3 ommits messages
	if len(resp.ModelInfo) == 0 {
		t.Errorf("%s missing model_info: %#v", modelName, resp)
	}
	// llama3 omits projectors
	var nilTime time.Time
	if resp.ModifiedAt == nilTime {
		t.Errorf("%s missing modified_at: %#v", modelName, resp)
	}
}

func TestAPIEmbeddings(t *testing.T) {
	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
	defer cancel()
	client, _, cleanup := InitServerConnection(ctx, t)
	defer cleanup()
	req := api.EmbeddingRequest{
391
		Model:  libraryEmbedModels[0],
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
		Prompt: "why is the sky blue?",
		Options: map[string]interface{}{
			"temperature": 0,
			"seed":        123,
		},
	}

	if err := PullIfMissing(ctx, client, req.Model); err != nil {
		t.Fatalf("pull failed %s", err)
	}

	resp, err := client.Embeddings(ctx, &req)
	if err != nil {
		t.Fatalf("embeddings call failed %s", err)
	}
	if len(resp.Embedding) == 0 {
		t.Errorf("zero length embedding response")
	}
}