models.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. package server
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "net/http"
  8. "os"
  9. "path"
  10. "strconv"
  11. "github.com/jmorganca/ollama/api"
  12. )
  13. // const directoryURL = "https://ollama.ai/api/models"
  14. // TODO
  15. const directoryURL = "https://raw.githubusercontent.com/jmorganca/ollama/go/models.json"
  16. type Model struct {
  17. Name string `json:"name"`
  18. DisplayName string `json:"display_name"`
  19. Parameters string `json:"parameters"`
  20. URL string `json:"url"`
  21. ShortDescription string `json:"short_description"`
  22. Description string `json:"description"`
  23. PublishedBy string `json:"published_by"`
  24. OriginalAuthor string `json:"original_author"`
  25. OriginalURL string `json:"original_url"`
  26. License string `json:"license"`
  27. }
  28. func pull(model string, progressCh chan<- api.PullProgress) error {
  29. remote, err := getRemote(model)
  30. if err != nil {
  31. return fmt.Errorf("failed to pull model: %w", err)
  32. }
  33. return saveModel(remote, progressCh)
  34. }
  35. func getRemote(model string) (*Model, error) {
  36. // resolve the model download from our directory
  37. resp, err := http.Get(directoryURL)
  38. if err != nil {
  39. return nil, fmt.Errorf("failed to get directory: %w", err)
  40. }
  41. defer resp.Body.Close()
  42. body, err := ioutil.ReadAll(resp.Body)
  43. if err != nil {
  44. return nil, fmt.Errorf("failed to read directory: %w", err)
  45. }
  46. var models []Model
  47. err = json.Unmarshal(body, &models)
  48. if err != nil {
  49. return nil, fmt.Errorf("failed to parse directory: %w", err)
  50. }
  51. for _, m := range models {
  52. if m.Name == model {
  53. return &m, nil
  54. }
  55. }
  56. return nil, fmt.Errorf("model not found in directory: %s", model)
  57. }
  58. func saveModel(model *Model, progressCh chan<- api.PullProgress) error {
  59. // this models cache directory is created by the server on startup
  60. home, err := os.UserHomeDir()
  61. if err != nil {
  62. return fmt.Errorf("failed to get home directory: %w", err)
  63. }
  64. modelsCache := path.Join(home, ".ollama", "models")
  65. fileName := path.Join(modelsCache, model.Name+".bin")
  66. client := &http.Client{}
  67. req, err := http.NewRequest("GET", model.URL, nil)
  68. if err != nil {
  69. return fmt.Errorf("failed to download model: %w", err)
  70. }
  71. // check for resume
  72. alreadyDownloaded := int64(0)
  73. fileInfo, err := os.Stat(fileName)
  74. if err != nil {
  75. if !os.IsNotExist(err) {
  76. return fmt.Errorf("failed to check resume model file: %w", err)
  77. }
  78. // file doesn't exist, create it now
  79. } else {
  80. alreadyDownloaded = fileInfo.Size()
  81. req.Header.Add("Range", fmt.Sprintf("bytes=%d-", alreadyDownloaded))
  82. }
  83. resp, err := client.Do(req)
  84. if err != nil {
  85. return fmt.Errorf("failed to download model: %w", err)
  86. }
  87. defer resp.Body.Close()
  88. if resp.StatusCode == http.StatusRequestedRangeNotSatisfiable {
  89. // already downloaded
  90. progressCh <- api.PullProgress{
  91. Total: alreadyDownloaded,
  92. Completed: alreadyDownloaded,
  93. Percent: 100,
  94. }
  95. return nil
  96. }
  97. if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusPartialContent {
  98. return fmt.Errorf("failed to download model: %s", resp.Status)
  99. }
  100. out, err := os.OpenFile(fileName, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
  101. if err != nil {
  102. panic(err)
  103. }
  104. defer out.Close()
  105. totalSize, _ := strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64)
  106. buf := make([]byte, 1024)
  107. totalBytes := alreadyDownloaded
  108. totalSize += alreadyDownloaded
  109. for {
  110. n, err := resp.Body.Read(buf)
  111. if err != nil && err != io.EOF {
  112. return err
  113. }
  114. if n == 0 {
  115. break
  116. }
  117. if _, err := out.Write(buf[:n]); err != nil {
  118. return err
  119. }
  120. totalBytes += int64(n)
  121. // send progress updates
  122. progressCh <- api.PullProgress{
  123. Total: totalSize,
  124. Completed: totalBytes,
  125. Percent: float64(totalBytes) / float64(totalSize) * 100,
  126. }
  127. }
  128. progressCh <- api.PullProgress{
  129. Total: totalSize,
  130. Completed: totalSize,
  131. Percent: 100,
  132. }
  133. return nil
  134. }