cmd.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package cmd
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "net"
  7. "os"
  8. "path"
  9. "github.com/jmorganca/ollama/api"
  10. "github.com/jmorganca/ollama/server"
  11. "github.com/spf13/cobra"
  12. )
  13. func cacheDir() string {
  14. home, err := os.UserHomeDir()
  15. if err != nil {
  16. panic(err)
  17. }
  18. return path.Join(home, ".ollama")
  19. }
  20. func run(model string) error {
  21. client, err := NewAPIClient()
  22. if err != nil {
  23. return err
  24. }
  25. pr := api.PullRequest{
  26. Model: model,
  27. }
  28. callback := func(progress string) {
  29. fmt.Println(progress)
  30. }
  31. _, err = client.Pull(context.Background(), &pr, callback)
  32. return err
  33. }
  34. func serve() error {
  35. ln, err := net.Listen("tcp", "127.0.0.1:11434")
  36. if err != nil {
  37. return err
  38. }
  39. return server.Serve(ln)
  40. }
  41. func NewAPIClient() (*api.Client, error) {
  42. return &api.Client{
  43. URL: "http://localhost:11434",
  44. }, nil
  45. }
  46. func NewCLI() *cobra.Command {
  47. log.SetFlags(log.LstdFlags | log.Lshortfile)
  48. rootCmd := &cobra.Command{
  49. Use: "ollama",
  50. Short: "Large language model runner",
  51. CompletionOptions: cobra.CompletionOptions{
  52. DisableDefaultCmd: true,
  53. },
  54. PersistentPreRun: func(cmd *cobra.Command, args []string) {
  55. // Disable usage printing on errors
  56. cmd.SilenceUsage = true
  57. // create the models directory and it's parent
  58. if err := os.MkdirAll(path.Join(cacheDir(), "models"), 0o700); err != nil {
  59. panic(err)
  60. }
  61. },
  62. }
  63. cobra.EnableCommandSorting = false
  64. runCmd := &cobra.Command{
  65. Use: "run MODEL",
  66. Short: "Run a model",
  67. Args: cobra.ExactArgs(1),
  68. RunE: func(cmd *cobra.Command, args []string) error {
  69. return run(args[0])
  70. },
  71. }
  72. serveCmd := &cobra.Command{
  73. Use: "serve",
  74. Aliases: []string{"start"},
  75. Short: "Start ollama",
  76. RunE: func(cmd *cobra.Command, args []string) error {
  77. return serve()
  78. },
  79. }
  80. rootCmd.AddCommand(
  81. serveCmd,
  82. runCmd,
  83. )
  84. return rootCmd
  85. }