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

import (
Michael Yang's avatar
Michael Yang committed
4
	"bytes"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
5
	"context"
6
7
	"crypto/ed25519"
	"crypto/rand"
Michael Yang's avatar
Michael Yang committed
8
	"crypto/sha256"
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
14
	"log"
	"net"
15
	"net/http"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
16
	"os"
17
	"os/exec"
18
	"os/signal"
19
	"path/filepath"
20
	"runtime"
Michael Yang's avatar
Michael Yang committed
21
	"strings"
22
	"syscall"
Michael Yang's avatar
Michael Yang committed
23
	"time"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
24

Patrick Devine's avatar
Patrick Devine committed
25
	"github.com/olekukonko/tablewriter"
Michael Yang's avatar
Michael Yang committed
26
	"github.com/spf13/cobra"
27
	"golang.org/x/crypto/ssh"
28
	"golang.org/x/term"
Michael Yang's avatar
Michael Yang committed
29

Jeffrey Morgan's avatar
Jeffrey Morgan committed
30
	"github.com/jmorganca/ollama/api"
Patrick Devine's avatar
Patrick Devine committed
31
	"github.com/jmorganca/ollama/format"
Michael Yang's avatar
Michael Yang committed
32
	"github.com/jmorganca/ollama/parser"
Michael Yang's avatar
Michael Yang committed
33
	"github.com/jmorganca/ollama/progress"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
34
	"github.com/jmorganca/ollama/server"
Michael Yang's avatar
Michael Yang committed
35
	"github.com/jmorganca/ollama/version"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
36
37
)

38
func CreateHandler(cmd *cobra.Command, args []string) error {
39
	filename, _ := cmd.Flags().GetString("file")
40
41
42
43
44
	filename, err := filepath.Abs(filename)
	if err != nil {
		return err
	}

Michael Yang's avatar
Michael Yang committed
45
	client, err := api.ClientFromEnvironment()
46
47
48
	if err != nil {
		return err
	}
49

Michael Yang's avatar
Michael Yang committed
50
51
52
53
54
	p := progress.NewProgress(os.Stderr)
	defer p.Stop()

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

Michael Yang's avatar
Michael Yang committed
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
	modelfile, err := os.ReadFile(filename)
	if err != nil {
		return err
	}

	commands, err := parser.Parse(bytes.NewReader(modelfile))
	if err != nil {
		return err
	}

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

70
71
	status := "transferring model data"
	spinner := progress.NewSpinner(status)
72
73
	p.Add(status, spinner)

Michael Yang's avatar
Michael Yang committed
74
75
76
77
78
79
80
81
82
83
	for _, c := range commands {
		switch c.Name {
		case "model", "adapter":
			path := c.Args
			if path == "~" {
				path = home
			} else if strings.HasPrefix(path, "~/") {
				path = filepath.Join(home, path[2:])
			}

84
85
86
87
			if !filepath.IsAbs(path) {
				path = filepath.Join(filepath.Dir(filename), path)
			}

Michael Yang's avatar
Michael Yang committed
88
89
			bin, err := os.Open(path)
			if errors.Is(err, os.ErrNotExist) && c.Name == "model" {
Michael Yang's avatar
Michael Yang committed
90
				continue
Michael Yang's avatar
Michael Yang committed
91
92
93
94
95
96
97
98
99
100
101
102
			} else if err != nil {
				return err
			}
			defer bin.Close()

			hash := sha256.New()
			if _, err := io.Copy(hash, bin); err != nil {
				return err
			}
			bin.Seek(0, io.SeekStart)

			digest := fmt.Sprintf("sha256:%x", hash.Sum(nil))
Michael Yang's avatar
Michael Yang committed
103
			if err = client.CreateBlob(cmd.Context(), digest, bin); err != nil {
Michael Yang's avatar
Michael Yang committed
104
105
106
				return err
			}

Michael Yang's avatar
Michael Yang committed
107
			modelfile = bytes.ReplaceAll(modelfile, []byte(c.Args), []byte("@"+digest))
Michael Yang's avatar
Michael Yang committed
108
109
		}
	}
Michael Yang's avatar
Michael Yang committed
110

111
	fn := func(resp api.ProgressResponse) error {
Michael Yang's avatar
Michael Yang committed
112
113
114
115
116
		if resp.Digest != "" {
			spinner.Stop()

			bar, ok := bars[resp.Digest]
			if !ok {
117
				bar = progress.NewBar(fmt.Sprintf("pulling %s...", resp.Digest[7:19]), resp.Total, resp.Completed)
Michael Yang's avatar
Michael Yang committed
118
119
120
121
122
123
124
125
126
127
128
129
130
				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)
		}

131
132
133
		return nil
	}

134
	request := api.CreateRequest{Name: args[0], Modelfile: string(modelfile)}
Michael Yang's avatar
Michael Yang committed
135
	if err := client.Create(cmd.Context(), &request, fn); err != nil {
136
137
138
139
140
141
		return err
	}

	return nil
}

142
func RunHandler(cmd *cobra.Command, args []string) error {
Michael Yang's avatar
Michael Yang committed
143
	client, err := api.ClientFromEnvironment()
144
145
146
147
	if err != nil {
		return err
	}

148
149
	name := args[0]
	// check if the model exists on the server
150
	_, err = client.Show(cmd.Context(), &api.ShowRequest{Name: name})
Michael Yang's avatar
Michael Yang committed
151
152
153
	var statusError api.StatusError
	switch {
	case errors.As(err, &statusError) && statusError.StatusCode == http.StatusNotFound:
154
		if err := PullHandler(cmd, []string{name}); err != nil {
155
			return err
Michael Yang's avatar
Michael Yang committed
156
		}
Michael Yang's avatar
Michael Yang committed
157
158
	case err != nil:
		return err
159
160
	}

161
	return RunGenerate(cmd, args)
Bruce MacDonald's avatar
Bruce MacDonald committed
162
163
}

164
func PushHandler(cmd *cobra.Command, args []string) error {
Michael Yang's avatar
Michael Yang committed
165
	client, err := api.ClientFromEnvironment()
166
167
168
	if err != nil {
		return err
	}
169

170
171
172
173
174
	insecure, err := cmd.Flags().GetBool("insecure")
	if err != nil {
		return err
	}

Michael Yang's avatar
Michael Yang committed
175
176
177
178
	p := progress.NewProgress(os.Stderr)
	defer p.Stop()

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

182
	fn := func(resp api.ProgressResponse) error {
Michael Yang's avatar
Michael Yang committed
183
		if resp.Digest != "" {
184
185
186
			if spinner != nil {
				spinner.Stop()
			}
Michael Yang's avatar
Michael Yang committed
187
188
189

			bar, ok := bars[resp.Digest]
			if !ok {
190
				bar = progress.NewBar(fmt.Sprintf("pushing %s...", resp.Digest[7:19]), resp.Total, resp.Completed)
Michael Yang's avatar
Michael Yang committed
191
192
193
194
195
196
				bars[resp.Digest] = bar
				p.Add(resp.Digest, bar)
			}

			bar.Set(resp.Completed)
		} else if status != resp.Status {
197
198
199
			if spinner != nil {
				spinner.Stop()
			}
Michael Yang's avatar
Michael Yang committed
200
201
202
203
204
205

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

206
207
208
		return nil
	}

Michael Yang's avatar
Michael Yang committed
209
	request := api.PushRequest{Name: args[0], Insecure: insecure}
Michael Yang's avatar
Michael Yang committed
210
	if err := client.Push(cmd.Context(), &request, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
211
212
213
		return err
	}

214
	spinner.Stop()
Michael Yang's avatar
Michael Yang committed
215
	return nil
216
217
}

218
func ListHandler(cmd *cobra.Command, args []string) error {
Michael Yang's avatar
Michael Yang committed
219
	client, err := api.ClientFromEnvironment()
220
221
222
	if err != nil {
		return err
	}
Patrick Devine's avatar
Patrick Devine committed
223

Michael Yang's avatar
Michael Yang committed
224
	models, err := client.List(cmd.Context())
Patrick Devine's avatar
Patrick Devine committed
225
226
227
228
229
230
231
	if err != nil {
		return err
	}

	var data [][]string

	for _, m := range models.Models {
Michael Yang's avatar
Michael Yang committed
232
		if len(args) == 0 || strings.HasPrefix(m.Name, args[0]) {
233
			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
234
		}
Patrick Devine's avatar
Patrick Devine committed
235
236
237
	}

	table := tablewriter.NewWriter(os.Stdout)
Patrick Devine's avatar
Patrick Devine committed
238
	table.SetHeader([]string{"NAME", "ID", "SIZE", "MODIFIED"})
Patrick Devine's avatar
Patrick Devine committed
239
240
241
242
243
244
245
246
247
248
249
250
	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
}

251
func DeleteHandler(cmd *cobra.Command, args []string) error {
Michael Yang's avatar
Michael Yang committed
252
	client, err := api.ClientFromEnvironment()
253
254
255
	if err != nil {
		return err
	}
256

257
258
	for _, name := range args {
		req := api.DeleteRequest{Name: name}
Michael Yang's avatar
Michael Yang committed
259
		if err := client.Delete(cmd.Context(), &req); err != nil {
260
261
262
			return err
		}
		fmt.Printf("deleted '%s'\n", name)
263
264
265
266
	}
	return nil
}

Patrick Devine's avatar
Patrick Devine committed
267
func ShowHandler(cmd *cobra.Command, args []string) error {
Michael Yang's avatar
Michael Yang committed
268
	client, err := api.ClientFromEnvironment()
Patrick Devine's avatar
Patrick Devine committed
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
	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 {
318
		return errors.New("only one of '--license', '--modelfile', '--parameters', '--system', or '--template' can be specified")
Patrick Devine's avatar
Patrick Devine committed
319
	} else if flagsSet == 0 {
320
		return errors.New("one of '--license', '--modelfile', '--parameters', '--system', or '--template' must be specified")
Patrick Devine's avatar
Patrick Devine committed
321
322
	}

323
	req := api.ShowRequest{Name: args[0]}
Michael Yang's avatar
Michael Yang committed
324
	resp, err := client.Show(cmd.Context(), &req)
Patrick Devine's avatar
Patrick Devine committed
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
	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
345
func CopyHandler(cmd *cobra.Command, args []string) error {
Michael Yang's avatar
Michael Yang committed
346
	client, err := api.ClientFromEnvironment()
347
348
349
	if err != nil {
		return err
	}
Patrick Devine's avatar
Patrick Devine committed
350
351

	req := api.CopyRequest{Source: args[0], Destination: args[1]}
Michael Yang's avatar
Michael Yang committed
352
	if err := client.Copy(cmd.Context(), &req); err != nil {
Patrick Devine's avatar
Patrick Devine committed
353
354
355
356
357
358
		return err
	}
	fmt.Printf("copied '%s' to '%s'\n", args[0], args[1])
	return nil
}

359
func PullHandler(cmd *cobra.Command, args []string) error {
360
361
362
363
364
	insecure, err := cmd.Flags().GetBool("insecure")
	if err != nil {
		return err
	}

Michael Yang's avatar
Michael Yang committed
365
	client, err := api.ClientFromEnvironment()
366
367
368
	if err != nil {
		return err
	}
369

Michael Yang's avatar
Michael Yang committed
370
371
372
373
374
	p := progress.NewProgress(os.Stderr)
	defer p.Stop()

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

375
376
	var status string
	var spinner *progress.Spinner
Michael Yang's avatar
Michael Yang committed
377

378
	fn := func(resp api.ProgressResponse) error {
Michael Yang's avatar
Michael Yang committed
379
		if resp.Digest != "" {
380
381
382
			if spinner != nil {
				spinner.Stop()
			}
Michael Yang's avatar
Michael Yang committed
383
384
385

			bar, ok := bars[resp.Digest]
			if !ok {
386
				bar = progress.NewBar(fmt.Sprintf("pulling %s...", resp.Digest[7:19]), resp.Total, resp.Completed)
Michael Yang's avatar
Michael Yang committed
387
388
389
390
391
392
				bars[resp.Digest] = bar
				p.Add(resp.Digest, bar)
			}

			bar.Set(resp.Completed)
		} else if status != resp.Status {
393
394
395
			if spinner != nil {
				spinner.Stop()
			}
Michael Yang's avatar
Michael Yang committed
396
397
398
399
400
401

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

402
403
		return nil
	}
404

Michael Yang's avatar
Michael Yang committed
405
	request := api.PullRequest{Name: args[0], Insecure: insecure}
Michael Yang's avatar
Michael Yang committed
406
	if err := client.Pull(cmd.Context(), &request, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
407
408
409
410
		return err
	}

	return nil
Michael Yang's avatar
Michael Yang committed
411
412
}

413
414
415
func RunGenerate(cmd *cobra.Command, args []string) error {
	interactive := true

416
	opts := runOptions{
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
		Model:    args[0],
		WordWrap: os.Getenv("TERM") == "xterm-256color",
		Options:  map[string]interface{}{},
	}

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

	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)
}

type generateContextKey string

460
type runOptions struct {
461
462
463
464
465
466
467
468
469
470
471
	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
472
473
}

474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
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
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
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 {
			if state.lineLength+1 > termWidth-5 {
				if len(state.wordBuffer) > termWidth-10 {
					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
				fmt.Printf("\x1b[%dD\x1b[K\n", len(state.wordBuffer))
				fmt.Printf("%s%c", state.wordBuffer, ch)
				state.lineLength = len(state.wordBuffer) + 1
			} else {
				fmt.Print(string(ch))
				state.lineLength += 1

				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,
	}

	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
591
	client, err := api.ClientFromEnvironment()
Patrick Devine's avatar
Patrick Devine committed
592
	if err != nil {
593
		return err
Patrick Devine's avatar
Patrick Devine committed
594
	}
Michael Yang's avatar
Michael Yang committed
595

Michael Yang's avatar
Michael Yang committed
596
	p := progress.NewProgress(os.Stderr)
597
	defer p.StopAndClear()
598

Michael Yang's avatar
Michael Yang committed
599
600
601
	spinner := progress.NewSpinner("")
	p.Add("", spinner)

602
603
604
605
606
607
608
	var latest api.GenerateResponse

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

Michael Yang's avatar
Michael Yang committed
609
	ctx, cancel := context.WithCancel(cmd.Context())
610
611
612
613
614
615
616
617
618
619
	defer cancel()

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

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

620
	var state *displayResponseState = &displayResponseState{}
621

622
	fn := func(response api.GenerateResponse) error {
Michael Yang's avatar
Michael Yang committed
623
		p.StopAndClear()
624

Patrick Devine's avatar
Patrick Devine committed
625
		latest = response
626
		content := response.Response
627

628
		displayResponse(content, opts.WordWrap, state)
629

Patrick Devine's avatar
Patrick Devine committed
630
631
		return nil
	}
632

Michael Yang's avatar
Michael Yang committed
633
634
635
636
637
638
639
640
641
642
643
	request := api.GenerateRequest{
		Model:    opts.Model,
		Prompt:   opts.Prompt,
		Context:  generateContext,
		Format:   opts.Format,
		System:   opts.System,
		Template: opts.Template,
		Options:  opts.Options,
	}

	if err := client.Generate(ctx, &request, fn); err != nil {
644
		if errors.Is(err, context.Canceled) {
645
			return nil
646
		}
647
		return err
Patrick Devine's avatar
Patrick Devine committed
648
	}
649

650
	if opts.Prompt != "" {
Michael Yang's avatar
Michael Yang committed
651
652
		fmt.Println()
		fmt.Println()
Patrick Devine's avatar
Patrick Devine committed
653
	}
654

655
656
657
658
	if !latest.Done {
		return nil
	}

Patrick Devine's avatar
Patrick Devine committed
659
660
	verbose, err := cmd.Flags().GetBool("verbose")
	if err != nil {
661
		return err
Patrick Devine's avatar
Patrick Devine committed
662
	}
Michael Yang's avatar
Michael Yang committed
663

Patrick Devine's avatar
Patrick Devine committed
664
665
	if verbose {
		latest.Summary()
Michael Yang's avatar
Michael Yang committed
666
	}
Michael Yang's avatar
Michael Yang committed
667

Patrick Devine's avatar
Patrick Devine committed
668
669
670
	ctx = context.WithValue(cmd.Context(), generateContextKey("context"), latest.Context)
	cmd.SetContext(ctx)

671
	return nil
Michael Yang's avatar
Michael Yang committed
672
673
}

674
func RunServer(cmd *cobra.Command, _ []string) error {
Michael Yang's avatar
Michael Yang committed
675
676
677
	host, port, err := net.SplitHostPort(os.Getenv("OLLAMA_HOST"))
	if err != nil {
		host, port = "127.0.0.1", "11434"
Michael Yang's avatar
Michael Yang committed
678
		if ip := net.ParseIP(strings.Trim(os.Getenv("OLLAMA_HOST"), "[]")); ip != nil {
Michael Yang's avatar
Michael Yang committed
679
680
			host = ip.String()
		}
Jeffrey Morgan's avatar
Jeffrey Morgan committed
681
	}
682

Michael Yang's avatar
Michael Yang committed
683
	if err := initializeKeypair(); err != nil {
684
685
686
		return err
	}

Michael Yang's avatar
Michael Yang committed
687
	ln, err := net.Listen("tcp", net.JoinHostPort(host, port))
688
689
690
	if err != nil {
		return err
	}
Jeffrey Morgan's avatar
Jeffrey Morgan committed
691

692
	return server.Serve(ln)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
693
694
}

695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
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)
		_, privKey, err := ed25519.GenerateKey(rand.Reader)
		if err != nil {
			return err
		}

		privKeyBytes, err := format.OpenSSHPrivateKey(privKey, "")
		if err != nil {
			return err
		}

Michael Yang's avatar
Michael Yang committed
717
		err = os.MkdirAll(filepath.Dir(privKeyPath), 0o755)
718
719
720
721
		if err != nil {
			return fmt.Errorf("could not create directory %w", err)
		}

722
		err = os.WriteFile(privKeyPath, pem.EncodeToMemory(privKeyBytes), 0o600)
723
724
725
726
727
728
729
730
731
732
733
		if err != nil {
			return err
		}

		sshPrivateKey, err := ssh.NewSignerFromKey(privKey)
		if err != nil {
			return err
		}

		pubKeyData := ssh.MarshalAuthorizedKey(sshPrivateKey.PublicKey())

734
		err = os.WriteFile(pubKeyPath, pubKeyData, 0o644)
735
736
737
738
739
740
741
742
743
		if err != nil {
			return err
		}

		fmt.Printf("Your new public key is: \n\n%s\n", string(pubKeyData))
	}
	return nil
}

Michael Yang's avatar
Michael Yang committed
744
func startMacApp(ctx context.Context, client *api.Client) error {
Bruce MacDonald's avatar
Bruce MacDonald committed
745
746
747
748
749
	exe, err := os.Executable()
	if err != nil {
		return err
	}
	link, err := os.Readlink(exe)
Bruce MacDonald's avatar
Bruce MacDonald committed
750
751
752
	if err != nil {
		return err
	}
Bruce MacDonald's avatar
Bruce MacDonald committed
753
754
755
	if !strings.Contains(link, "Ollama.app") {
		return fmt.Errorf("could not find ollama app")
	}
Bruce MacDonald's avatar
Bruce MacDonald committed
756
757
758
759
760
761
762
763
764
765
766
767
	path := strings.Split(link, "Ollama.app")
	if err := exec.Command("/usr/bin/open", "-a", path[0]+"Ollama.app").Run(); err != nil {
		return err
	}
	// 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
768
			if err := client.Heartbeat(ctx); err == nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
769
770
771
772
773
774
				return nil // server has started
			}
		}
	}
}

Michael Yang's avatar
Michael Yang committed
775
func checkServerHeartbeat(cmd *cobra.Command, _ []string) error {
Michael Yang's avatar
Michael Yang committed
776
	client, err := api.ClientFromEnvironment()
777
778
779
	if err != nil {
		return err
	}
Michael Yang's avatar
Michael Yang committed
780
	if err := client.Heartbeat(cmd.Context()); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
781
782
783
784
		if !strings.Contains(err.Error(), "connection refused") {
			return err
		}
		if runtime.GOOS == "darwin" {
Michael Yang's avatar
Michael Yang committed
785
			if err := startMacApp(cmd.Context(), client); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
786
				return fmt.Errorf("could not connect to ollama app, is it running?")
787
			}
Bruce MacDonald's avatar
Bruce MacDonald committed
788
		} else {
789
790
791
792
793
794
			return fmt.Errorf("could not connect to ollama server, run 'ollama serve' to start it")
		}
	}
	return nil
}

Michael Yang's avatar
Michael Yang committed
795
796
797
798
799
800
801
802
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
803
804
805
806
807
		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
808
809
	}

810
	if serverVersion != version.Version {
Michael Yang's avatar
Michael Yang committed
811
		fmt.Printf("Warning: client version is %s\n", version.Version)
812
	}
Michael Yang's avatar
Michael Yang committed
813
814
}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
815
816
func NewCLI() *cobra.Command {
	log.SetFlags(log.LstdFlags | log.Lshortfile)
Michael Yang's avatar
Michael Yang committed
817
	cobra.EnableCommandSorting = false
Jeffrey Morgan's avatar
Jeffrey Morgan committed
818
819

	rootCmd := &cobra.Command{
820
821
822
823
		Use:           "ollama",
		Short:         "Large language model runner",
		SilenceUsage:  true,
		SilenceErrors: true,
Jeffrey Morgan's avatar
Jeffrey Morgan committed
824
825
826
		CompletionOptions: cobra.CompletionOptions{
			DisableDefaultCmd: true,
		},
Michael Yang's avatar
Michael Yang committed
827
828
829
830
831
832
833
834
		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
835
836
	}

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

839
	createCmd := &cobra.Command{
840
841
		Use:     "create MODEL",
		Short:   "Create a model from a Modelfile",
Michael Yang's avatar
Michael Yang committed
842
		Args:    cobra.ExactArgs(1),
843
844
		PreRunE: checkServerHeartbeat,
		RunE:    CreateHandler,
845
846
847
848
	}

	createCmd.Flags().StringP("file", "f", "Modelfile", "Name of the Modelfile (default \"Modelfile\")")

Patrick Devine's avatar
Patrick Devine committed
849
850
851
	showCmd := &cobra.Command{
		Use:     "show MODEL",
		Short:   "Show information for a model",
Michael Yang's avatar
Michael Yang committed
852
		Args:    cobra.ExactArgs(1),
Patrick Devine's avatar
Patrick Devine committed
853
854
855
856
857
858
859
860
		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")
861
	showCmd.Flags().Bool("system", false, "Show system message of a model")
Patrick Devine's avatar
Patrick Devine committed
862

Jeffrey Morgan's avatar
Jeffrey Morgan committed
863
	runCmd := &cobra.Command{
864
865
866
867
868
		Use:     "run MODEL [PROMPT]",
		Short:   "Run a model",
		Args:    cobra.MinimumNArgs(1),
		PreRunE: checkServerHeartbeat,
		RunE:    RunHandler,
Jeffrey Morgan's avatar
Jeffrey Morgan committed
869
870
	}

871
	runCmd.Flags().Bool("verbose", false, "Show timings for response")
872
	runCmd.Flags().Bool("insecure", false, "Use an insecure registry")
873
	runCmd.Flags().Bool("nowordwrap", false, "Don't wrap words to the next line automatically")
Jeffrey Morgan's avatar
Jeffrey Morgan committed
874
	runCmd.Flags().String("format", "", "Response format (e.g. json)")
875

Jeffrey Morgan's avatar
Jeffrey Morgan committed
876
877
878
879
	serveCmd := &cobra.Command{
		Use:     "serve",
		Aliases: []string{"start"},
		Short:   "Start ollama",
Michael Yang's avatar
Michael Yang committed
880
		Args:    cobra.ExactArgs(0),
Michael Yang's avatar
Michael Yang committed
881
		RunE:    RunServer,
Jeffrey Morgan's avatar
Jeffrey Morgan committed
882
883
	}

884
	pullCmd := &cobra.Command{
885
886
		Use:     "pull MODEL",
		Short:   "Pull a model from a registry",
Michael Yang's avatar
Michael Yang committed
887
		Args:    cobra.ExactArgs(1),
888
889
		PreRunE: checkServerHeartbeat,
		RunE:    PullHandler,
890
891
	}

892
893
	pullCmd.Flags().Bool("insecure", false, "Use an insecure registry")

894
	pushCmd := &cobra.Command{
895
896
		Use:     "push MODEL",
		Short:   "Push a model to a registry",
Michael Yang's avatar
Michael Yang committed
897
		Args:    cobra.ExactArgs(1),
898
899
		PreRunE: checkServerHeartbeat,
		RunE:    PushHandler,
900
901
	}

902
903
	pushCmd.Flags().Bool("insecure", false, "Use an insecure registry")

Patrick Devine's avatar
Patrick Devine committed
904
	listCmd := &cobra.Command{
905
		Use:     "list",
Patrick Devine's avatar
Patrick Devine committed
906
		Aliases: []string{"ls"},
907
		Short:   "List models",
908
		PreRunE: checkServerHeartbeat,
909
		RunE:    ListHandler,
910
911
	}

Patrick Devine's avatar
Patrick Devine committed
912
	copyCmd := &cobra.Command{
Michael Yang's avatar
Michael Yang committed
913
		Use:     "cp SOURCE TARGET",
914
		Short:   "Copy a model",
Michael Yang's avatar
Michael Yang committed
915
		Args:    cobra.ExactArgs(2),
916
917
		PreRunE: checkServerHeartbeat,
		RunE:    CopyHandler,
Patrick Devine's avatar
Patrick Devine committed
918
919
	}

920
	deleteCmd := &cobra.Command{
Michael Yang's avatar
Michael Yang committed
921
		Use:     "rm MODEL [MODEL...]",
922
923
924
925
		Short:   "Remove a model",
		Args:    cobra.MinimumNArgs(1),
		PreRunE: checkServerHeartbeat,
		RunE:    DeleteHandler,
Patrick Devine's avatar
Patrick Devine committed
926
927
	}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
928
929
	rootCmd.AddCommand(
		serveCmd,
930
		createCmd,
Patrick Devine's avatar
Patrick Devine committed
931
		showCmd,
932
		runCmd,
933
934
		pullCmd,
		pushCmd,
Patrick Devine's avatar
Patrick Devine committed
935
		listCmd,
Patrick Devine's avatar
Patrick Devine committed
936
		copyCmd,
937
		deleteCmd,
Jeffrey Morgan's avatar
Jeffrey Morgan committed
938
939
940
941
	)

	return rootCmd
}