model.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package compose
  14. import (
  15. "bufio"
  16. "context"
  17. "encoding/json"
  18. "fmt"
  19. "os/exec"
  20. "slices"
  21. "strconv"
  22. "strings"
  23. "github.com/compose-spec/compose-go/v2/types"
  24. "github.com/containerd/errdefs"
  25. "github.com/docker/cli/cli-plugins/manager"
  26. "github.com/docker/compose/v2/pkg/progress"
  27. "github.com/spf13/cobra"
  28. "golang.org/x/sync/errgroup"
  29. )
  30. func (s *composeService) ensureModels(ctx context.Context, project *types.Project, quietPull bool) error {
  31. if len(project.Models) == 0 {
  32. return nil
  33. }
  34. api, err := s.newModelAPI(project)
  35. if err != nil {
  36. return err
  37. }
  38. availableModels, err := api.ListModels(ctx)
  39. eg, ctx := errgroup.WithContext(ctx)
  40. eg.Go(func() error {
  41. return api.SetModelVariables(ctx, project)
  42. })
  43. w := progress.ContextWriter(ctx)
  44. for name, config := range project.Models {
  45. if config.Name == "" {
  46. config.Name = name
  47. }
  48. eg.Go(func() error {
  49. if !slices.Contains(availableModels, config.Model) {
  50. err = api.PullModel(ctx, config, quietPull, w)
  51. if err != nil {
  52. return err
  53. }
  54. }
  55. return api.ConfigureModel(ctx, config, w)
  56. })
  57. }
  58. return eg.Wait()
  59. }
  60. type modelAPI struct {
  61. path string
  62. env []string
  63. prepare func(ctx context.Context, cmd *exec.Cmd) error
  64. }
  65. func (s *composeService) newModelAPI(project *types.Project) (*modelAPI, error) {
  66. dockerModel, err := manager.GetPlugin("model", s.dockerCli, &cobra.Command{})
  67. if err != nil {
  68. if errdefs.IsNotFound(err) {
  69. return nil, fmt.Errorf("'models' support requires Docker Model plugin")
  70. }
  71. return nil, err
  72. }
  73. return &modelAPI{
  74. path: dockerModel.Path,
  75. prepare: func(ctx context.Context, cmd *exec.Cmd) error {
  76. return s.prepareShellOut(ctx, project.Environment, cmd)
  77. },
  78. env: project.Environment.Values(),
  79. }, nil
  80. }
  81. func (m *modelAPI) PullModel(ctx context.Context, model types.ModelConfig, quietPull bool, w progress.Writer) error {
  82. w.Event(progress.Event{
  83. ID: model.Name,
  84. Status: progress.Working,
  85. Text: "Pulling",
  86. })
  87. cmd := exec.CommandContext(ctx, m.path, "pull", model.Model)
  88. err := m.prepare(ctx, cmd)
  89. if err != nil {
  90. return err
  91. }
  92. stream, err := cmd.StdoutPipe()
  93. if err != nil {
  94. return err
  95. }
  96. err = cmd.Start()
  97. if err != nil {
  98. return err
  99. }
  100. scanner := bufio.NewScanner(stream)
  101. for scanner.Scan() {
  102. msg := scanner.Text()
  103. if msg == "" {
  104. continue
  105. }
  106. if !quietPull {
  107. w.Event(progress.Event{
  108. ID: model.Name,
  109. Status: progress.Working,
  110. Text: "Pulling",
  111. StatusText: msg,
  112. })
  113. }
  114. }
  115. err = cmd.Wait()
  116. if err != nil {
  117. w.Event(progress.ErrorMessageEvent(model.Name, err.Error()))
  118. }
  119. w.Event(progress.Event{
  120. ID: model.Name,
  121. Status: progress.Working,
  122. Text: "Pulled",
  123. })
  124. return err
  125. }
  126. func (m *modelAPI) ConfigureModel(ctx context.Context, config types.ModelConfig, w progress.Writer) error {
  127. w.Event(progress.Event{
  128. ID: config.Name,
  129. Status: progress.Working,
  130. Text: "Configuring",
  131. })
  132. // configure [--context-size=<n>] MODEL [-- <runtime-flags...>]
  133. args := []string{"configure"}
  134. if config.ContextSize > 0 {
  135. args = append(args, "--context-size", strconv.Itoa(config.ContextSize))
  136. }
  137. args = append(args, config.Model)
  138. if len(config.RuntimeFlags) != 0 {
  139. args = append(args, "--")
  140. args = append(args, config.RuntimeFlags...)
  141. }
  142. cmd := exec.CommandContext(ctx, m.path, args...)
  143. err := m.prepare(ctx, cmd)
  144. if err != nil {
  145. return err
  146. }
  147. return cmd.Run()
  148. }
  149. func (m *modelAPI) SetModelVariables(ctx context.Context, project *types.Project) error {
  150. cmd := exec.CommandContext(ctx, m.path, "status", "--json")
  151. err := m.prepare(ctx, cmd)
  152. if err != nil {
  153. return err
  154. }
  155. statusOut, err := cmd.CombinedOutput()
  156. if err != nil {
  157. return fmt.Errorf("error checking docker-model status: %w", err)
  158. }
  159. type Status struct {
  160. Endpoint string `json:"endpoint"`
  161. }
  162. var status Status
  163. err = json.Unmarshal(statusOut, &status)
  164. if err != nil {
  165. return err
  166. }
  167. for _, service := range project.Services {
  168. for ref, modelConfig := range service.Models {
  169. model := project.Models[ref]
  170. varPrefix := strings.ReplaceAll(strings.ToUpper(ref), "-", "_")
  171. var variable string
  172. if modelConfig != nil && modelConfig.ModelVariable != "" {
  173. variable = modelConfig.ModelVariable
  174. } else {
  175. variable = varPrefix + "_MODEL"
  176. }
  177. service.Environment[variable] = &model.Model
  178. if modelConfig != nil && modelConfig.EndpointVariable != "" {
  179. variable = modelConfig.EndpointVariable
  180. } else {
  181. variable = varPrefix + "_URL"
  182. }
  183. service.Environment[variable] = &status.Endpoint
  184. }
  185. }
  186. return nil
  187. }
  188. type Model struct {
  189. Id string `json:"id"`
  190. Tags []string `json:"tags"`
  191. Created int `json:"created"`
  192. Config struct {
  193. Format string `json:"format"`
  194. Quantization string `json:"quantization"`
  195. Parameters string `json:"parameters"`
  196. Architecture string `json:"architecture"`
  197. Size string `json:"size"`
  198. } `json:"config"`
  199. }
  200. func (m *modelAPI) ListModels(ctx context.Context) ([]string, error) {
  201. cmd := exec.CommandContext(ctx, m.path, "ls", "--json")
  202. err := m.prepare(ctx, cmd)
  203. if err != nil {
  204. return nil, err
  205. }
  206. output, err := cmd.CombinedOutput()
  207. if err != nil {
  208. return nil, fmt.Errorf("error checking available models: %w", err)
  209. }
  210. type AvailableModel struct {
  211. Id string `json:"id"`
  212. Tags []string `json:"tags"`
  213. Created int `json:"created"`
  214. }
  215. models := []AvailableModel{}
  216. err = json.Unmarshal(output, &models)
  217. if err != nil {
  218. return nil, fmt.Errorf("error unmarshalling available models: %w", err)
  219. }
  220. var availableModels []string
  221. for _, model := range models {
  222. availableModels = append(availableModels, model.Tags...)
  223. }
  224. return availableModels, nil
  225. }