model.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. dockerModel, err := manager.GetPlugin("model", s.dockerCli, &cobra.Command{})
  35. if err != nil {
  36. if errdefs.IsNotFound(err) {
  37. return fmt.Errorf("'models' support requires Docker Model plugin")
  38. }
  39. return err
  40. }
  41. cmd := exec.CommandContext(ctx, dockerModel.Path, "ls", "--json")
  42. err = s.prepareShellOut(ctx, project, cmd)
  43. if err != nil {
  44. return err
  45. }
  46. output, err := cmd.CombinedOutput()
  47. if err != nil {
  48. return fmt.Errorf("error checking available models: %w", err)
  49. }
  50. type AvailableModel struct {
  51. Id string `json:"id"`
  52. Tags []string `json:"tags"`
  53. Created int `json:"created"`
  54. }
  55. models := []AvailableModel{}
  56. err = json.Unmarshal(output, &models)
  57. if err != nil {
  58. return fmt.Errorf("error unmarshalling available models: %w", err)
  59. }
  60. var availableModels []string
  61. for _, model := range models {
  62. availableModels = append(availableModels, model.Tags...)
  63. }
  64. eg, gctx := errgroup.WithContext(ctx)
  65. eg.Go(func() error {
  66. return s.setModelVariables(gctx, dockerModel, project)
  67. })
  68. for name, config := range project.Models {
  69. if config.Name == "" {
  70. config.Name = name
  71. }
  72. eg.Go(func() error {
  73. w := progress.ContextWriter(gctx)
  74. if !slices.Contains(availableModels, config.Model) {
  75. err = s.pullModel(gctx, dockerModel, project, config, quietPull, w)
  76. if err != nil {
  77. return err
  78. }
  79. }
  80. return s.configureModel(gctx, dockerModel, project, config, w)
  81. })
  82. }
  83. return eg.Wait()
  84. }
  85. func (s *composeService) pullModel(ctx context.Context, dockerModel *manager.Plugin, project *types.Project, model types.ModelConfig, quietPull bool, w progress.Writer) error {
  86. w.Event(progress.Event{
  87. ID: model.Name,
  88. Status: progress.Working,
  89. Text: "Pulling",
  90. })
  91. cmd := exec.CommandContext(ctx, dockerModel.Path, "pull", model.Model)
  92. err := s.prepareShellOut(ctx, project, cmd)
  93. if err != nil {
  94. return err
  95. }
  96. stream, err := cmd.StdoutPipe()
  97. if err != nil {
  98. return err
  99. }
  100. err = cmd.Start()
  101. if err != nil {
  102. return err
  103. }
  104. scanner := bufio.NewScanner(stream)
  105. for scanner.Scan() {
  106. msg := scanner.Text()
  107. if msg == "" {
  108. continue
  109. }
  110. if !quietPull {
  111. w.Event(progress.Event{
  112. ID: model.Name,
  113. Status: progress.Working,
  114. Text: "Pulling",
  115. StatusText: msg,
  116. })
  117. }
  118. }
  119. err = cmd.Wait()
  120. if err != nil {
  121. w.Event(progress.ErrorMessageEvent(model.Name, err.Error()))
  122. }
  123. w.Event(progress.Event{
  124. ID: model.Name,
  125. Status: progress.Working,
  126. Text: "Pulled",
  127. })
  128. return err
  129. }
  130. func (s *composeService) configureModel(ctx context.Context, dockerModel *manager.Plugin, project *types.Project, config types.ModelConfig, w progress.Writer) error {
  131. w.Event(progress.Event{
  132. ID: config.Name,
  133. Status: progress.Working,
  134. Text: "Configuring",
  135. })
  136. // configure [--context-size=<n>] MODEL [-- <runtime-flags...>]
  137. args := []string{"configure"}
  138. if config.ContextSize > 0 {
  139. args = append(args, "--context-size", strconv.Itoa(config.ContextSize))
  140. }
  141. args = append(args, config.Model)
  142. if len(config.RuntimeFlags) != 0 {
  143. args = append(args, "--")
  144. args = append(args, config.RuntimeFlags...)
  145. }
  146. cmd := exec.CommandContext(ctx, dockerModel.Path, args...)
  147. err := s.prepareShellOut(ctx, project, cmd)
  148. if err != nil {
  149. return err
  150. }
  151. return cmd.Run()
  152. }
  153. func (s *composeService) setModelVariables(ctx context.Context, dockerModel *manager.Plugin, project *types.Project) error {
  154. cmd := exec.CommandContext(ctx, dockerModel.Path, "status", "--json")
  155. err := s.prepareShellOut(ctx, project, cmd)
  156. if err != nil {
  157. return err
  158. }
  159. statusOut, err := cmd.CombinedOutput()
  160. if err != nil {
  161. return fmt.Errorf("error checking docker-model status: %w", err)
  162. }
  163. type Status struct {
  164. Endpoint string `json:"endpoint"`
  165. }
  166. var status Status
  167. err = json.Unmarshal(statusOut, &status)
  168. if err != nil {
  169. return err
  170. }
  171. for _, service := range project.Services {
  172. for ref, modelConfig := range service.Models {
  173. model := project.Models[ref]
  174. varPrefix := strings.ReplaceAll(strings.ToUpper(ref), "-", "_")
  175. var variable string
  176. if modelConfig != nil && modelConfig.ModelVariable != "" {
  177. variable = modelConfig.ModelVariable
  178. } else {
  179. variable = varPrefix
  180. }
  181. service.Environment[variable] = &model.Model
  182. if modelConfig != nil && modelConfig.EndpointVariable != "" {
  183. variable = modelConfig.EndpointVariable
  184. } else {
  185. variable = varPrefix + "_URL"
  186. }
  187. service.Environment[variable] = &status.Endpoint
  188. }
  189. }
  190. return nil
  191. }
  192. type Model struct {
  193. Id string `json:"id"`
  194. Tags []string `json:"tags"`
  195. Created int `json:"created"`
  196. Config struct {
  197. Format string `json:"format"`
  198. Quantization string `json:"quantization"`
  199. Parameters string `json:"parameters"`
  200. Architecture string `json:"architecture"`
  201. Size string `json:"size"`
  202. } `json:"config"`
  203. }