"vscode:/vscode.git/clone" did not exist on "c962f4ce80b790f51656bdff4d789c7deefa6dc2"
cmd.go 19.9 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/signal"
18
	"path/filepath"
Michael Yang's avatar
Michael Yang committed
19
	"strings"
20
	"syscall"
Michael Yang's avatar
Michael Yang committed
21
	"time"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
22

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

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

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

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

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

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

Michael Yang's avatar
Michael Yang committed
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
	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
	}

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

Michael Yang's avatar
Michael Yang committed
73
74
75
76
77
78
79
80
81
82
	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:])
			}

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

Michael Yang's avatar
Michael Yang committed
87
88
			bin, err := os.Open(path)
			if errors.Is(err, os.ErrNotExist) && c.Name == "model" {
Michael Yang's avatar
Michael Yang committed
89
				continue
Michael Yang's avatar
Michael Yang committed
90
91
92
93
94
95
96
97
98
99
100
101
			} 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
102
			if err = client.CreateBlob(cmd.Context(), digest, bin); err != nil {
Michael Yang's avatar
Michael Yang committed
103
104
105
				return err
			}

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

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

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

130
131
132
		return nil
	}

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

	return nil
}

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

147
	name := args[0]
148

149
	// check if the model exists on the server
150
	show, 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
		}
157
158
159
160
161

		show, err = client.Show(cmd.Context(), &api.ShowRequest{Name: name})
		if err != nil {
			return err
		}
Michael Yang's avatar
Michael Yang committed
162
163
	case err != nil:
		return err
164
165
	}

166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
	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

	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
210
211
}

212
func PushHandler(cmd *cobra.Command, args []string) error {
Michael Yang's avatar
Michael Yang committed
213
	client, err := api.ClientFromEnvironment()
214
215
216
	if err != nil {
		return err
	}
217

218
219
220
221
222
	insecure, err := cmd.Flags().GetBool("insecure")
	if err != nil {
		return err
	}

Michael Yang's avatar
Michael Yang committed
223
224
225
226
	p := progress.NewProgress(os.Stderr)
	defer p.Stop()

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

230
	fn := func(resp api.ProgressResponse) error {
Michael Yang's avatar
Michael Yang committed
231
		if resp.Digest != "" {
232
233
234
			if spinner != nil {
				spinner.Stop()
			}
Michael Yang's avatar
Michael Yang committed
235
236
237

			bar, ok := bars[resp.Digest]
			if !ok {
238
				bar = progress.NewBar(fmt.Sprintf("pushing %s...", resp.Digest[7:19]), resp.Total, resp.Completed)
Michael Yang's avatar
Michael Yang committed
239
240
241
242
243
244
				bars[resp.Digest] = bar
				p.Add(resp.Digest, bar)
			}

			bar.Set(resp.Completed)
		} else if status != resp.Status {
245
246
247
			if spinner != nil {
				spinner.Stop()
			}
Michael Yang's avatar
Michael Yang committed
248
249
250
251
252
253

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

254
255
256
		return nil
	}

Michael Yang's avatar
Michael Yang committed
257
	request := api.PushRequest{Name: args[0], Insecure: insecure}
Michael Yang's avatar
Michael Yang committed
258
	if err := client.Push(cmd.Context(), &request, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
259
260
261
		return err
	}

262
	spinner.Stop()
Michael Yang's avatar
Michael Yang committed
263
	return nil
264
265
}

266
func ListHandler(cmd *cobra.Command, args []string) error {
Michael Yang's avatar
Michael Yang committed
267
	client, err := api.ClientFromEnvironment()
268
269
270
	if err != nil {
		return err
	}
Patrick Devine's avatar
Patrick Devine committed
271

Michael Yang's avatar
Michael Yang committed
272
	models, err := client.List(cmd.Context())
Patrick Devine's avatar
Patrick Devine committed
273
274
275
276
277
278
279
	if err != nil {
		return err
	}

	var data [][]string

	for _, m := range models.Models {
Michael Yang's avatar
Michael Yang committed
280
		if len(args) == 0 || strings.HasPrefix(m.Name, args[0]) {
281
			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
282
		}
Patrick Devine's avatar
Patrick Devine committed
283
284
285
	}

	table := tablewriter.NewWriter(os.Stdout)
Patrick Devine's avatar
Patrick Devine committed
286
	table.SetHeader([]string{"NAME", "ID", "SIZE", "MODIFIED"})
Patrick Devine's avatar
Patrick Devine committed
287
288
289
290
291
292
293
294
295
296
297
298
	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
}

299
func DeleteHandler(cmd *cobra.Command, args []string) error {
Michael Yang's avatar
Michael Yang committed
300
	client, err := api.ClientFromEnvironment()
301
302
303
	if err != nil {
		return err
	}
304

305
306
	for _, name := range args {
		req := api.DeleteRequest{Name: name}
Michael Yang's avatar
Michael Yang committed
307
		if err := client.Delete(cmd.Context(), &req); err != nil {
308
309
310
			return err
		}
		fmt.Printf("deleted '%s'\n", name)
311
312
313
314
	}
	return nil
}

Patrick Devine's avatar
Patrick Devine committed
315
func ShowHandler(cmd *cobra.Command, args []string) error {
Michael Yang's avatar
Michael Yang committed
316
	client, err := api.ClientFromEnvironment()
Patrick Devine's avatar
Patrick Devine committed
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
	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 {
366
		return errors.New("only one of '--license', '--modelfile', '--parameters', '--system', or '--template' can be specified")
Patrick Devine's avatar
Patrick Devine committed
367
	} else if flagsSet == 0 {
368
		return errors.New("one of '--license', '--modelfile', '--parameters', '--system', or '--template' must be specified")
Patrick Devine's avatar
Patrick Devine committed
369
370
	}

371
	req := api.ShowRequest{Name: args[0]}
Michael Yang's avatar
Michael Yang committed
372
	resp, err := client.Show(cmd.Context(), &req)
Patrick Devine's avatar
Patrick Devine committed
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
	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
393
func CopyHandler(cmd *cobra.Command, args []string) error {
Michael Yang's avatar
Michael Yang committed
394
	client, err := api.ClientFromEnvironment()
395
396
397
	if err != nil {
		return err
	}
Patrick Devine's avatar
Patrick Devine committed
398
399

	req := api.CopyRequest{Source: args[0], Destination: args[1]}
Michael Yang's avatar
Michael Yang committed
400
	if err := client.Copy(cmd.Context(), &req); err != nil {
Patrick Devine's avatar
Patrick Devine committed
401
402
403
404
405
406
		return err
	}
	fmt.Printf("copied '%s' to '%s'\n", args[0], args[1])
	return nil
}

407
func PullHandler(cmd *cobra.Command, args []string) error {
408
409
410
411
412
	insecure, err := cmd.Flags().GetBool("insecure")
	if err != nil {
		return err
	}

Michael Yang's avatar
Michael Yang committed
413
	client, err := api.ClientFromEnvironment()
414
415
416
	if err != nil {
		return err
	}
417

Michael Yang's avatar
Michael Yang committed
418
419
420
421
422
	p := progress.NewProgress(os.Stderr)
	defer p.Stop()

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

423
424
	var status string
	var spinner *progress.Spinner
Michael Yang's avatar
Michael Yang committed
425

426
	fn := func(resp api.ProgressResponse) error {
Michael Yang's avatar
Michael Yang committed
427
		if resp.Digest != "" {
428
429
430
			if spinner != nil {
				spinner.Stop()
			}
Michael Yang's avatar
Michael Yang committed
431
432
433

			bar, ok := bars[resp.Digest]
			if !ok {
434
				bar = progress.NewBar(fmt.Sprintf("pulling %s...", resp.Digest[7:19]), resp.Total, resp.Completed)
Michael Yang's avatar
Michael Yang committed
435
436
437
438
439
440
				bars[resp.Digest] = bar
				p.Add(resp.Digest, bar)
			}

			bar.Set(resp.Completed)
		} else if status != resp.Status {
441
442
443
			if spinner != nil {
				spinner.Stop()
			}
Michael Yang's avatar
Michael Yang committed
444
445
446
447
448
449

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

450
451
		return nil
	}
452

Michael Yang's avatar
Michael Yang committed
453
	request := api.PullRequest{Name: args[0], Insecure: insecure}
Michael Yang's avatar
Michael Yang committed
454
	if err := client.Pull(cmd.Context(), &request, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
455
456
457
458
		return err
	}

	return nil
Michael Yang's avatar
Michael Yang committed
459
460
}

461
462
type generateContextKey string

463
type runOptions struct {
464
465
466
467
468
469
470
471
472
473
474
	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
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
591
592
593
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
594
	client, err := api.ClientFromEnvironment()
Patrick Devine's avatar
Patrick Devine committed
595
	if err != nil {
596
		return err
Patrick Devine's avatar
Patrick Devine committed
597
	}
Michael Yang's avatar
Michael Yang committed
598

Michael Yang's avatar
Michael Yang committed
599
	p := progress.NewProgress(os.Stderr)
600
	defer p.StopAndClear()
601

Michael Yang's avatar
Michael Yang committed
602
603
604
	spinner := progress.NewSpinner("")
	p.Add("", spinner)

605
606
607
608
609
610
611
	var latest api.GenerateResponse

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

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

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

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

623
	var state *displayResponseState = &displayResponseState{}
624

625
	fn := func(response api.GenerateResponse) error {
Michael Yang's avatar
Michael Yang committed
626
		p.StopAndClear()
627

Patrick Devine's avatar
Patrick Devine committed
628
		latest = response
629
		content := response.Response
630

631
		displayResponse(content, opts.WordWrap, state)
632

Patrick Devine's avatar
Patrick Devine committed
633
634
		return nil
	}
635

636
637
638
639
640
641
642
	if opts.MultiModal {
		opts.Prompt, opts.Images, err = extractFileData(opts.Prompt)
		if err != nil {
			return err
		}
	}

Michael Yang's avatar
Michael Yang committed
643
644
645
646
	request := api.GenerateRequest{
		Model:    opts.Model,
		Prompt:   opts.Prompt,
		Context:  generateContext,
647
		Images:   opts.Images,
Michael Yang's avatar
Michael Yang committed
648
649
650
651
652
653
654
		Format:   opts.Format,
		System:   opts.System,
		Template: opts.Template,
		Options:  opts.Options,
	}

	if err := client.Generate(ctx, &request, fn); err != nil {
655
		if errors.Is(err, context.Canceled) {
656
			return nil
657
		}
658
		return err
Patrick Devine's avatar
Patrick Devine committed
659
	}
660

661
	if opts.Prompt != "" {
Michael Yang's avatar
Michael Yang committed
662
663
		fmt.Println()
		fmt.Println()
Patrick Devine's avatar
Patrick Devine committed
664
	}
665

666
667
668
669
	if !latest.Done {
		return nil
	}

Patrick Devine's avatar
Patrick Devine committed
670
671
	verbose, err := cmd.Flags().GetBool("verbose")
	if err != nil {
672
		return err
Patrick Devine's avatar
Patrick Devine committed
673
	}
Michael Yang's avatar
Michael Yang committed
674

Patrick Devine's avatar
Patrick Devine committed
675
676
	if verbose {
		latest.Summary()
Michael Yang's avatar
Michael Yang committed
677
	}
Michael Yang's avatar
Michael Yang committed
678

Patrick Devine's avatar
Patrick Devine committed
679
680
681
	ctx = context.WithValue(cmd.Context(), generateContextKey("context"), latest.Context)
	cmd.SetContext(ctx)

682
	return nil
Michael Yang's avatar
Michael Yang committed
683
684
}

685
func RunServer(cmd *cobra.Command, _ []string) error {
Michael Yang's avatar
Michael Yang committed
686
687
688
	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
689
		if ip := net.ParseIP(strings.Trim(os.Getenv("OLLAMA_HOST"), "[]")); ip != nil {
Michael Yang's avatar
Michael Yang committed
690
691
			host = ip.String()
		}
Jeffrey Morgan's avatar
Jeffrey Morgan committed
692
	}
693

Michael Yang's avatar
Michael Yang committed
694
	if err := initializeKeypair(); err != nil {
695
696
697
		return err
	}

Michael Yang's avatar
Michael Yang committed
698
	ln, err := net.Listen("tcp", net.JoinHostPort(host, port))
699
700
701
	if err != nil {
		return err
	}
Jeffrey Morgan's avatar
Jeffrey Morgan committed
702

703
	return server.Serve(ln)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
704
705
}

706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
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
728
		err = os.MkdirAll(filepath.Dir(privKeyPath), 0o755)
729
730
731
732
		if err != nil {
			return fmt.Errorf("could not create directory %w", err)
		}

733
		err = os.WriteFile(privKeyPath, pem.EncodeToMemory(privKeyBytes), 0o600)
734
735
736
737
738
739
740
741
742
743
744
		if err != nil {
			return err
		}

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

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

745
		err = os.WriteFile(pubKeyPath, pubKeyData, 0o644)
746
747
748
749
750
751
752
753
754
		if err != nil {
			return err
		}

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

755
756
//nolint:unused
func waitForServer(ctx context.Context, client *api.Client) error {
Bruce MacDonald's avatar
Bruce MacDonald committed
757
758
759
760
761
762
763
764
	// 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
765
			if err := client.Heartbeat(ctx); err == nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
766
767
768
769
				return nil // server has started
			}
		}
	}
770

Bruce MacDonald's avatar
Bruce MacDonald committed
771
772
}

Michael Yang's avatar
Michael Yang committed
773
func checkServerHeartbeat(cmd *cobra.Command, _ []string) error {
Michael Yang's avatar
Michael Yang committed
774
	client, err := api.ClientFromEnvironment()
775
776
777
	if err != nil {
		return err
	}
Michael Yang's avatar
Michael Yang committed
778
	if err := client.Heartbeat(cmd.Context()); err != nil {
779
		if !strings.Contains(err.Error(), " refused") {
Bruce MacDonald's avatar
Bruce MacDonald committed
780
781
			return err
		}
782
783
		if err := startApp(cmd.Context(), client); err != nil {
			return fmt.Errorf("could not connect to ollama app, is it running?")
784
785
786
787
788
		}
	}
	return nil
}

Michael Yang's avatar
Michael Yang committed
789
790
791
792
793
794
795
796
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
797
798
799
800
801
		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
802
803
	}

804
	if serverVersion != version.Version {
Michael Yang's avatar
Michael Yang committed
805
		fmt.Printf("Warning: client version is %s\n", version.Version)
806
	}
Michael Yang's avatar
Michael Yang committed
807
808
}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
809
810
func NewCLI() *cobra.Command {
	log.SetFlags(log.LstdFlags | log.Lshortfile)
Michael Yang's avatar
Michael Yang committed
811
	cobra.EnableCommandSorting = false
Jeffrey Morgan's avatar
Jeffrey Morgan committed
812
813

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

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

833
	createCmd := &cobra.Command{
834
835
		Use:     "create MODEL",
		Short:   "Create a model from a Modelfile",
Michael Yang's avatar
Michael Yang committed
836
		Args:    cobra.ExactArgs(1),
837
838
		PreRunE: checkServerHeartbeat,
		RunE:    CreateHandler,
839
840
841
842
	}

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

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

Jeffrey Morgan's avatar
Jeffrey Morgan committed
857
	runCmd := &cobra.Command{
858
859
860
861
862
		Use:     "run MODEL [PROMPT]",
		Short:   "Run a model",
		Args:    cobra.MinimumNArgs(1),
		PreRunE: checkServerHeartbeat,
		RunE:    RunHandler,
Jeffrey Morgan's avatar
Jeffrey Morgan committed
863
864
	}

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

Jeffrey Morgan's avatar
Jeffrey Morgan committed
870
871
872
873
	serveCmd := &cobra.Command{
		Use:     "serve",
		Aliases: []string{"start"},
		Short:   "Start ollama",
Michael Yang's avatar
Michael Yang committed
874
		Args:    cobra.ExactArgs(0),
Michael Yang's avatar
Michael Yang committed
875
		RunE:    RunServer,
Jeffrey Morgan's avatar
Jeffrey Morgan committed
876
877
	}

878
	pullCmd := &cobra.Command{
879
880
		Use:     "pull MODEL",
		Short:   "Pull a model from a registry",
Michael Yang's avatar
Michael Yang committed
881
		Args:    cobra.ExactArgs(1),
882
883
		PreRunE: checkServerHeartbeat,
		RunE:    PullHandler,
884
885
	}

886
887
	pullCmd.Flags().Bool("insecure", false, "Use an insecure registry")

888
	pushCmd := &cobra.Command{
889
890
		Use:     "push MODEL",
		Short:   "Push a model to a registry",
Michael Yang's avatar
Michael Yang committed
891
		Args:    cobra.ExactArgs(1),
892
893
		PreRunE: checkServerHeartbeat,
		RunE:    PushHandler,
894
895
	}

896
897
	pushCmd.Flags().Bool("insecure", false, "Use an insecure registry")

Patrick Devine's avatar
Patrick Devine committed
898
	listCmd := &cobra.Command{
899
		Use:     "list",
Patrick Devine's avatar
Patrick Devine committed
900
		Aliases: []string{"ls"},
901
		Short:   "List models",
902
		PreRunE: checkServerHeartbeat,
903
		RunE:    ListHandler,
904
905
	}

Patrick Devine's avatar
Patrick Devine committed
906
	copyCmd := &cobra.Command{
Michael Yang's avatar
Michael Yang committed
907
		Use:     "cp SOURCE TARGET",
908
		Short:   "Copy a model",
Michael Yang's avatar
Michael Yang committed
909
		Args:    cobra.ExactArgs(2),
910
911
		PreRunE: checkServerHeartbeat,
		RunE:    CopyHandler,
Patrick Devine's avatar
Patrick Devine committed
912
913
	}

914
	deleteCmd := &cobra.Command{
Michael Yang's avatar
Michael Yang committed
915
		Use:     "rm MODEL [MODEL...]",
916
917
918
919
		Short:   "Remove a model",
		Args:    cobra.MinimumNArgs(1),
		PreRunE: checkServerHeartbeat,
		RunE:    DeleteHandler,
Patrick Devine's avatar
Patrick Devine committed
920
921
	}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
922
923
	rootCmd.AddCommand(
		serveCmd,
924
		createCmd,
Patrick Devine's avatar
Patrick Devine committed
925
		showCmd,
926
		runCmd,
927
928
		pullCmd,
		pushCmd,
Patrick Devine's avatar
Patrick Devine committed
929
		listCmd,
Patrick Devine's avatar
Patrick Devine committed
930
		copyCmd,
931
		deleteCmd,
Jeffrey Morgan's avatar
Jeffrey Morgan committed
932
933
934
935
	)

	return rootCmd
}