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

import (
Michael Yang's avatar
Michael Yang committed
4
	"bufio"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
5
	"context"
6
7
	"crypto/ed25519"
	"crypto/rand"
8
	"encoding/json"
9
	"encoding/pem"
Michael Yang's avatar
Michael Yang committed
10
	"errors"
Bruce MacDonald's avatar
Bruce MacDonald committed
11
	"fmt"
Michael Yang's avatar
Michael Yang committed
12
	"io"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
13
	"log"
14
	"math"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
15
	"net"
16
	"net/http"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
17
	"os"
18
	"os/signal"
19
	"path/filepath"
20
	"runtime"
Michael Yang's avatar
Michael Yang committed
21
	"strconv"
Michael Yang's avatar
Michael Yang committed
22
	"strings"
23
	"sync/atomic"
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/term"
Michael Yang's avatar
Michael Yang committed
33

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

46
var errModelfileNotFound = errors.New("specified Modelfile wasn't found")
47
48

func getModelfileName(cmd *cobra.Command) (string, error) {
49
	filename, _ := cmd.Flags().GetString("file")
50
51
52
53
54
55

	if filename == "" {
		filename = "Modelfile"
	}

	absName, err := filepath.Abs(filename)
56
	if err != nil {
57
		return "", err
58
59
	}

60
	_, err = os.Stat(absName)
61
	if err != nil {
62
		return "", err
63
	}
64

65
66
67
68
	return absName, nil
}

func CreateHandler(cmd *cobra.Command, args []string) error {
Michael Yang's avatar
Michael Yang committed
69
70
71
	p := progress.NewProgress(os.Stderr)
	defer p.Stop()

72
73
74
75
76
77
78
79
80
81
	var reader io.Reader

	filename, err := getModelfileName(cmd)
	if os.IsNotExist(err) {
		if filename == "" {
			reader = strings.NewReader("FROM .\n")
		} else {
			return errModelfileNotFound
		}
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
82
		return err
83
84
85
86
87
88
89
90
	} else {
		f, err := os.Open(filename)
		if err != nil {
			return err
		}

		reader = f
		defer f.Close()
Michael Yang's avatar
Michael Yang committed
91
92
	}

93
	modelfile, err := parser.ParseFile(reader)
Michael Yang's avatar
Michael Yang committed
94
95
96
97
	if err != nil {
		return err
	}

98
99
100
101
	status := "gathering model components"
	spinner := progress.NewSpinner(status)
	p.Add(status, spinner)

102
	req, err := modelfile.CreateRequest(filepath.Dir(filename))
Michael Yang's avatar
Michael Yang committed
103
104
105
	if err != nil {
		return err
	}
106
	spinner.Stop()
Michael Yang's avatar
Michael Yang committed
107

108
109
110
111
112
	req.Name = args[0]
	quantize, _ := cmd.Flags().GetString("quantize")
	if quantize != "" {
		req.Quantize = quantize
	}
113

114
115
116
117
118
	client, err := api.ClientFromEnvironment()
	if err != nil {
		return err
	}

119
120
121
122
	if len(req.Files) > 0 {
		fileMap := map[string]string{}
		for f, digest := range req.Files {
			if _, err := createBlob(cmd, client, f, digest, p); err != nil {
Michael Yang's avatar
Michael Yang committed
123
124
				return err
			}
125
126
127
128
			fileMap[filepath.Base(f)] = digest
		}
		req.Files = fileMap
	}
Michael Yang's avatar
Michael Yang committed
129

130
131
132
133
	if len(req.Adapters) > 0 {
		fileMap := map[string]string{}
		for f, digest := range req.Adapters {
			if _, err := createBlob(cmd, client, f, digest, p); err != nil {
Michael Yang's avatar
Michael Yang committed
134
135
				return err
			}
136
			fileMap[filepath.Base(f)] = digest
Michael Yang's avatar
Michael Yang committed
137
		}
138
		req.Adapters = fileMap
Michael Yang's avatar
Michael Yang committed
139
	}
Michael Yang's avatar
Michael Yang committed
140

Michael Yang's avatar
Michael Yang committed
141
	bars := make(map[string]*progress.Bar)
142
	fn := func(resp api.ProgressResponse) error {
Michael Yang's avatar
Michael Yang committed
143
144
145
		if resp.Digest != "" {
			bar, ok := bars[resp.Digest]
			if !ok {
146
				bar = progress.NewBar(fmt.Sprintf("pulling %s...", resp.Digest[7:19]), resp.Total, resp.Completed)
Michael Yang's avatar
Michael Yang committed
147
148
149
150
151
152
153
154
155
156
157
158
159
				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)
		}

160
161
162
		return nil
	}

163
	if err := client.Create(cmd.Context(), req, fn); err != nil {
164
165
166
		if strings.Contains(err.Error(), "path or Modelfile are required") {
			return fmt.Errorf("the ollama server must be updated to use `ollama create` with this client")
		}
167
168
169
170
171
172
		return err
	}

	return nil
}

173
174
func createBlob(cmd *cobra.Command, client *api.Client, path string, digest string, p *progress.Progress) (string, error) {
	realPath, err := filepath.EvalSymlinks(path)
Michael Yang's avatar
Michael Yang committed
175
176
177
178
	if err != nil {
		return "", err
	}

179
	bin, err := os.Open(realPath)
180
181
182
183
184
	if err != nil {
		return "", err
	}
	defer bin.Close()

185
186
187
188
189
190
191
192
	// Get file info to retrieve the size
	fileInfo, err := bin.Stat()
	if err != nil {
		return "", err
	}
	fileSize := fileInfo.Size()

	var pw progressWriter
193
194
195
196
	status := fmt.Sprintf("copying file %s 0%%", digest)
	spinner := progress.NewSpinner(status)
	p.Add(status, spinner)
	defer spinner.Stop()
197
198
199
200
201
202
203
204
205
206

	done := make(chan struct{})
	defer close(done)

	go func() {
		ticker := time.NewTicker(60 * time.Millisecond)
		defer ticker.Stop()
		for {
			select {
			case <-ticker.C:
207
				spinner.SetMessage(fmt.Sprintf("copying file %s %d%%", digest, int(100*pw.n.Load()/fileSize)))
208
			case <-done:
209
				spinner.SetMessage(fmt.Sprintf("copying file %s 100%%", digest))
210
211
212
213
214
215
				return
			}
		}
	}()

	if err = client.CreateBlob(cmd.Context(), digest, io.TeeReader(bin, &pw)); err != nil {
216
217
218
219
220
		return "", err
	}
	return digest, nil
}

221
222
223
224
225
226
227
228
229
type progressWriter struct {
	n atomic.Int64
}

func (w *progressWriter) Write(p []byte) (n int, err error) {
	w.n.Add(int64(len(p)))
	return len(p), nil
}

Patrick Devine's avatar
Patrick Devine committed
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
func loadOrUnloadModel(cmd *cobra.Command, opts *runOptions) error {
	p := progress.NewProgress(os.Stderr)
	defer p.StopAndClear()

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

	client, err := api.ClientFromEnvironment()
	if err != nil {
		return err
	}

	req := &api.GenerateRequest{
		Model:     opts.Model,
		KeepAlive: opts.KeepAlive,
	}

	return client.Generate(cmd.Context(), req, func(api.GenerateResponse) error { return nil })
}

func StopHandler(cmd *cobra.Command, args []string) error {
	opts := &runOptions{
		Model:     args[0],
		KeepAlive: &api.Duration{Duration: 0},
	}
	if err := loadOrUnloadModel(cmd, opts); err != nil {
		if strings.Contains(err.Error(), "not found") {
			return fmt.Errorf("couldn't find model \"%s\" to stop", args[0])
		}
	}
	return nil
}

263
func RunHandler(cmd *cobra.Command, args []string) error {
264
265
266
	interactive := true

	opts := runOptions{
267
268
269
		Model:    args[0],
		WordWrap: os.Getenv("TERM") == "xterm-256color",
		Options:  map[string]interface{}{},
270
271
272
273
274
275
276
277
	}

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

278
279
280
281
282
283
284
285
286
287
288
289
	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}
	}

290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
	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
	}
306
307
308
309
	// Be quiet if we're redirecting to a pipe or file
	if !term.IsTerminal(int(os.Stdout.Fd())) {
		interactive = false
	}
310
311
312
313
314
315
316

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

317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
	// Fill out the rest of the options based on information about the
	// model.
	client, err := api.ClientFromEnvironment()
	if err != nil {
		return err
	}

	name := args[0]
	info, err := func() (*api.ShowResponse, error) {
		showReq := &api.ShowRequest{Name: name}
		info, err := client.Show(cmd.Context(), showReq)
		var se api.StatusError
		if errors.As(err, &se) && se.StatusCode == http.StatusNotFound {
			if err := PullHandler(cmd, []string{name}); err != nil {
				return nil, err
			}
			return client.Show(cmd.Context(), &api.ShowRequest{Name: name})
		}
		return info, err
	}()
	if err != nil {
		return err
339
340
	}

Jesse Gross's avatar
Jesse Gross committed
341
342
343
344
	// TODO(jessegross): We should either find another way to know if this is
	// a vision model or remove the logic. Also consider that other modalities will
	// need different behavior anyways.
	opts.MultiModal = len(info.ProjectorInfo) != 0 || envconfig.NewEngine()
345
346
347
	opts.ParentModel = info.Details.ParentModel

	if interactive {
Patrick Devine's avatar
Patrick Devine committed
348
		if err := loadOrUnloadModel(cmd, &opts); err != nil {
Michael Yang's avatar
Michael Yang committed
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
			return err
		}

		for _, msg := range info.Messages {
			switch msg.Role {
			case "user":
				fmt.Printf(">>> %s\n", msg.Content)
			case "assistant":
				state := &displayResponseState{}
				displayResponse(msg.Content, opts.WordWrap, state)
				fmt.Println()
				fmt.Println()
			}
		}

364
365
366
		return generateInteractive(cmd, opts)
	}
	return generate(cmd, opts)
Bruce MacDonald's avatar
Bruce MacDonald committed
367
368
}

369
func PushHandler(cmd *cobra.Command, args []string) error {
Michael Yang's avatar
Michael Yang committed
370
	client, err := api.ClientFromEnvironment()
371
372
373
	if err != nil {
		return err
	}
374

375
376
377
378
379
	insecure, err := cmd.Flags().GetBool("insecure")
	if err != nil {
		return err
	}

Michael Yang's avatar
Michael Yang committed
380
381
382
383
	p := progress.NewProgress(os.Stderr)
	defer p.Stop()

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

387
	fn := func(resp api.ProgressResponse) error {
Michael Yang's avatar
Michael Yang committed
388
		if resp.Digest != "" {
389
390
391
			if spinner != nil {
				spinner.Stop()
			}
Michael Yang's avatar
Michael Yang committed
392
393
394

			bar, ok := bars[resp.Digest]
			if !ok {
395
				bar = progress.NewBar(fmt.Sprintf("pushing %s...", resp.Digest[7:19]), resp.Total, resp.Completed)
Michael Yang's avatar
Michael Yang committed
396
397
398
399
400
401
				bars[resp.Digest] = bar
				p.Add(resp.Digest, bar)
			}

			bar.Set(resp.Completed)
		} else if status != resp.Status {
402
403
404
			if spinner != nil {
				spinner.Stop()
			}
Michael Yang's avatar
Michael Yang committed
405
406
407
408
409
410

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

411
412
413
		return nil
	}

Michael Yang's avatar
Michael Yang committed
414
	request := api.PushRequest{Name: args[0], Insecure: insecure}
415
416

	n := model.ParseName(args[0])
Michael Yang's avatar
Michael Yang committed
417
	if err := client.Push(cmd.Context(), &request, fn); err != nil {
418
419
420
421
422
423
		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")
		}
Michael Yang's avatar
Michael Yang committed
424
425
426
		return err
	}

427
	p.Stop()
428
	spinner.Stop()
429
430
431
432
433
434
435
436

	destination := n.String()
	if strings.HasSuffix(n.Host, ".ollama.ai") || strings.HasSuffix(n.Host, ".ollama.com") {
		destination = "https://ollama.com/" + strings.TrimSuffix(n.DisplayShortest(), ":latest")
	}
	fmt.Printf("\nYou can find your model at:\n\n")
	fmt.Printf("\t%s\n", destination)

Michael Yang's avatar
Michael Yang committed
437
	return nil
438
439
}

440
func ListHandler(cmd *cobra.Command, args []string) error {
Michael Yang's avatar
Michael Yang committed
441
	client, err := api.ClientFromEnvironment()
442
443
444
	if err != nil {
		return err
	}
Patrick Devine's avatar
Patrick Devine committed
445

Michael Yang's avatar
Michael Yang committed
446
	models, err := client.List(cmd.Context())
Patrick Devine's avatar
Patrick Devine committed
447
448
449
450
451
452
453
	if err != nil {
		return err
	}

	var data [][]string

	for _, m := range models.Models {
454
		if len(args) == 0 || strings.HasPrefix(strings.ToLower(m.Name), strings.ToLower(args[0])) {
455
			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
456
		}
Patrick Devine's avatar
Patrick Devine committed
457
458
459
	}

	table := tablewriter.NewWriter(os.Stdout)
Patrick Devine's avatar
Patrick Devine committed
460
	table.SetHeader([]string{"NAME", "ID", "SIZE", "MODIFIED"})
Patrick Devine's avatar
Patrick Devine committed
461
462
463
464
465
	table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
	table.SetAlignment(tablewriter.ALIGN_LEFT)
	table.SetHeaderLine(false)
	table.SetBorder(false)
	table.SetNoWhiteSpace(true)
Michael Yang's avatar
Michael Yang committed
466
	table.SetTablePadding("    ")
Patrick Devine's avatar
Patrick Devine committed
467
468
469
470
471
472
	table.AppendBulk(data)
	table.Render()

	return nil
}

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
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))
			}
Patrick Devine's avatar
Patrick Devine committed
501
502
503
504
505
506
507
508
509

			var until string
			delta := time.Since(m.ExpiresAt)
			if delta > 0 {
				until = "Stopping..."
			} else {
				until = format.HumanTime(m.ExpiresAt, "Never")
			}
			data = append(data, []string{m.Name, m.Digest[:12], format.HumanBytes(m.Size), procStr, until})
510
511
512
513
514
515
516
517
518
519
		}
	}

	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)
Michael Yang's avatar
Michael Yang committed
520
	table.SetTablePadding("    ")
521
522
523
524
525
526
	table.AppendBulk(data)
	table.Render()

	return nil
}

527
func DeleteHandler(cmd *cobra.Command, args []string) error {
Michael Yang's avatar
Michael Yang committed
528
	client, err := api.ClientFromEnvironment()
529
530
531
	if err != nil {
		return err
	}
532

533
534
535
536
537
538
539
540
541
542
543
	// Unload the model if it's running before deletion
	opts := &runOptions{
		Model:     args[0],
		KeepAlive: &api.Duration{Duration: 0},
	}
	if err := loadOrUnloadModel(cmd, opts); err != nil {
		if !strings.Contains(err.Error(), "not found") {
			return fmt.Errorf("unable to stop existing running model \"%s\": %s", args[0], err)
		}
	}

544
545
	for _, name := range args {
		req := api.DeleteRequest{Name: name}
Michael Yang's avatar
Michael Yang committed
546
		if err := client.Delete(cmd.Context(), &req); err != nil {
547
548
549
			return err
		}
		fmt.Printf("deleted '%s'\n", name)
550
551
552
553
	}
	return nil
}

Patrick Devine's avatar
Patrick Devine committed
554
func ShowHandler(cmd *cobra.Command, args []string) error {
Michael Yang's avatar
Michael Yang committed
555
	client, err := api.ClientFromEnvironment()
Patrick Devine's avatar
Patrick Devine committed
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
	if err != nil {
		return err
	}

	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 {
601
		return errors.New("only one of '--license', '--modelfile', '--parameters', '--system', or '--template' can be specified")
602
603
	}

604
605
606
607
608
	req := api.ShowRequest{Name: args[0]}
	resp, err := client.Show(cmd.Context(), &req)
	if err != nil {
		return err
	}
609

610
	if flagsSet == 1 {
611
612
613
614
615
616
617
618
		switch showType {
		case "license":
			fmt.Println(resp.License)
		case "modelfile":
			fmt.Println(resp.Modelfile)
		case "parameters":
			fmt.Println(resp.Parameters)
		case "system":
619
			fmt.Print(resp.System)
620
		case "template":
621
			fmt.Print(resp.Template)
622
623
624
		}

		return nil
Patrick Devine's avatar
Patrick Devine committed
625
626
	}

Michael Yang's avatar
Michael Yang committed
627
	return showInfo(resp, os.Stdout)
628
629
}

Michael Yang's avatar
Michael Yang committed
630
631
632
633
634
635
636
637
func showInfo(resp *api.ShowResponse, w io.Writer) error {
	tableRender := func(header string, rows func() [][]string) {
		fmt.Fprintln(w, " ", header)
		table := tablewriter.NewWriter(w)
		table.SetAlignment(tablewriter.ALIGN_LEFT)
		table.SetBorder(false)
		table.SetNoWhiteSpace(true)
		table.SetTablePadding("    ")
638

Michael Yang's avatar
Michael Yang committed
639
640
641
		switch header {
		case "Template", "System", "License":
			table.SetColWidth(100)
642
643
		}

Michael Yang's avatar
Michael Yang committed
644
645
646
		table.AppendBulk(rows())
		table.Render()
		fmt.Fprintln(w)
Patrick Devine's avatar
Patrick Devine committed
647
648
	}

Michael Yang's avatar
Michael Yang committed
649
650
651
652
653
654
655
656
657
658
659
660
661
662
	tableRender("Model", func() (rows [][]string) {
		if resp.ModelInfo != nil {
			arch := resp.ModelInfo["general.architecture"].(string)
			rows = append(rows, []string{"", "architecture", arch})
			rows = append(rows, []string{"", "parameters", format.HumanNumber(uint64(resp.ModelInfo["general.parameter_count"].(float64)))})
			rows = append(rows, []string{"", "context length", strconv.FormatFloat(resp.ModelInfo[fmt.Sprintf("%s.context_length", arch)].(float64), 'f', -1, 64)})
			rows = append(rows, []string{"", "embedding length", strconv.FormatFloat(resp.ModelInfo[fmt.Sprintf("%s.embedding_length", arch)].(float64), 'f', -1, 64)})
		} else {
			rows = append(rows, []string{"", "architecture", resp.Details.Family})
			rows = append(rows, []string{"", "parameters", resp.Details.ParameterSize})
		}
		rows = append(rows, []string{"", "quantization", resp.Details.QuantizationLevel})
		return
	})
663

Michael Yang's avatar
Michael Yang committed
664
665
666
667
668
669
670
671
672
	if resp.ProjectorInfo != nil {
		tableRender("Projector", func() (rows [][]string) {
			arch := resp.ProjectorInfo["general.architecture"].(string)
			rows = append(rows, []string{"", "architecture", arch})
			rows = append(rows, []string{"", "parameters", format.HumanNumber(uint64(resp.ProjectorInfo["general.parameter_count"].(float64)))})
			rows = append(rows, []string{"", "embedding length", strconv.FormatFloat(resp.ProjectorInfo[fmt.Sprintf("%s.vision.embedding_length", arch)].(float64), 'f', -1, 64)})
			rows = append(rows, []string{"", "dimensions", strconv.FormatFloat(resp.ProjectorInfo[fmt.Sprintf("%s.vision.projection_dim", arch)].(float64), 'f', -1, 64)})
			return
		})
673
674
	}

Michael Yang's avatar
Michael Yang committed
675
676
677
678
679
680
681
682
683
684
	if resp.Parameters != "" {
		tableRender("Parameters", func() (rows [][]string) {
			scanner := bufio.NewScanner(strings.NewReader(resp.Parameters))
			for scanner.Scan() {
				if text := scanner.Text(); text != "" {
					rows = append(rows, append([]string{""}, strings.Fields(text)...))
				}
			}
			return
		})
685
686
	}

Michael Yang's avatar
Michael Yang committed
687
688
689
690
691
	head := func(s string, n int) (rows [][]string) {
		scanner := bufio.NewScanner(strings.NewReader(s))
		for scanner.Scan() && (len(rows) < n || n < 0) {
			if text := scanner.Text(); text != "" {
				rows = append(rows, []string{"", strings.TrimSpace(text)})
692
693
			}
		}
Michael Yang's avatar
Michael Yang committed
694
		return
695
696
	}

Michael Yang's avatar
Michael Yang committed
697
698
699
700
701
	if resp.System != "" {
		tableRender("System", func() [][]string {
			return head(resp.System, 2)
		})
	}
702

Michael Yang's avatar
Michael Yang committed
703
704
705
706
	if resp.License != "" {
		tableRender("License", func() [][]string {
			return head(resp.License, 2)
		})
707
	}
Michael Yang's avatar
Michael Yang committed
708
709

	return nil
710
711
}

Patrick Devine's avatar
Patrick Devine committed
712
func CopyHandler(cmd *cobra.Command, args []string) error {
Michael Yang's avatar
Michael Yang committed
713
	client, err := api.ClientFromEnvironment()
714
715
716
	if err != nil {
		return err
	}
Patrick Devine's avatar
Patrick Devine committed
717
718

	req := api.CopyRequest{Source: args[0], Destination: args[1]}
Michael Yang's avatar
Michael Yang committed
719
	if err := client.Copy(cmd.Context(), &req); err != nil {
Patrick Devine's avatar
Patrick Devine committed
720
721
722
723
724
725
		return err
	}
	fmt.Printf("copied '%s' to '%s'\n", args[0], args[1])
	return nil
}

726
func PullHandler(cmd *cobra.Command, args []string) error {
727
728
729
730
731
	insecure, err := cmd.Flags().GetBool("insecure")
	if err != nil {
		return err
	}

Michael Yang's avatar
Michael Yang committed
732
	client, err := api.ClientFromEnvironment()
733
734
735
	if err != nil {
		return err
	}
736

Michael Yang's avatar
Michael Yang committed
737
738
739
740
741
	p := progress.NewProgress(os.Stderr)
	defer p.Stop()

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

742
743
	var status string
	var spinner *progress.Spinner
Michael Yang's avatar
Michael Yang committed
744

745
	fn := func(resp api.ProgressResponse) error {
Michael Yang's avatar
Michael Yang committed
746
		if resp.Digest != "" {
747
748
749
			if spinner != nil {
				spinner.Stop()
			}
Michael Yang's avatar
Michael Yang committed
750
751
752

			bar, ok := bars[resp.Digest]
			if !ok {
753
				bar = progress.NewBar(fmt.Sprintf("pulling %s...", resp.Digest[7:19]), resp.Total, resp.Completed)
Michael Yang's avatar
Michael Yang committed
754
755
756
757
758
759
				bars[resp.Digest] = bar
				p.Add(resp.Digest, bar)
			}

			bar.Set(resp.Completed)
		} else if status != resp.Status {
760
761
762
			if spinner != nil {
				spinner.Stop()
			}
Michael Yang's avatar
Michael Yang committed
763
764
765
766
767
768

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

769
770
		return nil
	}
771

Michael Yang's avatar
Michael Yang committed
772
	request := api.PullRequest{Name: args[0], Insecure: insecure}
Michael Yang's avatar
Michael Yang committed
773
	if err := client.Pull(cmd.Context(), &request, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
774
775
776
777
		return err
	}

	return nil
Michael Yang's avatar
Michael Yang committed
778
779
}

780
781
type generateContextKey string

782
type runOptions struct {
783
784
785
786
787
788
789
790
791
792
	Model       string
	ParentModel string
	Prompt      string
	Messages    []api.Message
	WordWrap    bool
	Format      string
	System      string
	Images      []api.ImageData
	Options     map[string]interface{}
	MultiModal  bool
793
	KeepAlive   *api.Duration
794
795
}

796
797
798
799
800
801
802
803
804
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
805
806
			if state.lineLength+1 > termWidth-5 {
				if runewidth.StringWidth(state.wordBuffer) > termWidth-10 {
807
808
809
810
811
812
813
					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
814
815
				a := runewidth.StringWidth(state.wordBuffer)
				if a > 0 {
816
					fmt.Printf("\x1b[%dD", a)
817
818
				}
				fmt.Printf("\x1b[K\n")
819
				fmt.Printf("%s%c", state.wordBuffer, ch)
820
821
822
				chWidth := runewidth.RuneWidth(ch)

				state.lineLength = runewidth.StringWidth(state.wordBuffer) + chWidth
823
824
			} else {
				fmt.Print(string(ch))
825
826
827
828
				state.lineLength += runewidth.RuneWidth(ch)
				if runewidth.RuneWidth(ch) >= 2 {
					state.wordBuffer = ""
					continue
Josh Yan's avatar
Josh Yan committed
829
				}
830
831
832
833
834
835
836
837
838
839
840
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
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890

				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
	}

891
892
893
894
	if opts.Format == "json" {
		opts.Format = `"` + opts.Format + `"`
	}

895
896
897
	req := &api.ChatRequest{
		Model:    opts.Model,
		Messages: opts.Messages,
898
		Format:   json.RawMessage(opts.Format),
899
900
901
		Options:  opts.Options,
	}

902
903
904
905
	if opts.KeepAlive != nil {
		req.KeepAlive = opts.KeepAlive
	}

906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
	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
931
	client, err := api.ClientFromEnvironment()
Patrick Devine's avatar
Patrick Devine committed
932
	if err != nil {
933
		return err
Patrick Devine's avatar
Patrick Devine committed
934
	}
Michael Yang's avatar
Michael Yang committed
935

Michael Yang's avatar
Michael Yang committed
936
	p := progress.NewProgress(os.Stderr)
937
	defer p.StopAndClear()
938

Michael Yang's avatar
Michael Yang committed
939
940
941
	spinner := progress.NewSpinner("")
	p.Add("", spinner)

942
943
944
945
946
947
948
	var latest api.GenerateResponse

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

Michael Yang's avatar
Michael Yang committed
949
	ctx, cancel := context.WithCancel(cmd.Context())
950
951
952
953
954
955
956
957
958
959
	defer cancel()

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

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

960
	var state *displayResponseState = &displayResponseState{}
961

962
	fn := func(response api.GenerateResponse) error {
Michael Yang's avatar
Michael Yang committed
963
		p.StopAndClear()
964

Patrick Devine's avatar
Patrick Devine committed
965
		latest = response
966
		content := response.Response
967

968
		displayResponse(content, opts.WordWrap, state)
969

Patrick Devine's avatar
Patrick Devine committed
970
971
		return nil
	}
972

973
974
975
976
977
978
979
	if opts.MultiModal {
		opts.Prompt, opts.Images, err = extractFileData(opts.Prompt)
		if err != nil {
			return err
		}
	}

980
981
982
983
	if opts.Format == "json" {
		opts.Format = `"` + opts.Format + `"`
	}

Michael Yang's avatar
Michael Yang committed
984
	request := api.GenerateRequest{
985
986
987
988
		Model:     opts.Model,
		Prompt:    opts.Prompt,
		Context:   generateContext,
		Images:    opts.Images,
989
		Format:    json.RawMessage(opts.Format),
990
991
992
		System:    opts.System,
		Options:   opts.Options,
		KeepAlive: opts.KeepAlive,
Michael Yang's avatar
Michael Yang committed
993
994
995
	}

	if err := client.Generate(ctx, &request, fn); err != nil {
996
		if errors.Is(err, context.Canceled) {
997
			return nil
998
		}
999
		return err
Patrick Devine's avatar
Patrick Devine committed
1000
	}
1001

1002
	if opts.Prompt != "" {
Michael Yang's avatar
Michael Yang committed
1003
1004
		fmt.Println()
		fmt.Println()
Patrick Devine's avatar
Patrick Devine committed
1005
	}
1006

1007
1008
1009
1010
	if !latest.Done {
		return nil
	}

Patrick Devine's avatar
Patrick Devine committed
1011
1012
	verbose, err := cmd.Flags().GetBool("verbose")
	if err != nil {
1013
		return err
Patrick Devine's avatar
Patrick Devine committed
1014
	}
Michael Yang's avatar
Michael Yang committed
1015

Patrick Devine's avatar
Patrick Devine committed
1016
1017
	if verbose {
		latest.Summary()
Michael Yang's avatar
Michael Yang committed
1018
	}
Michael Yang's avatar
Michael Yang committed
1019

Patrick Devine's avatar
Patrick Devine committed
1020
1021
1022
	ctx = context.WithValue(cmd.Context(), generateContextKey("context"), latest.Context)
	cmd.SetContext(ctx)

1023
	return nil
Michael Yang's avatar
Michael Yang committed
1024
1025
}

1026
func RunServer(_ *cobra.Command, _ []string) error {
Michael Yang's avatar
Michael Yang committed
1027
	if err := initializeKeypair(); err != nil {
1028
1029
1030
		return err
	}

Michael Yang's avatar
host  
Michael Yang committed
1031
	ln, err := net.Listen("tcp", envconfig.Host().Host)
1032
1033
1034
	if err != nil {
		return err
	}
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1035

1036
1037
1038
1039
1040
1041
	err = server.Serve(ln)
	if errors.Is(err, http.ErrServerClosed) {
		return nil
	}

	return err
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1042
1043
}

1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
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
1056
		cryptoPublicKey, cryptoPrivateKey, err := ed25519.GenerateKey(rand.Reader)
1057
1058
1059
1060
		if err != nil {
			return err
		}

Michael Yang's avatar
Michael Yang committed
1061
		privateKeyBytes, err := ssh.MarshalPrivateKey(cryptoPrivateKey, "")
1062
1063
1064
1065
		if err != nil {
			return err
		}

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

Michael Yang's avatar
Michael Yang committed
1070
		if err := os.WriteFile(privKeyPath, pem.EncodeToMemory(privateKeyBytes), 0o600); err != nil {
1071
1072
1073
			return err
		}

Michael Yang's avatar
Michael Yang committed
1074
		sshPublicKey, err := ssh.NewPublicKey(cryptoPublicKey)
1075
1076
1077
1078
		if err != nil {
			return err
		}

Michael Yang's avatar
Michael Yang committed
1079
		publicKeyBytes := ssh.MarshalAuthorizedKey(sshPublicKey)
1080

Michael Yang's avatar
Michael Yang committed
1081
		if err := os.WriteFile(pubKeyPath, publicKeyBytes, 0o644); err != nil {
1082
1083
1084
			return err
		}

Michael Yang's avatar
Michael Yang committed
1085
		fmt.Printf("Your new public key is: \n\n%s\n", publicKeyBytes)
1086
1087
1088
1089
	}
	return nil
}

Michael Yang's avatar
Michael Yang committed
1090
func checkServerHeartbeat(cmd *cobra.Command, _ []string) error {
Michael Yang's avatar
Michael Yang committed
1091
	client, err := api.ClientFromEnvironment()
1092
1093
1094
	if err != nil {
		return err
	}
Michael Yang's avatar
Michael Yang committed
1095
	if err := client.Heartbeat(cmd.Context()); err != nil {
1096
		if !strings.Contains(err.Error(), " refused") {
Bruce MacDonald's avatar
Bruce MacDonald committed
1097
1098
			return err
		}
1099
		if err := startApp(cmd.Context(), client); err != nil {
Michael Yang's avatar
lint  
Michael Yang committed
1100
			return errors.New("could not connect to ollama app, is it running?")
1101
1102
1103
1104
1105
		}
	}
	return nil
}

Michael Yang's avatar
Michael Yang committed
1106
1107
1108
1109
1110
1111
1112
1113
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
1114
1115
1116
1117
1118
		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
1119
1120
	}

1121
	if serverVersion != version.Version {
Michael Yang's avatar
Michael Yang committed
1122
		fmt.Printf("Warning: client version is %s\n", version.Version)
1123
	}
Michael Yang's avatar
Michael Yang committed
1124
1125
}

1126
func appendEnvDocs(cmd *cobra.Command, envs []envconfig.EnvVar) {
1127
1128
1129
1130
1131
	if len(envs) == 0 {
		return
	}

	envUsage := `
1132
1133
Environment Variables:
`
1134
	for _, e := range envs {
1135
		envUsage += fmt.Sprintf("      %-24s   %s\n", e.Name, e.Description)
1136
1137
1138
	}

	cmd.SetUsageTemplate(cmd.UsageTemplate() + envUsage)
1139
1140
}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1141
1142
func NewCLI() *cobra.Command {
	log.SetFlags(log.LstdFlags | log.Lshortfile)
Michael Yang's avatar
Michael Yang committed
1143
	cobra.EnableCommandSorting = false
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1144

1145
	if runtime.GOOS == "windows" && term.IsTerminal(int(os.Stdout.Fd())) {
1146
		console.ConsoleFromFile(os.Stdin) //nolint:errcheck
1147
1148
	}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1149
	rootCmd := &cobra.Command{
1150
1151
1152
1153
		Use:           "ollama",
		Short:         "Large language model runner",
		SilenceUsage:  true,
		SilenceErrors: true,
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1154
1155
1156
		CompletionOptions: cobra.CompletionOptions{
			DisableDefaultCmd: true,
		},
Michael Yang's avatar
Michael Yang committed
1157
1158
1159
1160
1161
1162
1163
1164
		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
1165
1166
	}

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

1169
	createCmd := &cobra.Command{
1170
1171
		Use:     "create MODEL",
		Short:   "Create a model from a Modelfile",
Michael Yang's avatar
Michael Yang committed
1172
		Args:    cobra.ExactArgs(1),
1173
1174
		PreRunE: checkServerHeartbeat,
		RunE:    CreateHandler,
1175
1176
	}

1177
	createCmd.Flags().StringP("file", "f", "", "Name of the Modelfile (default \"Modelfile\"")
1178
	createCmd.Flags().StringP("quantize", "q", "", "Quantize model to this level (e.g. q4_0)")
1179

Patrick Devine's avatar
Patrick Devine committed
1180
1181
1182
	showCmd := &cobra.Command{
		Use:     "show MODEL",
		Short:   "Show information for a model",
Michael Yang's avatar
Michael Yang committed
1183
		Args:    cobra.ExactArgs(1),
Patrick Devine's avatar
Patrick Devine committed
1184
1185
1186
1187
1188
1189
1190
1191
		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")
1192
	showCmd.Flags().Bool("system", false, "Show system message of a model")
Patrick Devine's avatar
Patrick Devine committed
1193

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1194
	runCmd := &cobra.Command{
1195
1196
1197
1198
1199
		Use:     "run MODEL [PROMPT]",
		Short:   "Run a model",
		Args:    cobra.MinimumNArgs(1),
		PreRunE: checkServerHeartbeat,
		RunE:    RunHandler,
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1200
1201
	}

1202
	runCmd.Flags().String("keepalive", "", "Duration to keep a model loaded (e.g. 5m)")
1203
	runCmd.Flags().Bool("verbose", false, "Show timings for response")
1204
	runCmd.Flags().Bool("insecure", false, "Use an insecure registry")
1205
	runCmd.Flags().Bool("nowordwrap", false, "Don't wrap words to the next line automatically")
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1206
	runCmd.Flags().String("format", "", "Response format (e.g. json)")
Patrick Devine's avatar
Patrick Devine committed
1207
1208
1209
1210
1211
1212
1213
1214
1215

	stopCmd := &cobra.Command{
		Use:     "stop MODEL",
		Short:   "Stop a running model",
		Args:    cobra.ExactArgs(1),
		PreRunE: checkServerHeartbeat,
		RunE:    StopHandler,
	}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1216
1217
1218
1219
	serveCmd := &cobra.Command{
		Use:     "serve",
		Aliases: []string{"start"},
		Short:   "Start ollama",
Michael Yang's avatar
Michael Yang committed
1220
		Args:    cobra.ExactArgs(0),
Michael Yang's avatar
Michael Yang committed
1221
		RunE:    RunServer,
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1222
1223
	}

1224
	pullCmd := &cobra.Command{
1225
1226
		Use:     "pull MODEL",
		Short:   "Pull a model from a registry",
Michael Yang's avatar
Michael Yang committed
1227
		Args:    cobra.ExactArgs(1),
1228
1229
		PreRunE: checkServerHeartbeat,
		RunE:    PullHandler,
1230
1231
	}

1232
1233
	pullCmd.Flags().Bool("insecure", false, "Use an insecure registry")

1234
	pushCmd := &cobra.Command{
1235
1236
		Use:     "push MODEL",
		Short:   "Push a model to a registry",
Michael Yang's avatar
Michael Yang committed
1237
		Args:    cobra.ExactArgs(1),
1238
1239
		PreRunE: checkServerHeartbeat,
		RunE:    PushHandler,
1240
1241
	}

1242
1243
	pushCmd.Flags().Bool("insecure", false, "Use an insecure registry")

Patrick Devine's avatar
Patrick Devine committed
1244
	listCmd := &cobra.Command{
1245
		Use:     "list",
Patrick Devine's avatar
Patrick Devine committed
1246
		Aliases: []string{"ls"},
1247
		Short:   "List models",
1248
		PreRunE: checkServerHeartbeat,
1249
		RunE:    ListHandler,
1250
	}
1251
1252
1253
1254
1255
1256
1257
1258

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

Patrick Devine's avatar
Patrick Devine committed
1259
	copyCmd := &cobra.Command{
Michael Yang's avatar
Michael Yang committed
1260
		Use:     "cp SOURCE DESTINATION",
1261
		Short:   "Copy a model",
Michael Yang's avatar
Michael Yang committed
1262
		Args:    cobra.ExactArgs(2),
1263
1264
		PreRunE: checkServerHeartbeat,
		RunE:    CopyHandler,
Patrick Devine's avatar
Patrick Devine committed
1265
1266
	}

1267
	deleteCmd := &cobra.Command{
Michael Yang's avatar
Michael Yang committed
1268
		Use:     "rm MODEL [MODEL...]",
1269
1270
1271
1272
		Short:   "Remove a model",
		Args:    cobra.MinimumNArgs(1),
		PreRunE: checkServerHeartbeat,
		RunE:    DeleteHandler,
Patrick Devine's avatar
Patrick Devine committed
1273
1274
	}

1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
	runnerCmd := &cobra.Command{
		Use:    "runner",
		Short:  llama.PrintSystemInfo(),
		Hidden: true,
		RunE: func(cmd *cobra.Command, args []string) error {
			return runner.Execute(os.Args[1:])
		},
		FParseErrWhitelist: cobra.FParseErrWhitelist{UnknownFlags: true},
	}
	runnerCmd.SetHelpFunc(func(cmd *cobra.Command, args []string) {
		_ = runner.Execute(args[1:])
	})

1288
1289
1290
	envVars := envconfig.AsMap()

	envs := []envconfig.EnvVar{envVars["OLLAMA_HOST"]}
1291

1292
1293
1294
1295
	for _, cmd := range []*cobra.Command{
		createCmd,
		showCmd,
		runCmd,
Patrick Devine's avatar
Patrick Devine committed
1296
		stopCmd,
1297
1298
1299
		pullCmd,
		pushCmd,
		listCmd,
1300
		psCmd,
1301
1302
		copyCmd,
		deleteCmd,
1303
		serveCmd,
1304
	} {
1305
1306
		switch cmd {
		case runCmd:
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
			appendEnvDocs(cmd, []envconfig.EnvVar{envVars["OLLAMA_HOST"], envVars["OLLAMA_NOHISTORY"]})
		case serveCmd:
			appendEnvDocs(cmd, []envconfig.EnvVar{
				envVars["OLLAMA_DEBUG"],
				envVars["OLLAMA_HOST"],
				envVars["OLLAMA_KEEP_ALIVE"],
				envVars["OLLAMA_MAX_LOADED_MODELS"],
				envVars["OLLAMA_MAX_QUEUE"],
				envVars["OLLAMA_MODELS"],
				envVars["OLLAMA_NUM_PARALLEL"],
				envVars["OLLAMA_NOPRUNE"],
				envVars["OLLAMA_ORIGINS"],
1319
				envVars["OLLAMA_SCHED_SPREAD"],
1320
				envVars["OLLAMA_TMPDIR"],
1321
				envVars["OLLAMA_FLASH_ATTENTION"],
1322
				envVars["OLLAMA_KV_CACHE_TYPE"],
1323
				envVars["OLLAMA_LLM_LIBRARY"],
1324
				envVars["OLLAMA_GPU_OVERHEAD"],
1325
				envVars["OLLAMA_LOAD_TIMEOUT"],
1326
			})
1327
1328
1329
		default:
			appendEnvDocs(cmd, envs)
		}
1330
1331
	}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1332
1333
	rootCmd.AddCommand(
		serveCmd,
1334
		createCmd,
Patrick Devine's avatar
Patrick Devine committed
1335
		showCmd,
1336
		runCmd,
Patrick Devine's avatar
Patrick Devine committed
1337
		stopCmd,
1338
1339
		pullCmd,
		pushCmd,
Patrick Devine's avatar
Patrick Devine committed
1340
		listCmd,
1341
		psCmd,
Patrick Devine's avatar
Patrick Devine committed
1342
		copyCmd,
1343
		deleteCmd,
1344
		runnerCmd,
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1345
1346
1347
1348
	)

	return rootCmd
}