cmd.go 2.1 KB

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