cmd.go 29.1 KB
Newer Older
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1
2
3
package cmd

import (
4
	"archive/zip"
Michael Yang's avatar
Michael Yang committed
5
	"bytes"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
6
	"context"
7
8
	"crypto/ed25519"
	"crypto/rand"
Michael Yang's avatar
Michael Yang committed
9
	"crypto/sha256"
10
	"encoding/pem"
Michael Yang's avatar
Michael Yang committed
11
	"errors"
Bruce MacDonald's avatar
Bruce MacDonald committed
12
	"fmt"
Michael Yang's avatar
Michael Yang committed
13
	"io"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
14
	"log"
15
	"math"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
16
	"net"
17
	"net/http"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
18
	"os"
19
	"os/signal"
20
	"path/filepath"
21
	"regexp"
22
	"runtime"
Michael Yang's avatar
Michael Yang committed
23
	"strings"
24
	"syscall"
Michael Yang's avatar
Michael Yang committed
25
	"time"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
26

27
	"github.com/containerd/console"
28
	"github.com/mattn/go-runewidth"
Patrick Devine's avatar
Patrick Devine committed
29
	"github.com/olekukonko/tablewriter"
Michael Yang's avatar
Michael Yang committed
30
	"github.com/spf13/cobra"
31
	"golang.org/x/crypto/ssh"
32
	"golang.org/x/exp/slices"
33
	"golang.org/x/term"
Michael Yang's avatar
Michael Yang committed
34

35
	"github.com/ollama/ollama/api"
36
	"github.com/ollama/ollama/auth"
37
	"github.com/ollama/ollama/format"
38
	"github.com/ollama/ollama/parser"
39
40
	"github.com/ollama/ollama/progress"
	"github.com/ollama/ollama/server"
41
42
	"github.com/ollama/ollama/types/errtypes"
	"github.com/ollama/ollama/types/model"
43
	"github.com/ollama/ollama/version"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
44
45
)

46
func CreateHandler(cmd *cobra.Command, args []string) error {
47
	filename, _ := cmd.Flags().GetString("file")
48
49
50
51
52
	filename, err := filepath.Abs(filename)
	if err != nil {
		return err
	}

Michael Yang's avatar
Michael Yang committed
53
	client, err := api.ClientFromEnvironment()
54
55
56
	if err != nil {
		return err
	}
57

Michael Yang's avatar
Michael Yang committed
58
59
60
	p := progress.NewProgress(os.Stderr)
	defer p.Stop()

Michael Yang's avatar
Michael Yang committed
61
	f, err := os.Open(filename)
Michael Yang's avatar
Michael Yang committed
62
63
64
	if err != nil {
		return err
	}
Michael Yang's avatar
Michael Yang committed
65
	defer f.Close()
Michael Yang's avatar
Michael Yang committed
66

67
	modelfile, err := parser.ParseFile(f)
Michael Yang's avatar
Michael Yang committed
68
69
70
71
72
73
74
75
76
	if err != nil {
		return err
	}

	home, err := os.UserHomeDir()
	if err != nil {
		return err
	}

77
78
	status := "transferring model data"
	spinner := progress.NewSpinner(status)
79
80
	p.Add(status, spinner)

Michael Yang's avatar
Michael Yang committed
81
82
	for i := range modelfile.Commands {
		switch modelfile.Commands[i].Name {
Michael Yang's avatar
Michael Yang committed
83
		case "model", "adapter":
Michael Yang's avatar
Michael Yang committed
84
			path := modelfile.Commands[i].Args
Michael Yang's avatar
Michael Yang committed
85
86
87
88
89
90
			if path == "~" {
				path = home
			} else if strings.HasPrefix(path, "~/") {
				path = filepath.Join(home, path[2:])
			}

91
92
93
94
			if !filepath.IsAbs(path) {
				path = filepath.Join(filepath.Dir(filename), path)
			}

95
			fi, err := os.Stat(path)
Michael Yang's avatar
Michael Yang committed
96
			if errors.Is(err, os.ErrNotExist) && modelfile.Commands[i].Name == "model" {
Michael Yang's avatar
Michael Yang committed
97
				continue
Michael Yang's avatar
Michael Yang committed
98
99
100
101
			} else if err != nil {
				return err
			}

102
			if fi.IsDir() {
Michael Yang's avatar
Michael Yang committed
103
104
105
				// this is likely a safetensors or pytorch directory
				// TODO make this work w/ adapters
				tempfile, err := tempZipFiles(path)
106
107
108
				if err != nil {
					return err
				}
Michael Yang's avatar
Michael Yang committed
109
				defer os.RemoveAll(tempfile)
110

Michael Yang's avatar
Michael Yang committed
111
				path = tempfile
Michael Yang's avatar
Michael Yang committed
112
113
			}

114
115
			digest, err := createBlob(cmd, client, path)
			if err != nil {
Michael Yang's avatar
Michael Yang committed
116
117
118
				return err
			}

Michael Yang's avatar
Michael Yang committed
119
			modelfile.Commands[i].Args = "@" + digest
Michael Yang's avatar
Michael Yang committed
120
121
		}
	}
Michael Yang's avatar
Michael Yang committed
122

Michael Yang's avatar
Michael Yang committed
123
	bars := make(map[string]*progress.Bar)
124
	fn := func(resp api.ProgressResponse) error {
Michael Yang's avatar
Michael Yang committed
125
126
127
128
129
		if resp.Digest != "" {
			spinner.Stop()

			bar, ok := bars[resp.Digest]
			if !ok {
130
				bar = progress.NewBar(fmt.Sprintf("pulling %s...", resp.Digest[7:19]), resp.Total, resp.Completed)
Michael Yang's avatar
Michael Yang committed
131
132
133
134
135
136
137
138
139
140
141
142
143
				bars[resp.Digest] = bar
				p.Add(resp.Digest, bar)
			}

			bar.Set(resp.Completed)
		} else if status != resp.Status {
			spinner.Stop()

			status = resp.Status
			spinner = progress.NewSpinner(status)
			p.Add(status, spinner)
		}

144
145
146
		return nil
	}

147
	quantize, _ := cmd.Flags().GetString("quantize")
Michael Yang's avatar
Michael Yang committed
148

149
	request := api.CreateRequest{Name: args[0], Modelfile: modelfile.String(), Quantize: quantize}
Michael Yang's avatar
Michael Yang committed
150
	if err := client.Create(cmd.Context(), &request, fn); err != nil {
151
152
153
154
155
156
		return err
	}

	return nil
}

Michael Yang's avatar
Michael Yang committed
157
158
159
160
161
162
163
164
165
166
func tempZipFiles(path string) (string, error) {
	tempfile, err := os.CreateTemp("", "ollama-tf")
	if err != nil {
		return "", err
	}
	defer tempfile.Close()

	zipfile := zip.NewWriter(tempfile)
	defer zipfile.Close()

Michael Yang's avatar
Michael Yang committed
167
168
	detectContentType := func(path string) (string, error) {
		f, err := os.Open(path)
Michael Yang's avatar
Michael Yang committed
169
170
171
		if err != nil {
			return "", err
		}
Michael Yang's avatar
Michael Yang committed
172
		defer f.Close()
Michael Yang's avatar
Michael Yang committed
173

Michael Yang's avatar
Michael Yang committed
174
175
		var b bytes.Buffer
		b.Grow(512)
Michael Yang's avatar
Michael Yang committed
176

Michael Yang's avatar
Michael Yang committed
177
178
179
180
181
182
		if _, err := io.CopyN(&b, f, 512); err != nil && !errors.Is(err, io.EOF) {
			return "", err
		}

		contentType, _, _ := strings.Cut(http.DetectContentType(b.Bytes()), ";")
		return contentType, nil
Michael Yang's avatar
Michael Yang committed
183
184
	}

Michael Yang's avatar
Michael Yang committed
185
186
187
188
189
190
191
192
193
194
195
	glob := func(pattern, contentType string) ([]string, error) {
		matches, err := filepath.Glob(pattern)
		if err != nil {
			return nil, err
		}

		for _, safetensor := range matches {
			if ct, err := detectContentType(safetensor); err != nil {
				return nil, err
			} else if ct != contentType {
				return nil, fmt.Errorf("invalid content type: expected %s for %s", ct, safetensor)
Michael Yang's avatar
Michael Yang committed
196
			}
Michael Yang's avatar
Michael Yang committed
197
198
199
200
201
202
203
204
205
206
207
208
209
210
		}

		return matches, nil
	}

	var files []string
	if st, _ := glob(filepath.Join(path, "model*.safetensors"), "application/octet-stream"); len(st) > 0 {
		// safetensors files might be unresolved git lfs references; skip if they are
		// covers model-x-of-y.safetensors, model.fp32-x-of-y.safetensors, model.safetensors
		files = append(files, st...)
	} else if pt, _ := glob(filepath.Join(path, "pytorch_model*.bin"), "application/zip"); len(pt) > 0 {
		// pytorch files might also be unresolved git lfs references; skip if they are
		// covers pytorch_model-x-of-y.bin, pytorch_model.fp32-x-of-y.bin, pytorch_model.bin
		files = append(files, pt...)
Patrick Devine's avatar
Patrick Devine committed
211
	} else if pt, _ := glob(filepath.Join(path, "consolidated*.pth"), "application/zip"); len(pt) > 0 {
Michael Yang's avatar
Michael Yang committed
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
		// pytorch files might also be unresolved git lfs references; skip if they are
		// covers consolidated.x.pth, consolidated.pth
		files = append(files, pt...)
	} else {
		return "", errors.New("no safetensors or torch files found")
	}

	// add configuration files, json files are detected as text/plain
	js, err := glob(filepath.Join(path, "*.json"), "text/plain")
	if err != nil {
		return "", err
	}
	files = append(files, js...)

	if tks, _ := glob(filepath.Join(path, "tokenizer.model"), "application/octet-stream"); len(tks) > 0 {
		// add tokenizer.model if it exists, tokenizer.json is automatically picked up by the previous glob
		// tokenizer.model might be a unresolved git lfs reference; error if it is
		files = append(files, tks...)
	} else if tks, _ := glob(filepath.Join(path, "**/tokenizer.model"), "text/plain"); len(tks) > 0 {
		// some times tokenizer.model is in a subdirectory (e.g. meta-llama/Meta-Llama-3-8B)
		files = append(files, tks...)
	}

	for _, file := range files {
		f, err := os.Open(file)
		if err != nil {
Michael Yang's avatar
Michael Yang committed
238
239
			return "", err
		}
Michael Yang's avatar
Michael Yang committed
240
		defer f.Close()
Michael Yang's avatar
Michael Yang committed
241
242
243
244
245
246

		fi, err := f.Stat()
		if err != nil {
			return "", err
		}

Michael Yang's avatar
Michael Yang committed
247
		zfi, err := zip.FileInfoHeader(fi)
Michael Yang's avatar
Michael Yang committed
248
249
250
251
		if err != nil {
			return "", err
		}

Michael Yang's avatar
Michael Yang committed
252
		zf, err := zipfile.CreateHeader(zfi)
Michael Yang's avatar
Michael Yang committed
253
254
255
256
		if err != nil {
			return "", err
		}

Michael Yang's avatar
Michael Yang committed
257
		if _, err := io.Copy(zf, f); err != nil {
Michael Yang's avatar
Michael Yang committed
258
259
260
261
262
263
264
			return "", err
		}
	}

	return tempfile.Name(), nil
}

265
266
267
268
269
270
271
272
273
274
275
func createBlob(cmd *cobra.Command, client *api.Client, path string) (string, error) {
	bin, err := os.Open(path)
	if err != nil {
		return "", err
	}
	defer bin.Close()

	hash := sha256.New()
	if _, err := io.Copy(hash, bin); err != nil {
		return "", err
	}
276
277
278
279

	if _, err := bin.Seek(0, io.SeekStart); err != nil {
		return "", err
	}
280
281
282
283
284
285
286
287

	digest := fmt.Sprintf("sha256:%x", hash.Sum(nil))
	if err = client.CreateBlob(cmd.Context(), digest, bin); err != nil {
		return "", err
	}
	return digest, nil
}

288
func RunHandler(cmd *cobra.Command, args []string) error {
Michael Yang's avatar
Michael Yang committed
289
	client, err := api.ClientFromEnvironment()
290
291
292
293
	if err != nil {
		return err
	}

294
	name := args[0]
295

296
	// check if the model exists on the server
297
	show, err := client.Show(cmd.Context(), &api.ShowRequest{Name: name})
Michael Yang's avatar
Michael Yang committed
298
299
300
	var statusError api.StatusError
	switch {
	case errors.As(err, &statusError) && statusError.StatusCode == http.StatusNotFound:
301
		if err := PullHandler(cmd, []string{name}); err != nil {
302
			return err
Michael Yang's avatar
Michael Yang committed
303
		}
304
305
306
307
308

		show, err = client.Show(cmd.Context(), &api.ShowRequest{Name: name})
		if err != nil {
			return err
		}
Michael Yang's avatar
Michael Yang committed
309
310
	case err != nil:
		return err
311
312
	}

313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
	interactive := true

	opts := runOptions{
		Model:       args[0],
		WordWrap:    os.Getenv("TERM") == "xterm-256color",
		Options:     map[string]interface{}{},
		MultiModal:  slices.Contains(show.Details.Families, "clip"),
		ParentModel: show.Details.ParentModel,
	}

	format, err := cmd.Flags().GetString("format")
	if err != nil {
		return err
	}
	opts.Format = format

329
330
331
332
333
334
335
336
337
338
339
340
	keepAlive, err := cmd.Flags().GetString("keepalive")
	if err != nil {
		return err
	}
	if keepAlive != "" {
		d, err := time.ParseDuration(keepAlive)
		if err != nil {
			return err
		}
		opts.KeepAlive = &api.Duration{Duration: d}
	}

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
	prompts := args[1:]
	// prepend stdin to the prompt if provided
	if !term.IsTerminal(int(os.Stdin.Fd())) {
		in, err := io.ReadAll(os.Stdin)
		if err != nil {
			return err
		}

		prompts = append([]string{string(in)}, prompts...)
		opts.WordWrap = false
		interactive = false
	}
	opts.Prompt = strings.Join(prompts, " ")
	if len(prompts) > 0 {
		interactive = false
	}

	nowrap, err := cmd.Flags().GetBool("nowordwrap")
	if err != nil {
		return err
	}
	opts.WordWrap = !nowrap

	if !interactive {
		return generate(cmd, opts)
	}

	return generateInteractive(cmd, opts)
Bruce MacDonald's avatar
Bruce MacDonald committed
369
370
}

371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
func errFromUnknownKey(unknownKeyErr error) error {
	// find SSH public key in the error message
	sshKeyPattern := `ssh-\w+ [^\s"]+`
	re := regexp.MustCompile(sshKeyPattern)
	matches := re.FindStringSubmatch(unknownKeyErr.Error())

	if len(matches) > 0 {
		serverPubKey := matches[0]

		localPubKey, err := auth.GetPublicKey()
		if err != nil {
			return unknownKeyErr
		}

		if runtime.GOOS == "linux" && serverPubKey != localPubKey {
			// try the ollama service public key
			svcPubKey, err := os.ReadFile("/usr/share/ollama/.ollama/id_ed25519.pub")
			if err != nil {
				return unknownKeyErr
			}
			localPubKey = strings.TrimSpace(string(svcPubKey))
		}

		// check if the returned public key matches the local public key, this prevents adding a remote key to the user's account
		if serverPubKey != localPubKey {
			return unknownKeyErr
		}

		var msg strings.Builder
		msg.WriteString(unknownKeyErr.Error())
		msg.WriteString("\n\nYour ollama key is:\n")
		msg.WriteString(localPubKey)
		msg.WriteString("\nAdd your key at:\n")
		msg.WriteString("https://ollama.com/settings/keys")

		return errors.New(msg.String())
	}

	return unknownKeyErr
}

412
func PushHandler(cmd *cobra.Command, args []string) error {
Michael Yang's avatar
Michael Yang committed
413
	client, err := api.ClientFromEnvironment()
414
415
416
	if err != nil {
		return err
	}
417

418
419
420
421
422
	insecure, err := cmd.Flags().GetBool("insecure")
	if err != nil {
		return err
	}

Michael Yang's avatar
Michael Yang committed
423
424
425
426
	p := progress.NewProgress(os.Stderr)
	defer p.Stop()

	bars := make(map[string]*progress.Bar)
427
428
	var status string
	var spinner *progress.Spinner
Michael Yang's avatar
Michael Yang committed
429

430
	fn := func(resp api.ProgressResponse) error {
Michael Yang's avatar
Michael Yang committed
431
		if resp.Digest != "" {
432
433
434
			if spinner != nil {
				spinner.Stop()
			}
Michael Yang's avatar
Michael Yang committed
435
436
437

			bar, ok := bars[resp.Digest]
			if !ok {
438
				bar = progress.NewBar(fmt.Sprintf("pushing %s...", resp.Digest[7:19]), resp.Total, resp.Completed)
Michael Yang's avatar
Michael Yang committed
439
440
441
442
443
444
				bars[resp.Digest] = bar
				p.Add(resp.Digest, bar)
			}

			bar.Set(resp.Completed)
		} else if status != resp.Status {
445
446
447
			if spinner != nil {
				spinner.Stop()
			}
Michael Yang's avatar
Michael Yang committed
448
449
450
451
452
453

			status = resp.Status
			spinner = progress.NewSpinner(status)
			p.Add(status, spinner)
		}

454
455
456
		return nil
	}

Michael Yang's avatar
Michael Yang committed
457
	request := api.PushRequest{Name: args[0], Insecure: insecure}
Michael Yang's avatar
Michael Yang committed
458
	if err := client.Push(cmd.Context(), &request, fn); err != nil {
459
460
461
462
463
464
465
466
467
468
469
470
471
472
		if spinner != nil {
			spinner.Stop()
		}
		if strings.Contains(err.Error(), "access denied") {
			return errors.New("you are not authorized to push to this namespace, create the model under a namespace you own")
		}
		host := model.ParseName(args[0]).Host
		isOllamaHost := strings.HasSuffix(host, ".ollama.ai") || strings.HasSuffix(host, ".ollama.com")
		if strings.Contains(err.Error(), errtypes.UnknownOllamaKeyErrMsg) && isOllamaHost {
			// the user has not added their ollama key to ollama.com
			// re-throw an error with a more user-friendly message
			return errFromUnknownKey(err)
		}

Michael Yang's avatar
Michael Yang committed
473
474
475
		return err
	}

476
	spinner.Stop()
Michael Yang's avatar
Michael Yang committed
477
	return nil
478
479
}

480
func ListHandler(cmd *cobra.Command, args []string) error {
Michael Yang's avatar
Michael Yang committed
481
	client, err := api.ClientFromEnvironment()
482
483
484
	if err != nil {
		return err
	}
Patrick Devine's avatar
Patrick Devine committed
485

Michael Yang's avatar
Michael Yang committed
486
	models, err := client.List(cmd.Context())
Patrick Devine's avatar
Patrick Devine committed
487
488
489
490
491
492
493
	if err != nil {
		return err
	}

	var data [][]string

	for _, m := range models.Models {
Michael Yang's avatar
Michael Yang committed
494
		if len(args) == 0 || strings.HasPrefix(m.Name, args[0]) {
495
			data = append(data, []string{m.Name, m.Digest[:12], format.HumanBytes(m.Size), format.HumanTime(m.ModifiedAt, "Never")})
Michael Yang's avatar
Michael Yang committed
496
		}
Patrick Devine's avatar
Patrick Devine committed
497
498
499
	}

	table := tablewriter.NewWriter(os.Stdout)
Patrick Devine's avatar
Patrick Devine committed
500
	table.SetHeader([]string{"NAME", "ID", "SIZE", "MODIFIED"})
Patrick Devine's avatar
Patrick Devine committed
501
502
503
504
505
506
507
508
509
510
511
512
	table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
	table.SetAlignment(tablewriter.ALIGN_LEFT)
	table.SetHeaderLine(false)
	table.SetBorder(false)
	table.SetNoWhiteSpace(true)
	table.SetTablePadding("\t")
	table.AppendBulk(data)
	table.Render()

	return nil
}

513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
func ListRunningHandler(cmd *cobra.Command, args []string) error {
	client, err := api.ClientFromEnvironment()
	if err != nil {
		return err
	}

	models, err := client.ListRunning(cmd.Context())
	if err != nil {
		return err
	}

	var data [][]string

	for _, m := range models.Models {
		if len(args) == 0 || strings.HasPrefix(m.Name, args[0]) {
			var procStr string
			switch {
			case m.SizeVRAM == 0:
				procStr = "100% CPU"
			case m.SizeVRAM == m.Size:
				procStr = "100% GPU"
			case m.SizeVRAM > m.Size || m.Size == 0:
				procStr = "Unknown"
			default:
				sizeCPU := m.Size - m.SizeVRAM
				cpuPercent := math.Round(float64(sizeCPU) / float64(m.Size) * 100)
				procStr = fmt.Sprintf("%d%%/%d%% CPU/GPU", int(cpuPercent), int(100-cpuPercent))
			}
			data = append(data, []string{m.Name, m.Digest[:12], format.HumanBytes(m.Size), procStr, format.HumanTime(m.ExpiresAt, "Never")})
		}
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"NAME", "ID", "SIZE", "PROCESSOR", "UNTIL"})
	table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
	table.SetAlignment(tablewriter.ALIGN_LEFT)
	table.SetHeaderLine(false)
	table.SetBorder(false)
	table.SetNoWhiteSpace(true)
	table.SetTablePadding("\t")
	table.AppendBulk(data)
	table.Render()

	return nil
}

559
func DeleteHandler(cmd *cobra.Command, args []string) error {
Michael Yang's avatar
Michael Yang committed
560
	client, err := api.ClientFromEnvironment()
561
562
563
	if err != nil {
		return err
	}
564

565
566
	for _, name := range args {
		req := api.DeleteRequest{Name: name}
Michael Yang's avatar
Michael Yang committed
567
		if err := client.Delete(cmd.Context(), &req); err != nil {
568
569
570
			return err
		}
		fmt.Printf("deleted '%s'\n", name)
571
572
573
574
	}
	return nil
}

Patrick Devine's avatar
Patrick Devine committed
575
func ShowHandler(cmd *cobra.Command, args []string) error {
Michael Yang's avatar
Michael Yang committed
576
	client, err := api.ClientFromEnvironment()
Patrick Devine's avatar
Patrick Devine committed
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
	if err != nil {
		return err
	}

	if len(args) != 1 {
		return errors.New("missing model name")
	}

	license, errLicense := cmd.Flags().GetBool("license")
	modelfile, errModelfile := cmd.Flags().GetBool("modelfile")
	parameters, errParams := cmd.Flags().GetBool("parameters")
	system, errSystem := cmd.Flags().GetBool("system")
	template, errTemplate := cmd.Flags().GetBool("template")

	for _, boolErr := range []error{errLicense, errModelfile, errParams, errSystem, errTemplate} {
		if boolErr != nil {
			return errors.New("error retrieving flags")
		}
	}

	flagsSet := 0
	showType := ""

	if license {
		flagsSet++
		showType = "license"
	}

	if modelfile {
		flagsSet++
		showType = "modelfile"
	}

	if parameters {
		flagsSet++
		showType = "parameters"
	}

	if system {
		flagsSet++
		showType = "system"
	}

	if template {
		flagsSet++
		showType = "template"
	}

	if flagsSet > 1 {
626
		return errors.New("only one of '--license', '--modelfile', '--parameters', '--system', or '--template' can be specified")
Patrick Devine's avatar
Patrick Devine committed
627
	} else if flagsSet == 0 {
628
		return errors.New("one of '--license', '--modelfile', '--parameters', '--system', or '--template' must be specified")
Patrick Devine's avatar
Patrick Devine committed
629
630
	}

631
	req := api.ShowRequest{Name: args[0]}
Michael Yang's avatar
Michael Yang committed
632
	resp, err := client.Show(cmd.Context(), &req)
Patrick Devine's avatar
Patrick Devine committed
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
	if err != nil {
		return err
	}

	switch showType {
	case "license":
		fmt.Println(resp.License)
	case "modelfile":
		fmt.Println(resp.Modelfile)
	case "parameters":
		fmt.Println(resp.Parameters)
	case "system":
		fmt.Println(resp.System)
	case "template":
		fmt.Println(resp.Template)
	}

	return nil
}

Patrick Devine's avatar
Patrick Devine committed
653
func CopyHandler(cmd *cobra.Command, args []string) error {
Michael Yang's avatar
Michael Yang committed
654
	client, err := api.ClientFromEnvironment()
655
656
657
	if err != nil {
		return err
	}
Patrick Devine's avatar
Patrick Devine committed
658
659

	req := api.CopyRequest{Source: args[0], Destination: args[1]}
Michael Yang's avatar
Michael Yang committed
660
	if err := client.Copy(cmd.Context(), &req); err != nil {
Patrick Devine's avatar
Patrick Devine committed
661
662
663
664
665
666
		return err
	}
	fmt.Printf("copied '%s' to '%s'\n", args[0], args[1])
	return nil
}

667
func PullHandler(cmd *cobra.Command, args []string) error {
668
669
670
671
672
	insecure, err := cmd.Flags().GetBool("insecure")
	if err != nil {
		return err
	}

Michael Yang's avatar
Michael Yang committed
673
	client, err := api.ClientFromEnvironment()
674
675
676
	if err != nil {
		return err
	}
677

Michael Yang's avatar
Michael Yang committed
678
679
680
681
682
	p := progress.NewProgress(os.Stderr)
	defer p.Stop()

	bars := make(map[string]*progress.Bar)

683
684
	var status string
	var spinner *progress.Spinner
Michael Yang's avatar
Michael Yang committed
685

686
	fn := func(resp api.ProgressResponse) error {
Michael Yang's avatar
Michael Yang committed
687
		if resp.Digest != "" {
688
689
690
			if spinner != nil {
				spinner.Stop()
			}
Michael Yang's avatar
Michael Yang committed
691
692
693

			bar, ok := bars[resp.Digest]
			if !ok {
694
				bar = progress.NewBar(fmt.Sprintf("pulling %s...", resp.Digest[7:19]), resp.Total, resp.Completed)
Michael Yang's avatar
Michael Yang committed
695
696
697
698
699
700
				bars[resp.Digest] = bar
				p.Add(resp.Digest, bar)
			}

			bar.Set(resp.Completed)
		} else if status != resp.Status {
701
702
703
			if spinner != nil {
				spinner.Stop()
			}
Michael Yang's avatar
Michael Yang committed
704
705
706
707
708
709

			status = resp.Status
			spinner = progress.NewSpinner(status)
			p.Add(status, spinner)
		}

710
711
		return nil
	}
712

Michael Yang's avatar
Michael Yang committed
713
	request := api.PullRequest{Name: args[0], Insecure: insecure}
Michael Yang's avatar
Michael Yang committed
714
	if err := client.Pull(cmd.Context(), &request, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
715
716
717
718
		return err
	}

	return nil
Michael Yang's avatar
Michael Yang committed
719
720
}

721
722
type generateContextKey string

723
type runOptions struct {
724
725
726
727
728
729
730
731
732
733
734
	Model       string
	ParentModel string
	Prompt      string
	Messages    []api.Message
	WordWrap    bool
	Format      string
	System      string
	Template    string
	Images      []api.ImageData
	Options     map[string]interface{}
	MultiModal  bool
735
	KeepAlive   *api.Duration
736
737
}

738
739
740
741
742
743
744
745
746
type displayResponseState struct {
	lineLength int
	wordBuffer string
}

func displayResponse(content string, wordWrap bool, state *displayResponseState) {
	termWidth, _, _ := term.GetSize(int(os.Stdout.Fd()))
	if wordWrap && termWidth >= 10 {
		for _, ch := range content {
Josh Yan's avatar
Josh Yan committed
747
			if state.lineLength+1 > termWidth-5 {
Josh Yan's avatar
Josh Yan committed
748

Josh Yan's avatar
Josh Yan committed
749
				if runewidth.StringWidth(state.wordBuffer) > termWidth-10 {
750
751
752
753
754
755
756
					fmt.Printf("%s%c", state.wordBuffer, ch)
					state.wordBuffer = ""
					state.lineLength = 0
					continue
				}

				// backtrack the length of the last word and clear to the end of the line
757
				fmt.Printf("\x1b[%dD\x1b[K\n", runewidth.StringWidth(state.wordBuffer))
758
				fmt.Printf("%s%c", state.wordBuffer, ch)
759
760
761
				chWidth := runewidth.RuneWidth(ch)

				state.lineLength = runewidth.StringWidth(state.wordBuffer) + chWidth
762
763
			} else {
				fmt.Print(string(ch))
764
765
766
767
				state.lineLength += runewidth.RuneWidth(ch)
				if runewidth.RuneWidth(ch) >= 2 {
					state.wordBuffer = ""
					continue
Josh Yan's avatar
Josh Yan committed
768
				}
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836

				switch ch {
				case ' ':
					state.wordBuffer = ""
				case '\n':
					state.lineLength = 0
				default:
					state.wordBuffer += string(ch)
				}
			}
		}
	} else {
		fmt.Printf("%s%s", state.wordBuffer, content)
		if len(state.wordBuffer) > 0 {
			state.wordBuffer = ""
		}
	}
}

func chat(cmd *cobra.Command, opts runOptions) (*api.Message, error) {
	client, err := api.ClientFromEnvironment()
	if err != nil {
		return nil, err
	}

	p := progress.NewProgress(os.Stderr)
	defer p.StopAndClear()

	spinner := progress.NewSpinner("")
	p.Add("", spinner)

	cancelCtx, cancel := context.WithCancel(cmd.Context())
	defer cancel()

	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT)

	go func() {
		<-sigChan
		cancel()
	}()

	var state *displayResponseState = &displayResponseState{}
	var latest api.ChatResponse
	var fullResponse strings.Builder
	var role string

	fn := func(response api.ChatResponse) error {
		p.StopAndClear()

		latest = response

		role = response.Message.Role
		content := response.Message.Content
		fullResponse.WriteString(content)

		displayResponse(content, opts.WordWrap, state)

		return nil
	}

	req := &api.ChatRequest{
		Model:    opts.Model,
		Messages: opts.Messages,
		Format:   opts.Format,
		Options:  opts.Options,
	}

837
838
839
840
	if opts.KeepAlive != nil {
		req.KeepAlive = opts.KeepAlive
	}

841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
	if err := client.Chat(cancelCtx, req, fn); err != nil {
		if errors.Is(err, context.Canceled) {
			return nil, nil
		}
		return nil, err
	}

	if len(opts.Messages) > 0 {
		fmt.Println()
		fmt.Println()
	}

	verbose, err := cmd.Flags().GetBool("verbose")
	if err != nil {
		return nil, err
	}

	if verbose {
		latest.Summary()
	}

	return &api.Message{Role: role, Content: fullResponse.String()}, nil
}

func generate(cmd *cobra.Command, opts runOptions) error {
Michael Yang's avatar
Michael Yang committed
866
	client, err := api.ClientFromEnvironment()
Patrick Devine's avatar
Patrick Devine committed
867
	if err != nil {
868
		return err
Patrick Devine's avatar
Patrick Devine committed
869
	}
Michael Yang's avatar
Michael Yang committed
870

Michael Yang's avatar
Michael Yang committed
871
	p := progress.NewProgress(os.Stderr)
872
	defer p.StopAndClear()
873

Michael Yang's avatar
Michael Yang committed
874
875
876
	spinner := progress.NewSpinner("")
	p.Add("", spinner)

877
878
879
880
881
882
883
	var latest api.GenerateResponse

	generateContext, ok := cmd.Context().Value(generateContextKey("context")).([]int)
	if !ok {
		generateContext = []int{}
	}

Michael Yang's avatar
Michael Yang committed
884
	ctx, cancel := context.WithCancel(cmd.Context())
885
886
887
888
889
890
891
892
893
894
	defer cancel()

	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT)

	go func() {
		<-sigChan
		cancel()
	}()

895
	var state *displayResponseState = &displayResponseState{}
896

897
	fn := func(response api.GenerateResponse) error {
Michael Yang's avatar
Michael Yang committed
898
		p.StopAndClear()
899

Patrick Devine's avatar
Patrick Devine committed
900
		latest = response
901
		content := response.Response
902

903
		displayResponse(content, opts.WordWrap, state)
904

Patrick Devine's avatar
Patrick Devine committed
905
906
		return nil
	}
907

908
909
910
911
912
913
914
	if opts.MultiModal {
		opts.Prompt, opts.Images, err = extractFileData(opts.Prompt)
		if err != nil {
			return err
		}
	}

Michael Yang's avatar
Michael Yang committed
915
	request := api.GenerateRequest{
916
917
918
919
920
921
922
923
924
		Model:     opts.Model,
		Prompt:    opts.Prompt,
		Context:   generateContext,
		Images:    opts.Images,
		Format:    opts.Format,
		System:    opts.System,
		Template:  opts.Template,
		Options:   opts.Options,
		KeepAlive: opts.KeepAlive,
Michael Yang's avatar
Michael Yang committed
925
926
927
	}

	if err := client.Generate(ctx, &request, fn); err != nil {
928
		if errors.Is(err, context.Canceled) {
929
			return nil
930
		}
931
		return err
Patrick Devine's avatar
Patrick Devine committed
932
	}
933

934
	if opts.Prompt != "" {
Michael Yang's avatar
Michael Yang committed
935
936
		fmt.Println()
		fmt.Println()
Patrick Devine's avatar
Patrick Devine committed
937
	}
938

939
940
941
942
	if !latest.Done {
		return nil
	}

Patrick Devine's avatar
Patrick Devine committed
943
944
	verbose, err := cmd.Flags().GetBool("verbose")
	if err != nil {
945
		return err
Patrick Devine's avatar
Patrick Devine committed
946
	}
Michael Yang's avatar
Michael Yang committed
947

Patrick Devine's avatar
Patrick Devine committed
948
949
	if verbose {
		latest.Summary()
Michael Yang's avatar
Michael Yang committed
950
	}
Michael Yang's avatar
Michael Yang committed
951

Patrick Devine's avatar
Patrick Devine committed
952
953
954
	ctx = context.WithValue(cmd.Context(), generateContextKey("context"), latest.Context)
	cmd.SetContext(ctx)

955
	return nil
Michael Yang's avatar
Michael Yang committed
956
957
}

958
func RunServer(cmd *cobra.Command, _ []string) error {
959
960
	// retrieve the OLLAMA_HOST environment variable
	ollamaHost, err := api.GetOllamaHost()
Michael Yang's avatar
Michael Yang committed
961
	if err != nil {
962
		return err
Jeffrey Morgan's avatar
Jeffrey Morgan committed
963
	}
964

Michael Yang's avatar
Michael Yang committed
965
	if err := initializeKeypair(); err != nil {
966
967
968
		return err
	}

969
	ln, err := net.Listen("tcp", net.JoinHostPort(ollamaHost.Host, ollamaHost.Port))
970
971
972
	if err != nil {
		return err
	}
Jeffrey Morgan's avatar
Jeffrey Morgan committed
973

974
975
976
977
978
979
	err = server.Serve(ln)
	if errors.Is(err, http.ErrServerClosed) {
		return nil
	}

	return err
Jeffrey Morgan's avatar
Jeffrey Morgan committed
980
981
}

982
983
984
985
986
987
988
989
990
991
992
993
func initializeKeypair() error {
	home, err := os.UserHomeDir()
	if err != nil {
		return err
	}

	privKeyPath := filepath.Join(home, ".ollama", "id_ed25519")
	pubKeyPath := filepath.Join(home, ".ollama", "id_ed25519.pub")

	_, err = os.Stat(privKeyPath)
	if os.IsNotExist(err) {
		fmt.Printf("Couldn't find '%s'. Generating new private key.\n", privKeyPath)
Michael Yang's avatar
Michael Yang committed
994
		cryptoPublicKey, cryptoPrivateKey, err := ed25519.GenerateKey(rand.Reader)
995
996
997
998
		if err != nil {
			return err
		}

Michael Yang's avatar
Michael Yang committed
999
		privateKeyBytes, err := ssh.MarshalPrivateKey(cryptoPrivateKey, "")
1000
1001
1002
1003
		if err != nil {
			return err
		}

Michael Yang's avatar
Michael Yang committed
1004
		if err := os.MkdirAll(filepath.Dir(privKeyPath), 0o755); err != nil {
1005
1006
1007
			return fmt.Errorf("could not create directory %w", err)
		}

Michael Yang's avatar
Michael Yang committed
1008
		if err := os.WriteFile(privKeyPath, pem.EncodeToMemory(privateKeyBytes), 0o600); err != nil {
1009
1010
1011
			return err
		}

Michael Yang's avatar
Michael Yang committed
1012
		sshPublicKey, err := ssh.NewPublicKey(cryptoPublicKey)
1013
1014
1015
1016
		if err != nil {
			return err
		}

Michael Yang's avatar
Michael Yang committed
1017
		publicKeyBytes := ssh.MarshalAuthorizedKey(sshPublicKey)
1018

Michael Yang's avatar
Michael Yang committed
1019
		if err := os.WriteFile(pubKeyPath, publicKeyBytes, 0o644); err != nil {
1020
1021
1022
			return err
		}

Michael Yang's avatar
Michael Yang committed
1023
		fmt.Printf("Your new public key is: \n\n%s\n", publicKeyBytes)
1024
1025
1026
1027
	}
	return nil
}

1028
1029
//nolint:unused
func waitForServer(ctx context.Context, client *api.Client) error {
Bruce MacDonald's avatar
Bruce MacDonald committed
1030
1031
1032
1033
1034
1035
1036
1037
	// wait for the server to start
	timeout := time.After(5 * time.Second)
	tick := time.Tick(500 * time.Millisecond)
	for {
		select {
		case <-timeout:
			return errors.New("timed out waiting for server to start")
		case <-tick:
Michael Yang's avatar
Michael Yang committed
1038
			if err := client.Heartbeat(ctx); err == nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
1039
1040
1041
1042
				return nil // server has started
			}
		}
	}
1043

Bruce MacDonald's avatar
Bruce MacDonald committed
1044
1045
}

Michael Yang's avatar
Michael Yang committed
1046
func checkServerHeartbeat(cmd *cobra.Command, _ []string) error {
Michael Yang's avatar
Michael Yang committed
1047
	client, err := api.ClientFromEnvironment()
1048
1049
1050
	if err != nil {
		return err
	}
Michael Yang's avatar
Michael Yang committed
1051
	if err := client.Heartbeat(cmd.Context()); err != nil {
1052
		if !strings.Contains(err.Error(), " refused") {
Bruce MacDonald's avatar
Bruce MacDonald committed
1053
1054
			return err
		}
1055
1056
		if err := startApp(cmd.Context(), client); err != nil {
			return fmt.Errorf("could not connect to ollama app, is it running?")
1057
1058
1059
1060
1061
		}
	}
	return nil
}

Michael Yang's avatar
Michael Yang committed
1062
1063
1064
1065
1066
1067
1068
1069
func versionHandler(cmd *cobra.Command, _ []string) {
	client, err := api.ClientFromEnvironment()
	if err != nil {
		return
	}

	serverVersion, err := client.Version(cmd.Context())
	if err != nil {
Michael Yang's avatar
Michael Yang committed
1070
1071
1072
1073
1074
		fmt.Println("Warning: could not connect to a running Ollama instance")
	}

	if serverVersion != "" {
		fmt.Printf("ollama version is %s\n", serverVersion)
Michael Yang's avatar
Michael Yang committed
1075
1076
	}

1077
	if serverVersion != version.Version {
Michael Yang's avatar
Michael Yang committed
1078
		fmt.Printf("Warning: client version is %s\n", version.Version)
1079
	}
Michael Yang's avatar
Michael Yang committed
1080
1081
}

1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
type EnvironmentVar struct {
	Name        string
	Description string
}

func appendEnvDocs(cmd *cobra.Command, envs []EnvironmentVar) {
	if len(envs) == 0 {
		return
	}

	envUsage := `
1093
1094
Environment Variables:
`
1095
1096
1097
1098
1099
	for _, e := range envs {
		envUsage += fmt.Sprintf("      %-16s   %s\n", e.Name, e.Description)
	}

	cmd.SetUsageTemplate(cmd.UsageTemplate() + envUsage)
1100
1101
}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1102
1103
func NewCLI() *cobra.Command {
	log.SetFlags(log.LstdFlags | log.Lshortfile)
Michael Yang's avatar
Michael Yang committed
1104
	cobra.EnableCommandSorting = false
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1105

1106
	if runtime.GOOS == "windows" {
1107
		console.ConsoleFromFile(os.Stdin) //nolint:errcheck
1108
1109
	}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1110
	rootCmd := &cobra.Command{
1111
1112
1113
1114
		Use:           "ollama",
		Short:         "Large language model runner",
		SilenceUsage:  true,
		SilenceErrors: true,
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1115
1116
1117
		CompletionOptions: cobra.CompletionOptions{
			DisableDefaultCmd: true,
		},
Michael Yang's avatar
Michael Yang committed
1118
1119
1120
1121
1122
1123
1124
1125
		Run: func(cmd *cobra.Command, args []string) {
			if version, _ := cmd.Flags().GetBool("version"); version {
				versionHandler(cmd, args)
				return
			}

			cmd.Print(cmd.UsageString())
		},
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1126
1127
	}

Michael Yang's avatar
Michael Yang committed
1128
	rootCmd.Flags().BoolP("version", "v", false, "Show version information")
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1129

1130
	createCmd := &cobra.Command{
1131
1132
		Use:     "create MODEL",
		Short:   "Create a model from a Modelfile",
Michael Yang's avatar
Michael Yang committed
1133
		Args:    cobra.ExactArgs(1),
1134
1135
		PreRunE: checkServerHeartbeat,
		RunE:    CreateHandler,
1136
1137
	}

1138
	createCmd.Flags().StringP("file", "f", "Modelfile", "Name of the Modelfile")
1139
	createCmd.Flags().StringP("quantize", "q", "", "Quantize model to this level (e.g. q4_0)")
1140

Patrick Devine's avatar
Patrick Devine committed
1141
1142
1143
	showCmd := &cobra.Command{
		Use:     "show MODEL",
		Short:   "Show information for a model",
Michael Yang's avatar
Michael Yang committed
1144
		Args:    cobra.ExactArgs(1),
Patrick Devine's avatar
Patrick Devine committed
1145
1146
1147
1148
1149
1150
1151
1152
		PreRunE: checkServerHeartbeat,
		RunE:    ShowHandler,
	}

	showCmd.Flags().Bool("license", false, "Show license of a model")
	showCmd.Flags().Bool("modelfile", false, "Show Modelfile of a model")
	showCmd.Flags().Bool("parameters", false, "Show parameters of a model")
	showCmd.Flags().Bool("template", false, "Show template of a model")
1153
	showCmd.Flags().Bool("system", false, "Show system message of a model")
Patrick Devine's avatar
Patrick Devine committed
1154

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1155
	runCmd := &cobra.Command{
1156
1157
1158
1159
1160
		Use:     "run MODEL [PROMPT]",
		Short:   "Run a model",
		Args:    cobra.MinimumNArgs(1),
		PreRunE: checkServerHeartbeat,
		RunE:    RunHandler,
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1161
1162
	}

1163
	runCmd.Flags().String("keepalive", "", "Duration to keep a model loaded (e.g. 5m)")
1164
	runCmd.Flags().Bool("verbose", false, "Show timings for response")
1165
	runCmd.Flags().Bool("insecure", false, "Use an insecure registry")
1166
	runCmd.Flags().Bool("nowordwrap", false, "Don't wrap words to the next line automatically")
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1167
	runCmd.Flags().String("format", "", "Response format (e.g. json)")
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1168
1169
1170
1171
	serveCmd := &cobra.Command{
		Use:     "serve",
		Aliases: []string{"start"},
		Short:   "Start ollama",
Michael Yang's avatar
Michael Yang committed
1172
		Args:    cobra.ExactArgs(0),
Michael Yang's avatar
Michael Yang committed
1173
		RunE:    RunServer,
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1174
	}
1175
1176
1177
	serveCmd.SetUsageTemplate(serveCmd.UsageTemplate() + `
Environment Variables:

1178
    OLLAMA_HOST         The host:port to bind to (default "127.0.0.1:11434")
Josh Yan's avatar
Josh Yan committed
1179
    OLLAMA_ORIGINS      A comma separated list of allowed origins
Josh Yan's avatar
Josh Yan committed
1180
1181
    OLLAMA_MODELS       The path to the models directory (default "~/.ollama/models")
    OLLAMA_KEEP_ALIVE   The duration that models stay loaded in memory (default "5m")
1182
    OLLAMA_DEBUG        Set to 1 to enable additional debug logging
1183
`)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1184

1185
	pullCmd := &cobra.Command{
1186
1187
		Use:     "pull MODEL",
		Short:   "Pull a model from a registry",
Michael Yang's avatar
Michael Yang committed
1188
		Args:    cobra.ExactArgs(1),
1189
1190
		PreRunE: checkServerHeartbeat,
		RunE:    PullHandler,
1191
1192
	}

1193
1194
	pullCmd.Flags().Bool("insecure", false, "Use an insecure registry")

1195
	pushCmd := &cobra.Command{
1196
1197
		Use:     "push MODEL",
		Short:   "Push a model to a registry",
Michael Yang's avatar
Michael Yang committed
1198
		Args:    cobra.ExactArgs(1),
1199
1200
		PreRunE: checkServerHeartbeat,
		RunE:    PushHandler,
1201
1202
	}

1203
1204
	pushCmd.Flags().Bool("insecure", false, "Use an insecure registry")

Patrick Devine's avatar
Patrick Devine committed
1205
	listCmd := &cobra.Command{
1206
		Use:     "list",
Patrick Devine's avatar
Patrick Devine committed
1207
		Aliases: []string{"ls"},
1208
		Short:   "List models",
1209
		PreRunE: checkServerHeartbeat,
1210
		RunE:    ListHandler,
1211
	}
1212
1213
1214
1215
1216
1217
1218
1219

	psCmd := &cobra.Command{
		Use:     "ps",
		Short:   "List running models",
		PreRunE: checkServerHeartbeat,
		RunE:    ListRunningHandler,
	}

Patrick Devine's avatar
Patrick Devine committed
1220
	copyCmd := &cobra.Command{
Michael Yang's avatar
Michael Yang committed
1221
		Use:     "cp SOURCE DESTINATION",
1222
		Short:   "Copy a model",
Michael Yang's avatar
Michael Yang committed
1223
		Args:    cobra.ExactArgs(2),
1224
1225
		PreRunE: checkServerHeartbeat,
		RunE:    CopyHandler,
Patrick Devine's avatar
Patrick Devine committed
1226
1227
	}

1228
	deleteCmd := &cobra.Command{
Michael Yang's avatar
Michael Yang committed
1229
		Use:     "rm MODEL [MODEL...]",
1230
1231
1232
1233
		Short:   "Remove a model",
		Args:    cobra.MinimumNArgs(1),
		PreRunE: checkServerHeartbeat,
		RunE:    DeleteHandler,
Patrick Devine's avatar
Patrick Devine committed
1234
1235
	}

1236
1237
1238
1239
	ollamaHostEnv := EnvironmentVar{"OLLAMA_HOST", "The host:port or base URL of the Ollama server (e.g. http://localhost:11434)"}
	ollamaNoHistoryEnv := EnvironmentVar{"OLLAMA_NOHISTORY", "Disable readline history"}
	envs := []EnvironmentVar{ollamaHostEnv}

1240
1241
1242
1243
1244
1245
1246
	for _, cmd := range []*cobra.Command{
		createCmd,
		showCmd,
		runCmd,
		pullCmd,
		pushCmd,
		listCmd,
1247
		psCmd,
1248
1249
1250
		copyCmd,
		deleteCmd,
	} {
1251
1252
1253
1254
1255
1256
		switch cmd {
		case runCmd:
			appendEnvDocs(cmd, []EnvironmentVar{ollamaHostEnv, ollamaNoHistoryEnv})
		default:
			appendEnvDocs(cmd, envs)
		}
1257
1258
	}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1259
1260
	rootCmd.AddCommand(
		serveCmd,
1261
		createCmd,
Patrick Devine's avatar
Patrick Devine committed
1262
		showCmd,
1263
		runCmd,
1264
1265
		pullCmd,
		pushCmd,
Patrick Devine's avatar
Patrick Devine committed
1266
		listCmd,
1267
		psCmd,
Patrick Devine's avatar
Patrick Devine committed
1268
		copyCmd,
1269
		deleteCmd,
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1270
1271
1272
1273
	)

	return rootCmd
}