ollama/cmd/cmd.go

438 lines
8.7 KiB
Go
Raw Normal View History

package cmd
import (
2023-07-06 20:49:31 +00:00
"bufio"
"context"
2023-07-06 22:43:04 +00:00
"errors"
2023-07-06 16:24:49 +00:00
"fmt"
2023-07-18 21:01:19 +00:00
"io"
"log"
"net"
2023-07-11 20:05:51 +00:00
"net/http"
"os"
"path/filepath"
2023-07-07 17:12:58 +00:00
"strings"
2023-07-06 22:43:04 +00:00
"time"
2023-07-18 21:01:19 +00:00
"github.com/chzyer/readline"
2023-07-18 16:09:45 +00:00
"github.com/dustin/go-humanize"
"github.com/olekukonko/tablewriter"
2023-07-06 21:05:55 +00:00
"github.com/schollz/progressbar/v3"
2023-07-06 20:49:31 +00:00
"github.com/spf13/cobra"
2023-07-03 20:32:48 +00:00
"github.com/jmorganca/ollama/api"
2023-07-18 16:09:45 +00:00
"github.com/jmorganca/ollama/format"
2023-07-03 20:32:48 +00:00
"github.com/jmorganca/ollama/server"
)
func create(cmd *cobra.Command, args []string) error {
filename, _ := cmd.Flags().GetString("file")
filename, err := filepath.Abs(filename)
if err != nil {
return err
}
client := api.NewClient()
2023-07-17 21:14:41 +00:00
var spinner *Spinner
request := api.CreateRequest{Name: args[0], Path: filename}
fn := func(resp api.CreateProgress) error {
2023-07-17 21:14:41 +00:00
if spinner != nil {
spinner.Stop()
}
spinner = NewSpinner(resp.Status)
go spinner.Spin(100 * time.Millisecond)
return nil
}
if err := client.Create(context.Background(), &request, fn); err != nil {
return err
}
2023-07-17 21:14:41 +00:00
if spinner != nil {
spinner.Stop()
}
return nil
}
2023-07-06 21:05:55 +00:00
func RunRun(cmd *cobra.Command, args []string) error {
2023-07-18 05:44:21 +00:00
mp := server.ParseModelPath(args[0])
fp, err := mp.GetManifestPath(false)
if err != nil {
return err
}
_, err = os.Stat(fp)
2023-07-06 22:43:04 +00:00
switch {
case errors.Is(err, os.ErrNotExist):
if err := pull(args[0]); err != nil {
2023-07-11 20:05:51 +00:00
var apiStatusError api.StatusError
if !errors.As(err, &apiStatusError) {
return err
}
if apiStatusError.StatusCode != http.StatusBadGateway {
return err
}
2023-07-06 22:43:04 +00:00
}
case err != nil:
2023-07-06 21:05:55 +00:00
return err
}
return RunGenerate(cmd, args)
2023-07-06 18:18:40 +00:00
}
func push(cmd *cobra.Command, args []string) error {
client := api.NewClient()
request := api.PushRequest{Name: args[0]}
2023-07-19 01:51:30 +00:00
fn := func(resp api.ProgressResponse) error {
fmt.Println(resp.Status)
return nil
}
if err := client.Push(context.Background(), &request, fn); err != nil {
return err
}
return nil
}
2023-07-18 16:09:45 +00:00
func list(cmd *cobra.Command, args []string) error {
client := api.NewClient()
models, err := client.List(context.Background())
if err != nil {
return err
}
var data [][]string
for _, m := range models.Models {
2023-07-18 21:01:19 +00:00
if len(args) == 0 || strings.HasPrefix(m.Name, args[0]) {
data = append(data, []string{m.Name, humanize.Bytes(uint64(m.Size)), format.HumanTime(m.ModifiedAt, "Never")})
}
2023-07-18 16:09:45 +00:00
}
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"NAME", "SIZE", "MODIFIED"})
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
}
func RunPull(cmd *cobra.Command, args []string) error {
return pull(args[0])
}
2023-07-06 21:05:55 +00:00
func pull(model string) error {
2023-07-07 18:26:58 +00:00
client := api.NewClient()
2023-07-19 01:51:30 +00:00
var currentDigest string
2023-07-07 18:26:58 +00:00
var bar *progressbar.ProgressBar
2023-07-11 20:05:51 +00:00
request := api.PullRequest{Name: model}
2023-07-19 01:51:30 +00:00
fn := func(resp api.ProgressResponse) error {
if resp.Digest != currentDigest && resp.Digest != "" {
currentDigest = resp.Digest
bar = progressbar.DefaultBytes(
int64(resp.Total),
2023-07-19 01:51:30 +00:00
fmt.Sprintf("pulling %s...", resp.Digest[7:19]),
)
2023-07-19 01:51:30 +00:00
bar.Set(resp.Completed)
} else if resp.Digest == currentDigest && resp.Digest != "" {
bar.Set(resp.Completed)
} else {
2023-07-19 01:51:30 +00:00
currentDigest = ""
fmt.Println(resp.Status)
}
return nil
}
2023-07-07 14:22:37 +00:00
if err := client.Pull(context.Background(), &request, fn); err != nil {
return err
}
return nil
2023-07-06 20:49:31 +00:00
}
2023-07-13 01:18:06 +00:00
func RunGenerate(cmd *cobra.Command, args []string) error {
2023-07-06 20:49:31 +00:00
if len(args) > 1 {
2023-07-12 16:55:07 +00:00
// join all args into a single prompt
2023-07-13 01:18:06 +00:00
return generate(cmd, args[0], strings.Join(args[1:], " "))
2023-07-06 20:49:31 +00:00
}
2023-07-18 21:01:19 +00:00
if readline.IsTerminal(int(os.Stdin.Fd())) {
2023-07-13 01:18:06 +00:00
return generateInteractive(cmd, args[0])
2023-07-06 20:49:31 +00:00
}
2023-07-13 01:18:06 +00:00
return generateBatch(cmd, args[0])
2023-07-06 20:49:31 +00:00
}
var generateContextKey struct{}
2023-07-13 01:18:06 +00:00
func generate(cmd *cobra.Command, model, prompt string) error {
2023-07-07 17:12:58 +00:00
if len(strings.TrimSpace(prompt)) > 0 {
client := api.NewClient()
2023-07-17 21:14:41 +00:00
spinner := NewSpinner("")
go spinner.Spin(60 * time.Millisecond)
2023-07-06 22:43:04 +00:00
2023-07-13 01:18:06 +00:00
var latest api.GenerateResponse
generateContext, ok := cmd.Context().Value(generateContextKey).([]int)
if !ok {
generateContext = []int{}
}
request := api.GenerateRequest{Model: model, Prompt: prompt, Context: generateContext}
2023-07-07 21:04:43 +00:00
fn := func(resp api.GenerateResponse) error {
2023-07-07 17:12:58 +00:00
if !spinner.IsFinished() {
spinner.Finish()
}
2023-07-06 22:43:04 +00:00
2023-07-13 01:18:06 +00:00
latest = resp
2023-07-07 17:12:58 +00:00
fmt.Print(resp.Response)
cmd.SetContext(context.WithValue(cmd.Context(), generateContextKey, resp.Context))
2023-07-07 17:12:58 +00:00
return nil
2023-07-07 21:04:43 +00:00
}
if err := client.Generate(context.Background(), &request, fn); err != nil {
return err
}
2023-07-06 22:43:04 +00:00
2023-07-07 17:12:58 +00:00
fmt.Println()
fmt.Println()
2023-07-13 01:18:06 +00:00
verbose, err := cmd.Flags().GetBool("verbose")
if err != nil {
return err
}
if verbose {
latest.Summary()
}
2023-07-07 17:12:58 +00:00
}
2023-07-06 20:49:31 +00:00
return nil
}
2023-07-13 01:18:06 +00:00
func generateInteractive(cmd *cobra.Command, model string) error {
2023-07-18 21:01:19 +00:00
home, err := os.UserHomeDir()
if err != nil {
return err
}
completer := readline.NewPrefixCompleter(
readline.PcItem("/help"),
readline.PcItem("/list"),
readline.PcItem("/set",
readline.PcItem("history"),
readline.PcItem("nohistory"),
2023-07-19 16:25:23 +00:00
readline.PcItem("verbose"),
readline.PcItem("quiet"),
2023-07-18 21:01:19 +00:00
readline.PcItem("mode",
readline.PcItem("vim"),
readline.PcItem("emacs"),
readline.PcItem("default"),
),
),
readline.PcItem("/exit"),
readline.PcItem("/bye"),
)
usage := func() {
fmt.Fprintln(os.Stderr, "commands:")
fmt.Fprintln(os.Stderr, completer.Tree(" "))
}
config := readline.Config{
Prompt: ">>> ",
HistoryFile: filepath.Join(home, ".ollama", "history"),
AutoComplete: completer,
}
scanner, err := readline.NewEx(&config)
if err != nil {
return err
}
defer scanner.Close()
for {
line, err := scanner.Readline()
switch {
case errors.Is(err, io.EOF):
return nil
case errors.Is(err, readline.ErrInterrupt):
continue
case err != nil:
2023-07-06 20:49:31 +00:00
return err
}
2023-07-18 21:01:19 +00:00
line = strings.TrimSpace(line)
2023-07-06 20:49:31 +00:00
2023-07-18 21:01:19 +00:00
switch {
case strings.HasPrefix(line, "/list"):
args := strings.Fields(line)
if err := list(cmd, args[1:]); err != nil {
return err
}
continue
case strings.HasPrefix(line, "/set"):
args := strings.Fields(line)
if len(args) > 1 {
switch args[1] {
case "history":
scanner.HistoryEnable()
continue
case "nohistory":
scanner.HistoryDisable()
continue
2023-07-19 16:25:23 +00:00
case "verbose":
cmd.Flags().Set("verbose", "true")
continue
case "quiet":
cmd.Flags().Set("verbose", "false")
continue
2023-07-18 21:01:19 +00:00
case "mode":
if len(args) > 2 {
switch args[2] {
case "vim":
scanner.SetVimMode(true)
continue
case "emacs", "default":
scanner.SetVimMode(false)
continue
}
}
}
}
case line == "/help", line == "/?":
usage()
continue
case line == "/exit", line == "/bye":
return nil
}
if err := generate(cmd, model, line); err != nil {
return err
}
}
2023-07-06 16:24:49 +00:00
}
2023-07-13 01:18:06 +00:00
func generateBatch(cmd *cobra.Command, model string) error {
2023-07-06 20:49:31 +00:00
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
prompt := scanner.Text()
fmt.Printf(">>> %s\n", prompt)
2023-07-13 01:18:06 +00:00
if err := generate(cmd, model, prompt); err != nil {
2023-07-06 20:49:31 +00:00
return err
}
}
return nil
}
func RunServer(_ *cobra.Command, _ []string) error {
host := os.Getenv("OLLAMA_HOST")
if host == "" {
host = "127.0.0.1"
}
port := os.Getenv("OLLAMA_PORT")
if port == "" {
port = "11434"
}
ln, err := net.Listen("tcp", fmt.Sprintf("%s:%s", host, port))
2023-07-04 04:47:00 +00:00
if err != nil {
return err
}
return server.Serve(ln)
}
func NewCLI() *cobra.Command {
log.SetFlags(log.LstdFlags | log.Lshortfile)
rootCmd := &cobra.Command{
2023-07-06 20:49:31 +00:00
Use: "ollama",
Short: "Large language model runner",
SilenceUsage: true,
CompletionOptions: cobra.CompletionOptions{
DisableDefaultCmd: true,
},
}
cobra.EnableCommandSorting = false
createCmd := &cobra.Command{
Use: "create MODEL",
Short: "Create a model from a Modelfile",
Args: cobra.MinimumNArgs(1),
RunE: create,
}
createCmd.Flags().StringP("file", "f", "Modelfile", "Name of the Modelfile (default \"Modelfile\")")
runCmd := &cobra.Command{
2023-07-06 20:49:31 +00:00
Use: "run MODEL [PROMPT]",
2023-07-04 04:47:00 +00:00
Short: "Run a model",
2023-07-06 20:49:31 +00:00
Args: cobra.MinimumNArgs(1),
RunE: RunRun,
}
2023-07-13 01:18:06 +00:00
runCmd.Flags().Bool("verbose", false, "Show timings for response")
serveCmd := &cobra.Command{
Use: "serve",
Aliases: []string{"start"},
Short: "Start ollama",
2023-07-06 20:49:31 +00:00
RunE: RunServer,
}
pullCmd := &cobra.Command{
Use: "pull MODEL",
Short: "Pull a model from a registry",
Args: cobra.MinimumNArgs(1),
RunE: RunPull,
}
pushCmd := &cobra.Command{
Use: "push MODEL",
Short: "Push a model to a registry",
Args: cobra.MinimumNArgs(1),
RunE: push,
}
2023-07-18 16:09:45 +00:00
listCmd := &cobra.Command{
Use: "list",
Short: "List models",
RunE: list,
}
rootCmd.AddCommand(
serveCmd,
createCmd,
runCmd,
pullCmd,
pushCmd,
2023-07-18 16:09:45 +00:00
listCmd,
)
return rootCmd
}