models.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. package server
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "os"
  8. "path"
  9. "strconv"
  10. "github.com/jmorganca/ollama/api"
  11. )
  12. // const directoryURL = "https://ollama.ai/api/models"
  13. // TODO
  14. const directoryURL = "https://raw.githubusercontent.com/jmorganca/ollama/go/models.json"
  15. type Model struct {
  16. Name string `json:"name"`
  17. DisplayName string `json:"display_name"`
  18. Parameters string `json:"parameters"`
  19. URL string `json:"url"`
  20. ShortDescription string `json:"short_description"`
  21. Description string `json:"description"`
  22. PublishedBy string `json:"published_by"`
  23. OriginalAuthor string `json:"original_author"`
  24. OriginalURL string `json:"original_url"`
  25. License string `json:"license"`
  26. }
  27. func (m *Model) FullName() string {
  28. home, err := os.UserHomeDir()
  29. if err != nil {
  30. panic(err)
  31. }
  32. return path.Join(home, ".ollama", "models", m.Name+".bin")
  33. }
  34. func pull(model string, progressCh chan<- api.PullProgress) error {
  35. remote, err := getRemote(model)
  36. if err != nil {
  37. return fmt.Errorf("failed to pull model: %w", err)
  38. }
  39. return saveModel(remote, progressCh)
  40. }
  41. func getRemote(model string) (*Model, error) {
  42. // resolve the model download from our directory
  43. resp, err := http.Get(directoryURL)
  44. if err != nil {
  45. return nil, fmt.Errorf("failed to get directory: %w", err)
  46. }
  47. defer resp.Body.Close()
  48. body, err := io.ReadAll(resp.Body)
  49. if err != nil {
  50. return nil, fmt.Errorf("failed to read directory: %w", err)
  51. }
  52. var models []Model
  53. err = json.Unmarshal(body, &models)
  54. if err != nil {
  55. return nil, fmt.Errorf("failed to parse directory: %w", err)
  56. }
  57. for _, m := range models {
  58. if m.Name == model {
  59. return &m, nil
  60. }
  61. }
  62. return nil, fmt.Errorf("model not found in directory: %s", model)
  63. }
  64. func saveModel(model *Model, progressCh chan<- api.PullProgress) error {
  65. // this models cache directory is created by the server on startup
  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(model.FullName())
  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(model.FullName(), 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. }