model.go 6.4 KB

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