utils_test.go 20.5 KB
Newer Older
1
2
3
4
5
6
7
//go:build integration

package integration

import (
	"bytes"
	"context"
Daniel Hiltgen's avatar
Daniel Hiltgen committed
8
	"errors"
9
10
11
	"fmt"
	"io"
	"log/slog"
12
	"math"
13
14
15
	"math/rand"
	"net"
	"net/http"
Daniel Hiltgen's avatar
Daniel Hiltgen committed
16
	"net/url"
17
	"os"
18
	"os/exec"
19
20
21
22
23
24
25
26
	"path/filepath"
	"runtime"
	"strconv"
	"strings"
	"sync"
	"testing"
	"time"

27
	"github.com/ollama/ollama/api"
28
	"github.com/ollama/ollama/format"
29
30
)

31
var (
32
33
	smol   = "llama3.2:1b"
	stream = false
34
35
)

36
37
38
39
40
var (
	started = time.Now()

	// Note: add newer models at the top of the list to test them first
	ollamaEngineChatModels = []string{
41
		"ministral-3",
42
		"qwen3-coder:30b",
43
		"gpt-oss:20b",
44
45
46
47
48
49
50
		"gemma3n:e2b",
		"mistral-small3.2:latest",
		"deepseek-r1:1.5b",
		"llama3.2-vision:latest",
		"qwen2.5-coder:latest",
		"qwen2.5vl:3b",
		"qwen3:0.6b", // dense
51
		"qwen3:1.7b", // dense
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
		"qwen3:30b",  // MOE
		"gemma3:1b",
		"llama3.1:latest",
		"llama3.2:latest",
		"gemma2:latest",
		"minicpm-v:latest",    // arch=qwen2
		"granite-code:latest", // arch=llama
	}
	llamaRunnerChatModels = []string{
		"mistral:latest",
		"falcon3:latest",
		"granite3-moe:latest",
		"command-r:latest",
		"nemotron-mini:latest",
		"phi3.5:latest",
		"solar-pro:latest",
		"internlm2:latest",
		"codellama:latest", // arch=llama
		"phi3:latest",
		"falcon2:latest",
		"gemma:latest",
		"llama2:latest",
		"nous-hermes:latest",
		"orca-mini:latest",
		"qwen:latest",
		"stablelm2:latest", // Predictions are off, crashes on small VRAM GPUs
		"falcon:latest",
	}
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
122
123
124
125
126
127
128
129
130
131
132
133

	// Some library models are quite large - ensure large VRAM and sufficient disk space
	// before running scenarios based on this set
	libraryChatModels = []string{
		"alfred",
		"athene-v2",
		"aya-expanse",
		"aya",
		"bakllava",
		"bespoke-minicheck",
		"codebooga",
		"codegeex4",
		"codegemma",
		"codellama",
		"codeqwen",
		"codestral",
		"codeup",
		"cogito",
		"command-a",
		"command-r-plus",
		"command-r",
		"command-r7b-arabic",
		"command-r7b",
		"dbrx",
		"deepcoder",
		"deepscaler",
		"deepseek-coder-v2",
		"deepseek-coder",
		"deepseek-llm",
		"deepseek-r1",
		// "deepseek-v2.5", // requires 155 GB VRAM
		"deepseek-v2",
		// "deepseek-v3", // requires 482 GB VRAM
		"devstral",
		"dolphin-llama3",
		"dolphin-mistral",
		"dolphin-mixtral",
		"dolphin-phi",
		"dolphin3",
		"dolphincoder",
		"duckdb-nsql",
		"everythinglm",
		"exaone-deep",
		"exaone3.5",
		"falcon",
		"falcon2",
		"falcon3",
		"firefunction-v2",
		"gemma",
		"gemma2",
		"gemma3",
		"gemma3n",
		"glm4",
		"goliath",
134
		"gpt-oss:20b",
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
		"granite-code",
		"granite3-dense",
		"granite3-guardian",
		"granite3-moe",
		"granite3.1-dense",
		"granite3.1-moe",
		"granite3.2-vision",
		"granite3.2",
		"granite3.3",
		"hermes3",
		"internlm2",
		"llama-guard3",
		"llama-pro",
		"llama2-chinese",
		"llama2-uncensored",
		"llama2",
		"llama3-chatqa",
		"llama3-gradient",
		"llama3-groq-tool-use",
		"llama3.1",
		"llama3.2-vision",
		"llama3.2",
		"llama3.3",
		"llama3",
		"llama4",
		"llava-llama3",
		"llava-phi3",
		"llava",
		"magicoder",
		"magistral",
		"marco-o1",
		"mathstral",
		"meditron",
		"medllama2",
		"megadolphin",
		"minicpm-v",
171
		"ministral-3",
172
173
174
175
176
177
178
179
180
181
182
183
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
		"mistral-large",
		"mistral-nemo",
		"mistral-openorca",
		"mistral-small",
		"mistral-small3.1",
		"mistral-small3.2",
		"mistral",
		"mistrallite",
		"mixtral",
		"moondream",
		"nemotron-mini",
		"nemotron",
		"neural-chat",
		"nexusraven",
		"notus",
		"nous-hermes",
		"nous-hermes2-mixtral",
		"nous-hermes2",
		"nuextract",
		"olmo2",
		"open-orca-platypus2",
		"openchat",
		"opencoder",
		"openhermes",
		"openthinker",
		"orca-mini",
		"orca2",
		// "phi", // unreliable
		"phi3.5",
		"phi3",
		"phi4-mini-reasoning",
		"phi4-mini",
		"phi4-reasoning",
		"phi4",
		"phind-codellama",
		"qwen",
		"qwen2-math",
		"qwen2.5-coder",
		"qwen2.5",
		"qwen2.5vl",
		"qwen2",
		"qwen3:0.6b", // dense
		"qwen3:30b",  // MOE
		"qwq",
		"r1-1776",
		"reader-lm",
		"reflection",
		"sailor2",
		"samantha-mistral",
		"shieldgemma",
		"smallthinker",
		"smollm",
		"smollm2",
		"solar-pro",
		"solar",
		"sqlcoder",
		"stable-beluga",
		"stable-code",
		"stablelm-zephyr",
		"stablelm2",
		"starcoder",
		"starcoder2",
		"starling-lm",
		"tinydolphin",
		"tinyllama",
		"tulu3",
		"vicuna",
		"wizard-math",
		"wizard-vicuna-uncensored",
		"wizard-vicuna",
		"wizardcoder",
		"wizardlm-uncensored",
		"wizardlm2",
		"xwinlm",
		"yarn-llama2",
		"yarn-mistral",
		"yi-coder",
		"yi",
		"zephyr",
	}
	libraryEmbedModels = []string{
253
254
255
		"qwen3-embedding",
		"embeddinggemma",
		"nomic-embed-text",
256
257
258
259
260
261
262
263
264
		"all-minilm",
		"bge-large",
		"bge-m3",
		"granite-embedding",
		"mxbai-embed-large",
		"paraphrase-multilingual",
		"snowflake-arctic-embed",
		"snowflake-arctic-embed2",
	}
265
266
267
268
269
270
271
272
273
274
	libraryToolsModels = []string{
		"qwen3-vl",
		"gpt-oss:20b",
		"gpt-oss:120b",
		"qwen3",
		"llama3.1",
		"llama3.2",
		"mistral",
		"qwen2.5",
		"qwen2",
275
		"ministral-3",
276
277
278
279
280
281
		"mistral-nemo",
		"mistral-small",
		"mixtral:8x22b",
		"qwq",
		"granite3.3",
	}
282
283
284
285
286
287
288
289
290
291
292
293
294

	blueSkyPrompt   = "why is the sky blue? Be brief but factual in your reply"
	blueSkyExpected = []string{"rayleigh", "scatter", "atmosphere", "nitrogen", "oxygen", "wavelength", "interact"}

	rainbowPrompt    = "how do rainbows form? Be brief but factual in your reply"
	rainbowFollowups = []string{
		"Explain the physics involved in them.  Be breif in your reply",
		"Explain the chemistry involved in them.  Be breif in your reply",
		"What are common myths related to them? Be brief in your reply",
		"Can they form if there is no rain?  Be breif in your reply",
		"Can they form if there are no clouds?  Be breif in your reply",
		"Do they happen on other planets? Be brief in your reply",
	}
295
	rainbowExpected = []string{"water", "droplet", "mist", "glow", "refract", "reflect", "scatter", "particles", "wave", "color", "spectrum", "raindrop", "atmosphere", "frequency", "shower", "sky", "shimmer", "light", "storm", "sunny", "sunburst", "phenomenon", "mars", "venus", "jupiter"}
296
297
)

298
func init() {
299
300
	logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}))
	slog.SetDefault(logger)
301
	custom := os.Getenv("OLLAMA_TEST_DEFAULT_MODEL")
302
	if custom != "" {
303
		slog.Info("setting default test model to " + custom)
304
305
		smol = custom
	}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
306
307
}

308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
func FindPort() string {
	port := 0
	if a, err := net.ResolveTCPAddr("tcp", "localhost:0"); err == nil {
		var l *net.TCPListener
		if l, err = net.ListenTCP("tcp", a); err == nil {
			port = l.Addr().(*net.TCPAddr).Port
			l.Close()
		}
	}
	if port == 0 {
		port = rand.Intn(65535-49152) + 49152 // get a random port in the ephemeral range
	}
	return strconv.Itoa(port)
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
323
func GetTestEndpoint() (*api.Client, string) {
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
	defaultPort := "11434"
	ollamaHost := os.Getenv("OLLAMA_HOST")

	scheme, hostport, ok := strings.Cut(ollamaHost, "://")
	if !ok {
		scheme, hostport = "http", ollamaHost
	}

	// trim trailing slashes
	hostport = strings.TrimRight(hostport, "/")

	host, port, err := net.SplitHostPort(hostport)
	if err != nil {
		host, port = "127.0.0.1", defaultPort
		if ip := net.ParseIP(strings.Trim(hostport, "[]")); ip != nil {
			host = ip.String()
		} else if hostport != "" {
			host = hostport
		}
	}

345
	if os.Getenv("OLLAMA_TEST_EXISTING") == "" && runtime.GOOS != "windows" && port == defaultPort {
346
347
348
		port = FindPort()
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
349
350
351
352
353
354
355
356
	slog.Info("server connection", "host", host, "port", port)

	return api.NewClient(
		&url.URL{
			Scheme: scheme,
			Host:   net.JoinHostPort(host, port),
		},
		http.DefaultClient), fmt.Sprintf("%s:%s", host, port)
357
358
}

359
360
361
362
363
364
365
366
// Server lifecycle management
var (
	serverMutex sync.Mutex
	serverReady bool
	serverLog   bytes.Buffer
	serverDone  chan int
	serverCmd   *exec.Cmd
)
367

Daniel Hiltgen's avatar
Daniel Hiltgen committed
368
func startServer(t *testing.T, ctx context.Context, ollamaHost string) error {
369
370
371
	// Make sure the server has been built
	CLIName, err := filepath.Abs("../ollama")
	if err != nil {
372
		return fmt.Errorf("failed to get absolute path: %w", err)
373
374
375
376
377
378
379
	}

	if runtime.GOOS == "windows" {
		CLIName += ".exe"
	}
	_, err = os.Stat(CLIName)
	if err != nil {
380
		return fmt.Errorf("CLI missing, did you forget to 'go build .' first?  %w", err)
381
382
383
384
385
386
	}
	serverMutex.Lock()
	defer serverMutex.Unlock()
	if serverReady {
		return nil
	}
387
388
	serverDone = make(chan int)
	serverLog.Reset()
389
390
391

	if tmp := os.Getenv("OLLAMA_HOST"); tmp != ollamaHost {
		slog.Info("setting env", "OLLAMA_HOST", ollamaHost)
Michael Yang's avatar
Michael Yang committed
392
		t.Setenv("OLLAMA_HOST", ollamaHost)
393
394
	}

395
396
397
	serverCmd = exec.Command(CLIName, "serve")
	serverCmd.Stderr = &serverLog
	serverCmd.Stdout = &serverLog
398
	go func() {
399
400
401
		slog.Info("starting server", "url", ollamaHost)
		if err := serverCmd.Run(); err != nil {
			// "signal: killed" expected during normal shutdown
402
403
404
405
406
			if !strings.Contains(err.Error(), "signal") {
				slog.Info("failed to run server", "error", err)
			}
		}
		var code int
407
408
		if serverCmd.ProcessState != nil {
			code = serverCmd.ProcessState.ExitCode()
409
410
		}
		slog.Info("server exited")
411
		serverDone <- code
412
	}()
413
414
415

	serverReady = true
	return nil
416
417
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
418
func PullIfMissing(ctx context.Context, client *api.Client, modelName string) error {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
419
	slog.Info("checking status of model", "model", modelName)
420
421
	showReq := &api.ShowRequest{Name: modelName}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
422
423
	showCtx, cancel := context.WithDeadlineCause(
		ctx,
424
		time.Now().Add(20*time.Second),
Daniel Hiltgen's avatar
Daniel Hiltgen committed
425
426
427
428
429
430
431
432
433
		fmt.Errorf("show for existing model %s took too long", modelName),
	)
	defer cancel()
	_, err := client.Show(showCtx, showReq)
	var statusError api.StatusError
	switch {
	case errors.As(err, &statusError) && statusError.StatusCode == http.StatusNotFound:
		break
	case err != nil:
434
		return err
Daniel Hiltgen's avatar
Daniel Hiltgen committed
435
	default:
436
437
438
		slog.Info("model already present", "model", modelName)
		return nil
	}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
439
440
	slog.Info("model missing", "model", modelName)

441
	stallDuration := 60 * time.Second // This includes checksum verification, which can take a while on larger models, and slower systems
Daniel Hiltgen's avatar
Daniel Hiltgen committed
442
443
444
445
	stallTimer := time.NewTimer(stallDuration)
	fn := func(resp api.ProgressResponse) error {
		// fmt.Print(".")
		if !stallTimer.Reset(stallDuration) {
Michael Yang's avatar
lint  
Michael Yang committed
446
			return errors.New("stall was detected, aborting status reporting")
Daniel Hiltgen's avatar
Daniel Hiltgen committed
447
448
449
		}
		return nil
	}
450

Daniel Hiltgen's avatar
Daniel Hiltgen committed
451
	stream := true
452
453
	pullReq := &api.PullRequest{Name: modelName, Stream: &stream}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
454
	var pullError error
455

Daniel Hiltgen's avatar
Daniel Hiltgen committed
456
457
458
459
460
461
462
463
	done := make(chan int)
	go func() {
		pullError = client.Pull(ctx, pullReq, fn)
		done <- 0
	}()

	select {
	case <-stallTimer.C:
Michael Yang's avatar
lint  
Michael Yang committed
464
		return errors.New("download stalled")
Daniel Hiltgen's avatar
Daniel Hiltgen committed
465
466
	case <-done:
		return pullError
467
468
469
	}
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
470
471
var serverProcMutex sync.Mutex

Daniel Hiltgen's avatar
Daniel Hiltgen committed
472
473
474
475
// Returns an Client, the testEndpoint, and a cleanup function, fails the test on errors
// Starts the server if needed
func InitServerConnection(ctx context.Context, t *testing.T) (*api.Client, string, func()) {
	client, testEndpoint := GetTestEndpoint()
476
477
478
479
480
	cleanup := func() {}
	if os.Getenv("OLLAMA_TEST_EXISTING") == "" && runtime.GOOS != "windows" {
		var err error
		err = startServer(t, ctx, testEndpoint)
		if err != nil {
481
482
			t.Fatal(err)
		}
483
484
485
486
487
488
489
490
491
492
		cleanup = func() {
			serverMutex.Lock()
			defer serverMutex.Unlock()
			serverReady = false

			slog.Info("shutting down server")
			serverCmd.Process.Signal(os.Interrupt)
			slog.Info("waiting for server to exit")
			<-serverDone
			slog.Info("terminate complete")
Daniel Hiltgen's avatar
Daniel Hiltgen committed
493

Daniel Hiltgen's avatar
Daniel Hiltgen committed
494
495
			if t.Failed() {
				slog.Warn("SERVER LOG FOLLOWS")
496
				io.Copy(os.Stderr, &serverLog)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
497
				slog.Warn("END OF SERVER")
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
525
526
527
528
529
			slog.Info("cleanup complete", "failed", t.Failed())
		}
	}
	// Make sure server is online and healthy before returning
	for {
		select {
		case <-ctx.Done():
			t.Fatalf("context done before server ready: %v", ctx.Err())
			break
		default:
		}
		listCtx, cancel := context.WithDeadlineCause(
			ctx,
			time.Now().Add(10*time.Second),
			fmt.Errorf("list models took too long"),
		)
		defer cancel()
		models, err := client.ListRunning(listCtx)
		if err != nil {
			if runtime.GOOS == "windows" {
				t.Fatalf("did you forget to start the server: %v", err)
			}
			time.Sleep(10 * time.Millisecond)
			continue
		}
		if len(models.Models) > 0 {
			names := make([]string, len(models.Models))
			for i, m := range models.Models {
				names[i] = m.Name
			}
			slog.Info("currently loaded", "models", names)
530
		}
531
		break
532
	}
533
534

	return client, testEndpoint, cleanup
Daniel Hiltgen's avatar
Daniel Hiltgen committed
535
}
536

537
func ChatTestHelper(ctx context.Context, t *testing.T, req api.ChatRequest, anyResp []string) {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
538
539
	client, _, cleanup := InitServerConnection(ctx, t)
	defer cleanup()
540
	if err := PullIfMissing(ctx, client, req.Model); err != nil {
541
542
		t.Fatal(err)
	}
543
	DoChat(ctx, t, client, req, anyResp, 30*time.Second, 10*time.Second)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
544
}
545

546
func DoGenerate(ctx context.Context, t *testing.T, client *api.Client, genReq api.GenerateRequest, anyResp []string, initialTimeout, streamTimeout time.Duration) []int {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
547
548
	stallTimer := time.NewTimer(initialTimeout)
	var buf bytes.Buffer
549
	var context []int
Daniel Hiltgen's avatar
Daniel Hiltgen committed
550
551
552
553
	fn := func(response api.GenerateResponse) error {
		// fmt.Print(".")
		buf.Write([]byte(response.Response))
		if !stallTimer.Reset(streamTimeout) {
Michael Yang's avatar
lint  
Michael Yang committed
554
			return errors.New("stall was detected while streaming response, aborting")
Daniel Hiltgen's avatar
Daniel Hiltgen committed
555
		}
556
557
558
		if len(response.Context) > 0 {
			context = response.Context
		}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
559
		return nil
560
561
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
562
563
564
565
566
567
568
569
	stream := true
	genReq.Stream = &stream
	done := make(chan int)
	var genErr error
	go func() {
		genErr = client.Generate(ctx, &genReq, fn)
		done <- 0
	}()
570

571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
	var response string
	verify := func() {
		// Verify the response contains the expected data
		response = buf.String()
		atLeastOne := false
		for _, resp := range anyResp {
			if strings.Contains(strings.ToLower(response), resp) {
				atLeastOne = true
				break
			}
		}
		if !atLeastOne {
			t.Fatalf("%s: none of %v found in %s", genReq.Model, anyResp, response)
		}
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
587
588
589
590
591
592
593
594
	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:
595
596
		if genErr != nil && strings.Contains(genErr.Error(), "model requires more system memory") {
			slog.Warn("model is too large for the target test system", "model", genReq.Model, "error", genErr)
597
			return context
598
		}
599
600
601
		if genErr != nil {
			t.Fatalf("%s failed with %s request prompt %s", genErr, genReq.Model, genReq.Prompt)
		}
602
		verify()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
603
604
		slog.Info("test pass", "model", genReq.Model, "prompt", genReq.Prompt, "contains", anyResp, "response", response)
	case <-ctx.Done():
605
606
607
608
609
		// On slow systems, we might timeout before some models finish rambling, so check what we have so far to see
		// if it's considered a pass - the stallTimer will detect hangs, but we want to consider slow systems a pass
		// if they are still generating valid responses
		slog.Warn("outer test context done while waiting for generate")
		verify()
610
	}
611
	return context
Daniel Hiltgen's avatar
Daniel Hiltgen committed
612
}
613

Daniel Hiltgen's avatar
Daniel Hiltgen committed
614
// Generate a set of requests
615
// By default each request uses llama3.2 as the model
Daniel Hiltgen's avatar
Daniel Hiltgen committed
616
617
618
func GenerateRequests() ([]api.GenerateRequest, [][]string) {
	return []api.GenerateRequest{
			{
619
				Model:     smol,
620
				Prompt:    "why is the ocean blue? Be brief but factual in your reply",
Daniel Hiltgen's avatar
Daniel Hiltgen committed
621
622
				Stream:    &stream,
				KeepAlive: &api.Duration{Duration: 10 * time.Second},
Daniel Hiltgen's avatar
Daniel Hiltgen committed
623
			}, {
624
				Model:     smol,
625
				Prompt:    "why is the color of dirt brown? Be brief but factual in your reply",
Daniel Hiltgen's avatar
Daniel Hiltgen committed
626
627
				Stream:    &stream,
				KeepAlive: &api.Duration{Duration: 10 * time.Second},
Daniel Hiltgen's avatar
Daniel Hiltgen committed
628
			}, {
629
				Model:     smol,
630
				Prompt:    rainbowPrompt,
Daniel Hiltgen's avatar
Daniel Hiltgen committed
631
632
				Stream:    &stream,
				KeepAlive: &api.Duration{Duration: 10 * time.Second},
Daniel Hiltgen's avatar
Daniel Hiltgen committed
633
			}, {
634
				Model:     smol,
635
				Prompt:    "what is the origin of independence day? Be brief but factual in your reply",
Daniel Hiltgen's avatar
Daniel Hiltgen committed
636
637
				Stream:    &stream,
				KeepAlive: &api.Duration{Duration: 10 * time.Second},
Daniel Hiltgen's avatar
Daniel Hiltgen committed
638
			}, {
639
				Model:     smol,
640
				Prompt:    "what is the composition of air? Be brief but factual in your reply",
Daniel Hiltgen's avatar
Daniel Hiltgen committed
641
642
				Stream:    &stream,
				KeepAlive: &api.Duration{Duration: 10 * time.Second},
Daniel Hiltgen's avatar
Daniel Hiltgen committed
643
644
645
			},
		},
		[][]string{
646
647
			{"sunlight", "scatter", "interact", "color", "surface", "depth", "red", "orange", "yellow", "absorb", "wavelength", "water", "molecule"},
			{"soil", "organic", "earth", "black", "tan", "chemical", "processes", "pigment", "particle", "iron oxide", "rust", "air", "water", "wet", "mixture", "mixing", "mineral", "element", "decomposed", "matter", "wavelength"},
648
			rainbowExpected,
Michael Yang's avatar
Michael Yang committed
649
			{"fourth", "july", "declaration", "independence"},
650
			{"nitrogen", "oxygen", "carbon", "dioxide", "water", "vapor", "fluid", "particles", "gas"},
651
		}
652
}
653

654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
func DoChat(ctx context.Context, t *testing.T, client *api.Client, req api.ChatRequest, anyResp []string, initialTimeout, streamTimeout time.Duration) *api.Message {
	stallTimer := time.NewTimer(initialTimeout)
	var buf bytes.Buffer
	role := "assistant"
	fn := func(response api.ChatResponse) error {
		// fmt.Print(".")
		role = response.Message.Role
		buf.Write([]byte(response.Message.Content))
		if !stallTimer.Reset(streamTimeout) {
			return errors.New("stall was detected while streaming response, aborting")
		}
		return nil
	}

	stream := true
	req.Stream = &stream
	done := make(chan int)
	var genErr error
	go func() {
		genErr = client.Chat(ctx, &req, fn)
		done <- 0
	}()

677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
	var response string
	verify := func() {
		// Verify the response contains the expected data
		response = buf.String()
		atLeastOne := false
		for _, resp := range anyResp {
			if strings.Contains(strings.ToLower(response), resp) {
				atLeastOne = true
				break
			}
		}
		if !atLeastOne {
			t.Fatalf("%s: none of %v found in \"%s\" -- request was:%v", req.Model, anyResp, response, req.Messages)
		}
	}

693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
	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 && strings.Contains(genErr.Error(), "model requires more system memory") {
			slog.Warn("model is too large for the target test system", "model", req.Model, "error", genErr)
			return nil
		}
		if genErr != nil {
			t.Fatalf("%s failed with %s request prompt %v", genErr, req.Model, req.Messages)
		}
708
		verify()
709
710
		slog.Info("test pass", "model", req.Model, "messages", req.Messages, "contains", anyResp, "response", response)
	case <-ctx.Done():
711
712
713
714
715
		// On slow systems, we might timeout before some models finish rambling, so check what we have so far to see
		// if it's considered a pass - the stallTimer will detect hangs, but we want to consider slow systems a pass
		// if they are still generating valid responses
		slog.Warn("outer test context done while waiting for chat")
		verify()
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
	}
	return &api.Message{Role: role, Content: buf.String()}
}

func ChatRequests() ([]api.ChatRequest, [][]string) {
	genReqs, results := GenerateRequests()
	reqs := make([]api.ChatRequest, len(genReqs))
	// think := api.ThinkValue{Value: "low"}
	for i := range reqs {
		reqs[i].Model = genReqs[i].Model
		reqs[i].Stream = genReqs[i].Stream
		reqs[i].KeepAlive = genReqs[i].KeepAlive
		// reqs[i].Think = &think
		reqs[i].Messages = []api.Message{
			{
				Role:    "user",
				Content: genReqs[i].Prompt,
			},
		}
	}
	return reqs, results
}

739
740
741
742
func skipUnderMinVRAM(t *testing.T, gb uint64) {
	// TODO use info API in the future
	if s := os.Getenv("OLLAMA_MAX_VRAM"); s != "" {
		maxVram, err := strconv.ParseUint(s, 10, 64)
743
744
745
		if err != nil {
			t.Fatal(err)
		}
746
747
748
749
750
751
		// Don't hammer on small VRAM cards...
		if maxVram < gb*format.GibiByte {
			t.Skip("skipping with small VRAM to avoid timeouts")
		}
	}
}
752

753
754
// Skip if the target model isn't X% GPU loaded to avoid excessive runtime
func skipIfNotGPULoaded(ctx context.Context, t *testing.T, client *api.Client, model string, minPercent int) {
755
756
757
758
759
760
761
	gpuPercent := getGPUPercent(ctx, t, client, model)
	if gpuPercent < minPercent {
		t.Skip(fmt.Sprintf("test requires minimum %d%% GPU load, but model %s only has %d%%", minPercent, model, gpuPercent))
	}
}

func getGPUPercent(ctx context.Context, t *testing.T, client *api.Client, model string) int {
762
763
764
765
766
767
768
	models, err := client.ListRunning(ctx)
	if err != nil {
		t.Fatalf("failed to list running models: %s", err)
	}
	loaded := []string{}
	for _, m := range models.Models {
		loaded = append(loaded, m.Name)
769
770
771
772
773
774
775
776
		if strings.Contains(model, ":") {
			if m.Name != model {
				continue
			}
		} else if strings.Contains(m.Name, ":") {
			if !strings.HasPrefix(m.Name, model+":") {
				continue
			}
777
778
779
780
781
782
783
784
785
786
787
788
789
790
		}
		gpuPercent := 0
		switch {
		case m.SizeVRAM == 0:
			gpuPercent = 0
		case m.SizeVRAM == m.Size:
			gpuPercent = 100
		case m.SizeVRAM > m.Size || m.Size == 0:
			t.Logf("unexpected size detected: %d", m.SizeVRAM)
		default:
			sizeCPU := m.Size - m.SizeVRAM
			cpuPercent := math.Round(float64(sizeCPU) / float64(m.Size) * 110)
			gpuPercent = int(100 - cpuPercent)
		}
791
		return gpuPercent
792
	}
793
794
	t.Fatalf("model %s not loaded - actually loaded: %v", model, loaded)
	return 0
795
796
}

797
798
799
800
801
802
803
804
805
806
func getTimeouts(t *testing.T) (soft time.Duration, hard time.Duration) {
	deadline, hasDeadline := t.Deadline()
	if !hasDeadline {
		return 8 * time.Minute, 10 * time.Minute
	} else if deadline.Compare(time.Now().Add(2*time.Minute)) <= 0 {
		t.Skip("too little time")
		return time.Duration(0), time.Duration(0)
	}
	return -time.Since(deadline.Add(-2 * time.Minute)), -time.Since(deadline.Add(-20 * time.Second))
}