cmd.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. package cmd
  2. import (
  3. "bufio"
  4. "context"
  5. "errors"
  6. "fmt"
  7. "log"
  8. "net"
  9. "net/http"
  10. "os"
  11. "path/filepath"
  12. "strings"
  13. "time"
  14. "github.com/schollz/progressbar/v3"
  15. "github.com/spf13/cobra"
  16. "golang.org/x/term"
  17. "github.com/jmorganca/ollama/api"
  18. "github.com/jmorganca/ollama/server"
  19. )
  20. func cacheDir() string {
  21. home, err := os.UserHomeDir()
  22. if err != nil {
  23. panic(err)
  24. }
  25. return filepath.Join(home, ".ollama")
  26. }
  27. func create(cmd *cobra.Command, args []string) error {
  28. filename, _ := cmd.Flags().GetString("file")
  29. client := api.NewClient()
  30. request := api.CreateRequest{Name: args[0], Path: filename}
  31. fn := func(resp api.CreateProgress) error {
  32. fmt.Println(resp.Status)
  33. return nil
  34. }
  35. if err := client.Create(context.Background(), &request, fn); err != nil {
  36. return err
  37. }
  38. return nil
  39. }
  40. func RunRun(cmd *cobra.Command, args []string) error {
  41. _, err := os.Stat(args[0])
  42. switch {
  43. case errors.Is(err, os.ErrNotExist):
  44. if err := pull(args[0]); err != nil {
  45. var apiStatusError api.StatusError
  46. if !errors.As(err, &apiStatusError) {
  47. return err
  48. }
  49. if apiStatusError.StatusCode != http.StatusBadGateway {
  50. return err
  51. }
  52. }
  53. case err != nil:
  54. return err
  55. }
  56. return RunGenerate(cmd, args)
  57. }
  58. func push(cmd *cobra.Command, args []string) error {
  59. client := api.NewClient()
  60. request := api.PushRequest{Name: args[0]}
  61. fn := func(resp api.PushProgress) error {
  62. fmt.Println(resp.Status)
  63. return nil
  64. }
  65. if err := client.Push(context.Background(), &request, fn); err != nil {
  66. return err
  67. }
  68. return nil
  69. }
  70. func RunPull(cmd *cobra.Command, args []string) error {
  71. return pull(args[0])
  72. }
  73. func pull(model string) error {
  74. client := api.NewClient()
  75. request := api.PullRequest{Name: model}
  76. fn := func(resp api.PullProgress) error {
  77. fmt.Println(resp.Status)
  78. return nil
  79. }
  80. if err := client.Pull(context.Background(), &request, fn); err != nil {
  81. return err
  82. }
  83. return nil
  84. }
  85. func RunGenerate(cmd *cobra.Command, args []string) error {
  86. if len(args) > 1 {
  87. // join all args into a single prompt
  88. return generate(cmd, args[0], strings.Join(args[1:], " "))
  89. }
  90. if term.IsTerminal(int(os.Stdin.Fd())) {
  91. return generateInteractive(cmd, args[0])
  92. }
  93. return generateBatch(cmd, args[0])
  94. }
  95. var generateContextKey struct{}
  96. func generate(cmd *cobra.Command, model, prompt string) error {
  97. if len(strings.TrimSpace(prompt)) > 0 {
  98. client := api.NewClient()
  99. spinner := progressbar.NewOptions(-1,
  100. progressbar.OptionSetWriter(os.Stderr),
  101. progressbar.OptionThrottle(60*time.Millisecond),
  102. progressbar.OptionSpinnerType(14),
  103. progressbar.OptionSetRenderBlankState(true),
  104. progressbar.OptionSetElapsedTime(false),
  105. progressbar.OptionClearOnFinish(),
  106. )
  107. go func() {
  108. for range time.Tick(60 * time.Millisecond) {
  109. if spinner.IsFinished() {
  110. break
  111. }
  112. spinner.Add(1)
  113. }
  114. }()
  115. var latest api.GenerateResponse
  116. generateContext, ok := cmd.Context().Value(generateContextKey).([]int)
  117. if !ok {
  118. generateContext = []int{}
  119. }
  120. request := api.GenerateRequest{Model: model, Prompt: prompt, Context: generateContext}
  121. fn := func(resp api.GenerateResponse) error {
  122. if !spinner.IsFinished() {
  123. spinner.Finish()
  124. }
  125. latest = resp
  126. fmt.Print(resp.Response)
  127. cmd.SetContext(context.WithValue(cmd.Context(), generateContextKey, resp.Context))
  128. return nil
  129. }
  130. if err := client.Generate(context.Background(), &request, fn); err != nil {
  131. return err
  132. }
  133. fmt.Println()
  134. fmt.Println()
  135. verbose, err := cmd.Flags().GetBool("verbose")
  136. if err != nil {
  137. return err
  138. }
  139. if verbose {
  140. latest.Summary()
  141. }
  142. }
  143. return nil
  144. }
  145. func generateInteractive(cmd *cobra.Command, model string) error {
  146. fmt.Print(">>> ")
  147. scanner := bufio.NewScanner(os.Stdin)
  148. for scanner.Scan() {
  149. if err := generate(cmd, model, scanner.Text()); err != nil {
  150. return err
  151. }
  152. fmt.Print(">>> ")
  153. }
  154. return nil
  155. }
  156. func generateBatch(cmd *cobra.Command, model string) error {
  157. scanner := bufio.NewScanner(os.Stdin)
  158. for scanner.Scan() {
  159. prompt := scanner.Text()
  160. fmt.Printf(">>> %s\n", prompt)
  161. if err := generate(cmd, model, prompt); err != nil {
  162. return err
  163. }
  164. }
  165. return nil
  166. }
  167. func RunServer(_ *cobra.Command, _ []string) error {
  168. host := os.Getenv("OLLAMA_HOST")
  169. if host == "" {
  170. host = "127.0.0.1"
  171. }
  172. port := os.Getenv("OLLAMA_PORT")
  173. if port == "" {
  174. port = "11434"
  175. }
  176. ln, err := net.Listen("tcp", fmt.Sprintf("%s:%s", host, port))
  177. if err != nil {
  178. return err
  179. }
  180. return server.Serve(ln)
  181. }
  182. func NewCLI() *cobra.Command {
  183. log.SetFlags(log.LstdFlags | log.Lshortfile)
  184. rootCmd := &cobra.Command{
  185. Use: "ollama",
  186. Short: "Large language model runner",
  187. SilenceUsage: true,
  188. CompletionOptions: cobra.CompletionOptions{
  189. DisableDefaultCmd: true,
  190. },
  191. PersistentPreRunE: func(_ *cobra.Command, args []string) error {
  192. // create the models directory and it's parent
  193. return os.MkdirAll(filepath.Join(cacheDir(), "models"), 0o700)
  194. },
  195. }
  196. cobra.EnableCommandSorting = false
  197. createCmd := &cobra.Command{
  198. Use: "create MODEL",
  199. Short: "Create a model from a Modelfile",
  200. Args: cobra.MinimumNArgs(1),
  201. RunE: create,
  202. }
  203. createCmd.Flags().StringP("file", "f", "Modelfile", "Name of the Modelfile (default \"Modelfile\")")
  204. runCmd := &cobra.Command{
  205. Use: "run MODEL [PROMPT]",
  206. Short: "Run a model",
  207. Args: cobra.MinimumNArgs(1),
  208. RunE: RunRun,
  209. }
  210. runCmd.Flags().Bool("verbose", false, "Show timings for response")
  211. serveCmd := &cobra.Command{
  212. Use: "serve",
  213. Aliases: []string{"start"},
  214. Short: "Start ollama",
  215. RunE: RunServer,
  216. }
  217. pullCmd := &cobra.Command{
  218. Use: "pull MODEL",
  219. Short: "Pull a model from a registry",
  220. Args: cobra.MinimumNArgs(1),
  221. RunE: RunPull,
  222. }
  223. pushCmd := &cobra.Command{
  224. Use: "push MODEL",
  225. Short: "Push a model to a registry",
  226. Args: cobra.MinimumNArgs(1),
  227. RunE: push,
  228. }
  229. rootCmd.AddCommand(
  230. serveCmd,
  231. createCmd,
  232. runCmd,
  233. pullCmd,
  234. pushCmd,
  235. )
  236. return rootCmd
  237. }